• Tutorials >
  • (beta) Dynamic Quantization on an LSTM Word Language Model

(beta) Dynamic Quantization on an LSTM Word Language Model

Author: James Reed

Edited by: Seth Weidman


Quantization involves converting the weights and activations of your model from float to int, which can result in smaller model size and faster inference with only a small hit to accuracy.

In this tutorial, we’ll apply the easiest form of quantization - dynamic quantization - to an LSTM-based next word-prediction model, closely following the word language model from the PyTorch examples.

# imports
import os
from io import open
import time

import torch
import torch.nn as nn
import torch.nn.functional as F

1. Define the model

Here we define the LSTM model architecture, following the model from the word language model example.

class LSTMModel(nn.Module):
    """Container module with an encoder, a recurrent module, and a decoder."""

    def __init__(self, ntoken, ninp, nhid, nlayers, dropout=0.5):
        super(LSTMModel, self).__init__()
        self.drop = nn.Dropout(dropout)
        self.encoder = nn.Embedding(ntoken, ninp)
        self.rnn = nn.LSTM(ninp, nhid, nlayers, dropout=dropout)
        self.decoder = nn.Linear(nhid, ntoken)


        self.nhid = nhid
        self.nlayers = nlayers

    def init_weights(self):
        initrange = 0.1
        self.encoder.weight.data.uniform_(-initrange, initrange)
        self.decoder.weight.data.uniform_(-initrange, initrange)

    def forward(self, input, hidden):
        emb = self.drop(self.encoder(input))
        output, hidden = self.rnn(emb, hidden)
        output = self.drop(output)
        decoded = self.decoder(output)
        return decoded, hidden

    def init_hidden(self, bsz):
        weight = next(self.parameters())
        return (weight.new_zeros(self.nlayers, bsz, self.nhid),
                weight.new_zeros(self.nlayers, bsz, self.nhid))

2. Load in the text data

Next, we load the Wikitext-2 dataset into a Corpus, again following the preprocessing from the word language model example.

class Dictionary(object):
    def __init__(self):
        self.word2idx = {}
        self.idx2word = []

    def add_word(self, word):
        if word not in self.word2idx:
            self.word2idx[word] = len(self.idx2word) - 1
        return self.word2idx[word]

    def __len__(self):
        return len(self.idx2word)

class Corpus(object):
    def __init__(self, path):
        self.dictionary = Dictionary()
        self.train = self.tokenize(os.path.join(path, 'train.txt'))
        self.valid = self.tokenize(os.path.join(path, 'valid.txt'))
        self.test = self.tokenize(os.path.join(path, 'test.txt'))

    def tokenize(self, path):
        """Tokenizes a text file."""
        assert os.path.exists(path)
        # Add words to the dictionary
        with open(path, 'r', encoding="utf8") as f:
            for line in f:
                words = line.split() + ['<eos>']
                for word in words:

        # Tokenize file content
        with open(path, 'r', encoding="utf8") as f:
            idss = []
            for line in f:
                words = line.split() + ['<eos>']
                ids = []
                for word in words:
            ids = torch.cat(idss)

        return ids

model_data_filepath = 'data/'

corpus = Corpus(model_data_filepath + 'wikitext-2')

3. Load the pre-trained model

This is a tutorial on dynamic quantization, a quantization technique that is applied after a model has been trained. Therefore, we’ll simply load some pre-trained weights into this model architecture; these weights were obtained by training for five epochs using the default settings in the word language model example.

ntokens = len(corpus.dictionary)

