Create a torchscript version of Tokenizer in Bert

aksem_esmani: <p>I want to create an executable version of Tokenizer for Bert - Below is a small code piece:</p>
<pre><code class="lang-auto">from transformers import AutoTokenizer, AutoModel
import torch

sentences = ['This framework generates embeddings for each input sentence']
tokenizer_model = AutoTokenizer.from_pretrained("sentence-transformers/paraphrase-mpnet-base-v2", torchscript=True)
encoded_input = tokenizer_model(sentences, padding=True, truncation=True, max_length=128, return_tensors='pt')

# !!! complains that 'tokenizer_model' doesn't have eval()
tokenizer_model.eval();    

# !!! tokenizer_model takes list of sentences as inputs, how should I provide tensorial dummpy inputs?
traced_tokenizer_model = torch.jit.trace(tokenizer_model, dummpy_inputs)
torch.jit.save(traced_tokenizer_model, "traced_tokenize_bert.pt")
</code></pre>
<p>My first problem is that <code>tokenizer_model</code> doesn’t have <code>eval()</code></p>
<p>My second problem is that the <code>tokenizer_model</code> takes as inputs a list of strings. How am I supposed to provide tensorial form dummy inputs to create the <code>traced_tokenizer_model</code>?</p>

ptrblck: <p>This question seems to be specific to the HuggingFace repository, so could you explain what <code>AutoTokenizer</code> returns? As it doesn’t seem to be a plain <code>nn.Module</code>, I guess it might be a custom class? If so, could you check if this custom object defines the expected <code>__init__</code> and <code>forward</code> methods?</p>

puranjay_mishra: <p>you will find the solution of your problem at - <a href="https://huggingface.co/transformers/torchscript.html" class="inline-onebox" rel="noopener nofollow ugc">TorchScript — transformers 3.0.2 documentation</a><br>
And can you please tell me why you are using TorchScript ?</p>

mehmetcalikus: <p>There is no answer to the question in the link you sent. I can take the traced version of Transformers-based huggingface models and use it as an inference on the cpp side. But the problem here is with the tokenizer. How can we encode texts on cpp side as similar solution is not offered in tokenizers. No documentation suggests a solution for this. When this issue is mentioned, both on github and on the huggingface forums, irrelevant answers are given and the topic is closed. The developers of 2 institutions ignore this issue.</p>

ptrblck: <p>I wouldn’t claim this issue is ignored from our side as I’ve asked for the definition of <code>AutoTokenizer</code> as well as it’s usage without any follow-up (maybe the issue was solved already by the author?).<br>
If you are hitting the same issue, feel free to post a minimal, executable code snippet and provide the necessary information which were previously asked.</p>

bethebunny: <p>Yeah this is actually a big practical issue for productionizing Huggingface models.</p>
<p>A little background:</p>
<ul>
<li>Huggingface is a model library that contains implementations of many tokenizers and transformer architectures, as well as a simple API for loading many public pretrained transformers with these architectures, and supports both Tensorflow and Torch versions of many of these models.</li>
<li>A “model” must be paired with a “tokenizer”, where the tokenizer typically takes in python strings and outputs tensors, and the model takes in the tensors output by the tokenizer and outputs tensors according to its transformer’s architecture. If a different tokenizer is used than the model was originally trained with, the model will have undefined performance and likely not produce meaningful results at all.</li>
<li>The pairing from tokenizer to model is not explicit, but is managed through the Auto* api loading from the same external path.</li>
<li>AutoTokenizer and AutoModel are not real classes and don’t need to be traced or compatible with TorchScript; they’re an API for loading in pretrained tokenizer+model pairs, and so the output type of <code>AutoTokenizer.from_pretrained</code> will depend on the serialized data of the pretrained model you’re loading, but never inherit from AutoTokenizer. The actual implementations are described <a href="https://huggingface.co/docs/transformers/v4.16.2/en/main_classes/tokenizer" rel="noopener nofollow ugc">here</a> and for instance a commonly used implementation is <a href="https://github.com/huggingface/transformers/blob/v4.16.2/src/transformers/tokenization_utils_fast.py#L76" rel="noopener nofollow ugc">PreTrainedTokenizerFast</a>.</li>
<li>Huggingface supports TorchScript export for Models (specifically some subset of their model library that has supported Torch implementations), but does <em>not</em> support TorchScript export for their tokenizers.</li>
</ul>
<p>Since the tokenizers are paired 1:1 with a model and the tokenizer can’t be serialized with TorchScript, the benefit of serializing the model with TorchScript is extremely limited; any production scenario is still going to have to identify the correct tokenizer implementation for a specific serialized model, run a full python runtime and load in that tokenizer from a separate resource, and run tokenization in that python process to produce tensors compatible with the model.</p>
<p>The concrete request here is to expand TorchScript’s python language feature coverage to support the main tokenizer implementations in Huggingface, and work with Huggingface to make sure this support is maintained as they continue to develop their library. In order to practically and sustainably productionize popular pretrained text models, TorchScript and Huggingface together should support an API something like</p>
<pre><code class="lang-auto">class TextTransformer:
  def __init__(self, path):
    self.tokenizer: PreTrainedFastTokenizer = AutoTokenizer.from_pretrained(path)
    self.model: BertModel = AutoModel.from_pretrained(path)
  def sentence_embeddings(self, sentences: list[str]) -&gt; torch.Tensor:
    tokens = self.tokenizer(sentences, padding=True, truncation=True, return_tensors="pt")
    return self.model(**tokens.to(self.model.device), return_dict=True).last_hidden_state[:, 0].cpu()

torch.jit.script(TextTransformer("s3://path-to-model")).save("serialized_text_model.pt")
</code></pre>

bethebunny: <p>Reading back through the thread I noticed your request for a “minimal, executable code snippet”, so following up to add one <img src="https://discuss.pytorch.org/images/emoji/apple/slight_smile.png?v=12" title=":slight_smile:" class="emoji" alt=":slight_smile:" loading="lazy" width="20" height="20"></p>
<pre><code class="lang-auto">&gt;&gt;&gt; import transformers
&gt;&gt;&gt; from transformers import AutoTokenizer
&gt;&gt;&gt; tokenizer = AutoTokenizer.from_pretrained('facebook/bart-large-mnli')
&gt;&gt;&gt; type(tokenizer)
&lt;class 'transformers.models.bart.tokenization_bart_fast.BartTokenizerFast'&gt;
&gt;&gt;&gt; import torch
&gt;&gt;&gt; torch.jit.script(tokenizer)
Traceback (most recent call last):
&lt;...snipped traceback for compactness&gt;
torch.jit.frontend.NotSupportedError: Compiled functions can't take variable number of arguments or use keyword-only arguments with defaults: &lt;...snipped&gt;
&gt;&gt;&gt;</code></pre>

memetrusidovski: <p>Has anyone found a solution to this problem? I’m trying to run the HuggingFace tapas tokenizer in java for my Android app, but cant get the tokenizer to work in java without rewriting all the python code from the ground up. I’m using Deep Java Library but they only support the basic tokenization like Word Piece. If there is a way to run the tokenizer and model with machine code or something, or possibly run the entire colab python code It could work</p>

alayan2: <p>Any luck here? I have found a Pytorch Lite demo project on GitHub (<a href="https://github.com/pytorch/android-demo-app/blob/master/QuestionAnswering/app/src/main/java/org/pytorch/demo/questionanswering/MainActivity.kt" rel="noopener nofollow ugc">Question Answering with DistilBert</a>) with a Kotlin function for tokenizing strings (pasted below). I haven’t experimented with that yet to test its suitability with the other models. I don’t know how specific these outputs are to their associated models so this may not be helpful.</p>
<pre><code class="lang-auto">    @Throws(QAException::class)
    private fun tokenizer(question: String, text: String): LongArray {
        val tokenIdsQuestion = wordPieceTokenizer(question)
        if (tokenIdsQuestion.size &gt;= MODEL_INPUT_LENGTH) throw QAException("Question too long")
        val tokenIdsText = wordPieceTokenizer(text)
        val inputLength = tokenIdsQuestion.size + tokenIdsText.size + EXTRA_ID_NUM
        val ids = LongArray(Math.min(MODEL_INPUT_LENGTH, inputLength))
        ids[0] = mTokenIdMap!![CLS]!!

        for (i in tokenIdsQuestion.indices) ids[i + 1] = tokenIdsQuestion[i]!!.toLong()
        ids[tokenIdsQuestion.size + 1] = mTokenIdMap!![SEP]!!
        val maxTextLength = Math.min(tokenIdsText.size, MODEL_INPUT_LENGTH - tokenIdsQuestion.size - EXTRA_ID_NUM)

        for (i in 0 until maxTextLength) {
            ids[tokenIdsQuestion.size + i + 2] = tokenIdsText[i]!!.toLong()
        }

        ids[tokenIdsQuestion.size + maxTextLength + 2] = mTokenIdMap!![SEP]!!
        return ids
    }

    private fun wordPieceTokenizer(questionOrText: String): List&lt;Long?&gt; {
        // for each token, if it's in the vocab.txt (a key in mTokenIdMap), return its Id
        // else do: a. find the largest sub-token (at least the first letter) that exists in vocab;
        // b. add "##" to the rest (even if the rest is a valid token) and get the largest sub-token "##..." that exists in vocab;
        // and c. repeat b.
        val tokenIds: MutableList&lt;Long?&gt; = ArrayList()
        val p = Pattern.compile("\\w+|\\S")
        val m = p.matcher(questionOrText)
        while (m.find()) {
            val token = m.group().toLowerCase()
            if (mTokenIdMap!!.containsKey(token)) tokenIds.add(mTokenIdMap!![token]) else {
                for (i in 0 until token.length) {
                    if (mTokenIdMap!!.containsKey(token.substring(0, token.length - i - 1))) {
                        tokenIds.add(mTokenIdMap!![token.substring(0, token.length - i - 1)])
                        var subToken = token.substring(token.length - i - 1)
                        var j = 0

                        while (j &lt; subToken.length) {
                            if (mTokenIdMap!!.containsKey("##" + subToken.substring(0, subToken.length - j))) {
                                tokenIds.add(mTokenIdMap!!["##" + subToken.substring(0, subToken.length - j)])
                                subToken = subToken.substring(subToken.length - j)
                                j = subToken.length - j
                            } else if (j == subToken.length - 1) {
                                tokenIds.add(mTokenIdMap!!["##$subToken"])
                                break
                            } else j++
                        }
                        break
                    }
                }
            }
        }
        return tokenIds
    }
</code></pre>