model = LSTMModel(
    ntoken = ntokens,
    ninp = 512,
    nhid = 256,
    nlayers = 5,

        model_data_filepath + 'word_language_model_quantize.pth',



  (drop): Dropout(p=0.5, inplace=False)
  (encoder): Embedding(33278, 512)
  (rnn): LSTM(512, 256, num_layers=5, dropout=0.5)
  (decoder): Linear(in_features=256, out_features=33278, bias=True)

Now let’s generate some text to ensure that the pre-trained model is working properly - similarly to before, we follow here

input_ = torch.randint(ntokens, (1, 1), dtype=torch.long)
hidden = model.init_hidden(1)
temperature = 1.0
num_words = 1000

with open(model_data_filepath + 'out.txt', 'w') as outf:
    with torch.no_grad():  # no tracking history
        for i in range(num_words):
            output, hidden = model(input_, hidden)
            word_weights = output.squeeze().div(temperature).exp().cpu()
            word_idx = torch.multinomial(word_weights, 1)[0]

            word = corpus.dictionary.idx2word[word_idx]

            outf.write(str(word.encode('utf-8')) + ('\n' if i % 20 == 19 else ' '))

            if i % 100 == 0:
                print('| Generated {}/{} words'.format(i, 1000))

with open(model_data_filepath + 'out.txt', 'r') as outf:
    all_output = outf.read()


| Generated 0/1000 words
| Generated 100/1000 words
| Generated 200/1000 words
| Generated 300/1000 words
| Generated 400/1000 words
| Generated 500/1000 words
| Generated 600/1000 words
| Generated 700/1000 words
| Generated 800/1000 words
| Generated 900/1000 words
b'where' b'and' b'if' b'that' b'Ukraine' b',' b'the' b'spread' b'was' b'stable' b'\xe2\x80\x94' b'there' b'has' b'not' b'been' b'described' b'as' b'often' b'deadly' b','
b'giving' b'a' b'principles' b'that' b'could' b'establish' b'valid' b'or' b'continue' b'to' b'remain' b'an' b'series' b'there' b'had' b'been' b'dishes' b'following' b'<unk>' b'first'
b'after' b'on' b'a' b'kind' b'he' b'instructs' b'iris' b'.' b'One' b'of' b'these' b'books' b'showed' b'Boise' b'State' b'is' b'always' b'routed' b'into' b'violence'
b'with' b'a' b'cabinet' b'.' b'He' b'is' b'the' b'Lucas' b'of' b'the' b'<unk>' b'goddess' b',' b'state' b'in' b'1932' b'causes' b'direct' b'main' b'and'
b'creativity' b',' b'led' b'by' b'the' b'Nagoya' b'starling' b'system' b'(' b'Pure' b')' b'in' b'December' b'1918' b',' b'challenged' b'the' b'critique' b'of' b'the'
b'Museum' b'relaunched' b'in' b'the' b'former' b'<unk>' b'<unk>' b'and' b'Vol' b';' b'they' b'are' b'eventually' b'considered' b'.' b'Bell' b'created' b'that' b'interests' b'of'
b'theory' b'had' b'a' b'advantage' b'covers' b'about' b'24' b'%' b'.' b'Once' b'only' b'game' b'inventory' b'companion' b',' b'they' b'were' b'supplied' b'by' b'you'
b'according' b'to' b'John' b'Leonard' b'Alfred' b'Ferguson' b'from' b'Fife' b',' b'they' b'was' b'formally' b'also' b'felt' b'to' b'come' b'its' b'own' b'theorists' b'.'
b'Others' b'were' b'rival' b'that' b'poor' b'rains' b'lacked' b'his' b'relative' b'variety' b'at' b'a' b'detail' b'in' b'the' b'2011' b'edition' b'of' b'Fame' b'('
b'\xe2\x80\x93' b'1' b')' b',' b'and' b'was' b'due' b'to' b'digital' b'or' b'other' b'other' b'philosophies' b',' b'three' b'I' b'in' b'which' b'the' b'Underground'
b'took' b'a' b'extended' b'career' b'ill' b',' b'branded' b'29' b'@.@' b'8' b'%' b'per' b'hour' b'.' b'Some' b'of' b'rituals' b'unsuccessfully' b'has' b'return'
b'to' b'support' b'moulded' b'each' b'developments' b'of' b'sir' b'each' b'year' b'.' b'Casey' b'ratified' b'outside' b'Grande' b'sexpunctatus' b'of' b'fresh' b'Vig' b'.' b'Some'
b'opposition' b'to' b'only' b'a' b'British' b'particle' b'version' b',' b'but' b'word' b'up' b'there' b'such' b'more' b'difficult' b'to' b'appropriate' b'<eos>' b'<eos>' b'Points'
b'of' b'medical' b'<unk>' b'to' b'determines' b'books' b'or' b'higher' b',' b'taking' b'the' b'slick' b'language' b'or' b'guardian' b'for' b'the' b'species' b',' b'with'
b'his' b'ability' b'to' b'return' b'respected' b'into' b'Dirt' b',' b'Mesopotamia' b"'" b'languid' b'corpse' b',' b'incompetent' b'\xe2\x80\x99' b's' b'doubt' b'or' b'<unk>' b'.'
b'Throughout' b'Hornung' b"'s" b'death' b'with' b'Bolton' b':' b'Entertainment' b'nests' b'on' b'school' b',' b'the' b'galaxy' b'that' b'exhausted' b'every' b'account' b'of' b'Statistics'
b'by' b'supporter' b',' b'and' b'parasites' b'to' b'be' b'a' b'additional' b'part' b'of' b'<unk>' b'.' b'"' b'Henson' b'Shapur' b'was' b'all' b'box' b'.'
b'"' b'(' b'throwing' b'solvent' b'some' b'121' b"'" b'universities' b')' b'can' b'be' b'written' b'.' b'It' b'states' b'that' b'"' b'and' b'just' b'be'
b'to' b'have' b'one' b'of' b'his' b'biggest' b'services' b'.' b'Then' b'with' b'pad' b'<unk>' b'<unk>' b'makes' b'figures' b'from' b'an' b'living' b'tone' b'near'
b'king' b',' b'but' b'correlation' b'his' b'right' b'for' b'them' b'on' b'human' b'website' b';' b'they' b"'ve" b'always' b'seen' b'mounts' b'down' b'and' b'if'
b'these' b'rich' b'education' b'shall' b'have' b'their' b'game' b'as' b'this' b'intended' b'.' b'Once' b'of' b'you' b',' b'you' b'is' b'almost' b'sentimental' b'and'
b'<unk>' b'?' b'Ross' b'is' b'more' b'of' b'we' b'really' b'can' b'better' b'work' b'to' b'be' b'important' b'to' b'"' b'.' b'Up' b'Semaphore' b'in'
b'2006' b'Raven' b'wrote' b'that' b'dam' b'details' b'"' b'quite' b'<unk>' b'"' b',' b'so' b'personally' b'told' b'The' b'134' b'a' b':' b'<unk>' b'he'
b'responded' b'for' b'a' b'regular' b'side' b',' b'and' b'outweighed' b'a' b'suspect' b'or' b'clearly' b'<unk>' b'the' b'Schmoke' b"'s" b'leg' b'will' b'be' b'rational'
b'.' b'Chen' b'scattered' b'into' b'a' b'special' b'setting' b',' b'and' b'in' b'Dublin' b'culprits' b'issued' b'just' b'a' b'decisive' b'experience' b'at' b'inscribed' b'Roxas'
b'and' b'titles' b'on' b'networks' b'at' b'the' b'suburb' b'of' b'<unk>' b'bowling' b'as' b'The' b'meat' b'found' b'under' b'often' b'because' b'his' b'son' b'has'
b'not' b'affect' b'another' b'ship' b'of' b'mind' b'.' b'<eos>' b'The' b'eleventh' b'move' b'came' b'from' b'the' b'Edberg' b'Graphic' b'Sun' b',' b'<unk>' b'Claire'
b'and' b'Thomas' b'<unk>' b'.' b'By' b'the' b'beginning' b'of' b'the' b'Australian' b'version' b'of' b'Doyle' b'believes' b'ca' b'the' b'two' b'sources' b'after' b'misses'
b'moved' b'to' b'any' b'calls' b'.' b'I' b'have' b'been' b'<unk>' b'as' b'the' b'city' b'and' b'by' b'thirteen' b'films' b';' b'writers' b'pressure' b'dealing'
b'in' b'privately' b'sheer' b'Raffles' b'and' b'marry' b'rights' b';' b'they' b'really' b'wanted' b'to' b'affect' b'style' b'.' b'<eos>' b'A' b'writer' b',' b'a'
b'writer' b'whose' b'friend' b'in' b'Dress' b'and' b'his' b'kingdom' b'is' b'unknown' b'.' b'The' b'PlayStation' b'Kingdom' b'believes' b'at' b'the' b'conclusion' b'is' b'easily'
b'used' b'.' b'The' b'author' b'also' b'scored' b'disturbed' b'<unk>' b':' b'a' b'clash' b'with' b'finding' b',' b'and' b'friends' b'originally' b'being' b'"' b'sometimes'
b'very' b'small' b',' b'and' b'considered' b'here' b',' b'he' b'cut' b'yet' b'a' b'few' b'episode' b',' b'because' b'his' b'solo' b'have' b'not' b'unknowingly'
b'reported' b'to' b'get' b'step' b'to' b'gallinae' b'for' b'an' b'bit' b'than' b'a' b'could' b'so' b'on' b'almost' b'it' b'.' b'"' b'Walpole' b'ruled'
b'Liu' b"'Malley" b'tied' b'"' b'a' b'real' b'atmosphere' b'I' b"'m" b'required' b',' b'"' b'so' b'"' b'(' b'normal' b'in' b'us' b'to' b'a'
b'country' b'"' b')' b'appears' b'about' b'1820' b'replied' b'and' b'that' b'"' b'something' b'the' b'Whites' b"'s" b'rectory' b'players' b'may' b'run' b'.' b'"'
b'<eos>' b'After' b'Human' b'<unk>' b"'s" b'fictional' b'mission' b',' b'O' b"'Malley" b'inherited' b'an' b'equal' b'reception' b'in' b'heavily' b'three' b'who' b'won' b'it'
b'with' b'one' b'intellectual' b'harm' b'he' b'read' b'backhand' b'Hollywood' b'.' b'Chen' b'then' b'cast' b'his' b'adventures' b'"' b'Jesus' b'"' b'said' b'"' b'The'
b'Big' b'Day' b'"' b',' b'in' b'which' b'"' b'Michael' b'Warnock' b'went' b'to' b'tobacco' b'...' b'to' b'make' b'the' b'funeral' b'so' b'replicated' b'him'
b'on' b'his' b'<unk>' b'"' b'.' b'The' b'help' b'was' b'an' b'post' b'@-@' b'reminder' b'which' b'gives' b'five' b'false' b'economical' b'released' b'by' b'players'
b'and' b'other' b'literature' b'to' b'complete' b'them' b'with' b'Campbeltown' b"'s" b'bowler' b"'s" b'assassination' b'.' b'He' b'performed' b'Queen' b'O' b"'Malley" b'to' b'accept'
b'at' b'O' b'Diego' b'shows' b'his' b'house' b',' b'which' b'appeared' b'two' b'years' b'later' b'.' b'The' b'officers' b'for' b'stunt' b'basic' b'scenes' b'were'
b'<unk>' b',' b'and' b'1960' b',' b'suggesting' b'that' b'Frank' b'convinces' b'on' b'1682' b'.' b'<eos>' b'The' b'theme' b'of' b'philosophy' b',' b'with' b'evidence'
b'of' b'historical' b'interest' b',' b'first' b'journalists' b'as' b'which' b'Henry' b';' b'they' b'were' b'upset' b'43' b'or' b'eight' b'.' b'The' b'game' b'faced'
b'to' b'the' b'Augustan' b'DS' b',' b'Leopard' b'\xe2\x80\x93' b'Santiago' b',' b'while' b'Charlotte' b'statements' b'values' b'that' b'keeping' b'any' b'of' b'his' b'drinking' b'policy'
b'like' b'an' b'believer' b'up' b'by' b'sales' b'to' b'be' b'killed' b'natural' b'kids' b'.' b'On' b'the' b'period' b'of' b'Mann' b',' b'in' b'their'
b'contrary' b'to' b'the' b'Japanese' b'@-@' b'wars' b':' b'The' b'Thanhouser' b'Sun' b'that' b'I' b'saw' b'their' b'military' b'school' b'orange' b'concern' b'before' b'a'
b'<unk>' b'poor' b',' b'it' b'was' b'called' b'a' b'<unk>' b'book' b'is' b'lost' b'to' b'the' b'bond' b',' b'announced' b'it' b'too' b'two' b'writers'
b'died' b',' b'by' b'humour' b'in' b'debates' b'a' b'weekly' b'lining' b',' b'<unk>' b'critic' b"'Oc" b'Ray' b'Chapman' b',' b'<unk>' b'<unk>' b',' b'and'
b'Rodman' b'<unk>' b',' b'but' b'in' b'its' b'First' b'Hollywood' b'Film' b'Had' b'in' b'South' b'America' b'in' b'Delhi' b'required' b'a' b'works' b'.' b'There'

It’s no GPT-2, but it looks like the model has started to learn the structure of language!

We’re almost ready to demonstrate dynamic quantization. We just need to define a few more helper functions:

bptt = 25
criterion = nn.CrossEntropyLoss()
eval_batch_size = 1

# create test data set
def batchify(data, bsz):
    # Work out how cleanly we can divide the dataset into bsz parts.
    nbatch = data.size(0) // bsz
    # Trim off any extra elements that wouldn't cleanly fit (remainders).
    data = data.narrow(0, 0, nbatch * bsz)
    # Evenly divide the data across the bsz batches.
    return data.view(bsz, -1).t().contiguous()

test_data = batchify(corpus.test, eval_batch_size)

# Evaluation functions
def get_batch(source, i):
    seq_len = min(bptt, len(source) - 1 - i)
    data = source[i:i+seq_len]
    target = source[i+1:i+1+seq_len].view(-1)
    return data, target

def repackage_hidden(h):
  """Wraps hidden states in new Tensors, to detach them from their history."""

  if isinstance(h, torch.Tensor):
      return h.detach()
      return tuple(repackage_hidden(v) for v in h)

def evaluate(model_, data_source):
    # Turn on evaluation mode which disables dropout.
    total_loss = 0.
    hidden = model_.init_hidden(eval_batch_size)
    with torch.no_grad():
        for i in range(0, data_source.size(0) - 1, bptt):
            data, targets = get_batch(data_source, i)
            output, hidden = model_(data, hidden)
            hidden = repackage_hidden(hidden)
            output_flat = output.view(-1, ntokens)
            total_loss += len(data) * criterion(output_flat, targets).item()
    return total_loss / (len(data_source) - 1)

4. Test dynamic quantization

Finally, we can call torch.quantization.quantize_dynamic on the model! Specifically,

  • We specify that we want the nn.LSTM and nn.Linear modules in our model to be quantized

  • We specify that we want weights to be converted to int8 values

import torch.quantization

quantized_model = torch.quantization.quantize_dynamic(
    model, {nn.LSTM, nn.Linear}, dtype=torch.qint8


  (drop): Dropout(p=0.5, inplace=False)
  (encoder): Embedding(33278, 512)
  (rnn): DynamicQuantizedLSTM(512, 256, num_layers=5, dropout=0.5)
  (decoder): DynamicQuantizedLinear(in_features=256, out_features=33278, dtype=torch.qint8, qscheme=torch.per_tensor_affine)

The model looks the same; how has this benefited us? First, we see a significant reduction in model size:

def print_size_of_model(model):
    torch.save(model.state_dict(), "temp.p")
    print('Size (MB):', os.path.getsize("temp.p")/1e6)



Size (MB): 113.945562
Size (MB): 79.739752

Second, we see faster inference time, with no difference in evaluation loss:

Note: we number of threads to one for single threaded comparison, since quantized models run single threaded.


def time_model_evaluation(model, test_data):
    s = time.time()
    loss = evaluate(model, test_data)
    elapsed = time.time() - s
    print('''loss: {0:.3f}\nelapsed time (seconds): {1:.1f}'''.format(loss, elapsed))

time_model_evaluation(model, test_data)
time_model_evaluation(quantized_model, test_data)


loss: 5.167
elapsed time (seconds): 176.9
loss: 5.168
elapsed time (seconds): 115.9

Running this locally on a MacBook Pro, without quantization, inference takes about 200 seconds, and with quantization it takes just about 100 seconds.


Dynamic quantization can be an easy way to reduce model size while only having a limited effect on accuracy.

Thanks for reading! As always, we welcome any feedback, so please create an issue here if you have any.

Total running time of the script: ( 5 minutes 0.089 seconds)

Gallery generated by Sphinx-Gallery

이 문서가 도움이 되었나요?
피드백을 주셔서 감사합니다.

© Copyright 2019, PyTorch.

Built with Sphinx using a theme provided by Read the Docs.


Access comprehensive developer documentation for PyTorch

View Docs


Get in-depth tutorials for beginners and advanced developers

View Tutorials


Find development resources and get your questions answered

View Resources