# Fun with Hidden Markov Models
*by Loren Lugosch*

This notebook introduces the Hidden Markov Model (HMM), a simple model for sequential data.

We will see:
- what an HMM is and when you might want to use it;
- the so-called "three problems" of an HMM; and 
- how to implement an HMM in PyTorch.

(The code in this notebook can also be found at https://github.com/lorenlugosch/pytorch_HMM.)

A hypothetical scenario
------

To motivate the use of HMMs, imagine that you have a friend who gets to do a lot of travelling. Every day, this jet-setting friend sends you a selfie from the city they’re in, to make you envious.

<center>


</center>





How would you go about guessing which city the friend is in each day, just by looking at the selfies?

If the selfie contains a really obvious landmark, like the Eiffel Tower, it will be easy to figure out where the photo was taken. If not, it will be a lot harder to infer the city.

But we have a clue to help us: the city the friend is in each day is not totally random. For example, the friend will probably remain in the same city for a few days to sightsee before flying to a new city.

## The HMM setup

The hypothetical scenario of the friend travelling between cities and sending you selfies can be modeled using an HMM.


An HMM models a system that is in a particular state at any given time and produces an output that depends on that state. 

At each timestep or clock tick, the system randomly decides on a new state and jumps into that state. The system then randomly generates an observation. The states are "hidden": we can't observe them. (In the cities/selfies analogy, the unknown cities would be the hidden states, and the selfies would be the observations.)

Let's denote the sequence of states as $\mathbf{z} = \{z_1, z_2, \dots, z_T \}$, where each state is one of a finite set of $N$ states, and the sequence of observations as $\mathbf{x} = \{x_1, x_2, \dots, x_T\}$. The observations could be discrete, like letters, or real-valued, like audio frames.

<center>


</center>

An HMM makes two key assumptions:
- **Assumption 1:** The state at time $t$ depends *only* on the state at the previous time $t-1$. 
- **Assumption 2:** The output at time $t$ depends *only* on the state at time $t$.

These two assumptions make it possible to efficiently compute certain quantities that we may be interested in.

## Components of an HMM
An HMM has three sets of trainable parameters.
  


- The **transition model** is a square matrix $A$, where $A_{s, s'}$ represents $p(z_t = s|z_{t-1} = s')$, the probability of jumping from state $s'$ to state $s$. 

- The **emission model** $b_s(x_t)$ tells us $p(x_t|z_t = s)$, the probability of generating $x_t$ when the system is in state $s$. For discrete observations, which we will use in this notebook, the emission model is just a lookup table, with one row for each state, and one column for each observation. For real-valued observations, it is common to use a Gaussian mixture model or neural network to implement the emission model. 

- The **state priors** tell us $p(z_1 = s)$, the probability of starting in state $s$. We use $\pi$ to denote the vector of state priors, so $\pi_s$ is the state prior for state $s$.

Let's program an HMM class in PyTorch.


```
import torch
import numpy as np

class HMM(torch.nn.Module):
  """
  Hidden Markov Model with discrete observations.
  """
  def __init__(self, M, N):
    super(HMM, self).__init__()
    self.M = M # number of possible observations
    self.N = N # number of states

    # A
    self.transition_model = TransitionModel(self.N)

    # b(x_t)
    self.emission_model = EmissionModel(self.N,self.M)

    # pi
    self.unnormalized_state_priors = torch.nn.Parameter(torch.randn(self.N))

    # use the GPU
    self.is_cuda = torch.cuda.is_available()
    if self.is_cuda: self.cuda()

class TransitionModel(torch.nn.Module):
  def __init__(self, N):
    super(TransitionModel, self).__init__()
    self.N = N
    self.unnormalized_transition_matrix = torch.nn.Parameter(torch.randn(N,N))

class EmissionModel(torch.nn.Module):
  def __init__(self, N, M):
    super(EmissionModel, self).__init__()
    self.N = N
    self.M = M
    self.unnormalized_emission_matrix = torch.nn.Parameter(torch.randn(N,M))
```

To sample from the HMM, we start by picking a random initial state from the state prior distribution.

Then, we sample an output from the emission distribution, sample a transition from the transition distribution, and repeat.

(Notice that we pass the unnormalized model parameters through a softmax function to make them into probabilities.)



```
def sample(self, T=10):
  state_priors = torch.nn.functional.softmax(self.unnormalized_state_priors, dim=0)
  transition_matrix = torch.nn.functional.softmax(self.transition_model.unnormalized_transition_matrix, dim=1)
  emission_matrix = torch.nn.functional.softmax(self.emission_model.unnormalized_emission_matrix, dim=1)

  # sample initial state
  z_t = torch.distributions.categorical.Categorical(state_priors).sample().item()
  z = []; x = []
  z.append(z_t)
  for t in range(0,T):
    # sample emission
    x_t = torch.distributions.categorical.Categorical(emission_matrix[z_t]).sample().item()
    x.append(x_t)

    # sample transition
    z_t = torch.distributions.categorical.Categorical(transition_matrix[:,z_t]).sample().item()
    if t < T-1: z.append(z_t)

  return x, z

# Add the sampling method to our HMM class
HMM.sample = sample
```

Let's try hard-coding an HMM for generating fake words. (We'll also add some helper functions for encoding and decoding strings.)

We will assume that the system has one state for generating vowels and one state for generating consonants, and the transition matrix has 0s on the diagonal---in other words, the system cannot stay in the vowel state or the consonant state for one than one timestep; it has to switch.

Since we pass the transition matrix through a softmax, to get 0s we set the unnormalized parameter values to $-\infty$.


```
import string
alphabet = string.ascii_lowercase

def encode(s):
  """
  Convert a string into a list of integers
  """
  x = [alphabet.index(ss) for ss in s]
  return x

def decode(x):
  """
  Convert list of ints to string
  """
  s = "".join([alphabet[xx] for xx in x])
  return s

# Initialize the model
model = HMM(M=len(alphabet), N=2) 

# Hard-wiring the parameters!
# Let state 0 = consonant, state 1 = vowel
model.unnormalized_state_priors[0] = 0.    # Let's start with a consonant more frequently
model.unnormalized_state_priors[1] = -0.5
print("State priors:", torch.nn.functional.softmax(model.unnormalized_state_priors, dim=0))

# In state 0, only allow consonants; in state 1, only allow vowels
vowel_indices = torch.tensor([alphabet.index(letter) for letter in "aeiou"])
consonant_indices = torch.tensor([alphabet.index(letter) for letter in "bcdfghjklmnpqrstvwxyz"])
model.emission_model.unnormalized_emission_matrix[0, vowel_indices] = -np.inf
model.emission_model.unnormalized_emission_matrix[1, consonant_indices] = -np.inf 
print("Emission matrix:", torch.nn.functional.softmax(model.emission_model.unnormalized_emission_matrix, dim=1))

# Only allow vowel -> consonant and consonant -> vowel
model.transition_model.unnormalized_transition_matrix[0,0] = -np.inf  # consonant -> consonant
model.transition_model.unnormalized_transition_matrix[0,1] = 0.       # vowel -> consonant
model.transition_model.unnormalized_transition_matrix[1,0] = 0.       # consonant -> vowel
model.transition_model.unnormalized_transition_matrix[1,1] = -np.inf  # vowel -> vowel
print("Transition matrix:", torch.nn.functional.softmax(model.transition_model.unnormalized_transition_matrix, dim=1))


```

    State priors: tensor([0.6225, 0.3775], device='cuda:0', grad_fn=<SoftmaxBackward>)
    Emission matrix: tensor([[0.0000, 0.1565, 0.0253, 0.0934, 0.0000, 0.0126, 0.0238, 0.0468, 0.0000,
             0.0162, 0.1639, 0.1366, 0.0172, 0.0301, 0.0000, 0.0342, 0.0071, 0.0065,
             0.0322, 0.0313, 0.0000, 0.0080, 0.0368, 0.0281, 0.0539, 0.0396],
            [0.0508, 0.0000, 0.0000, 0.0000, 0.1702, 0.0000, 0.0000, 0.0000, 0.2490,
             0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0348, 0.0000, 0.0000, 0.0000,
             0.0000, 0.0000, 0.4951, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000]],
           device='cuda:0', grad_fn=<SoftmaxBackward>)
    Transition matrix: tensor([[0., 1.],
            [1., 0.]], device='cuda:0', grad_fn=<SoftmaxBackward>)


Try sampling from our hard-coded model:



```
# Sample some outputs
for _ in range(4):
  sampled_x, sampled_z = model.sample(T=5)
  print("x:", decode(sampled_x))
  print("z:", sampled_z)
```

    x: buyup
    z: [0, 1, 0, 1, 0]
    x: enabe
    z: [1, 0, 1, 0, 1]
    x: zehuk
    z: [0, 1, 0, 1, 0]
    x: xuliy
    z: [0, 1, 0, 1, 0]


## The Three Problems

In a [classic tutorial](https://www.cs.cmu.edu/~cga/behavior/rabiner1.pdf) on HMMs, Lawrence Rabiner describes "three problems" that need to be solved before you can effectively use an HMM. They are:
- Problem 1: How do we efficiently compute $p(\mathbf{x})$?
- Problem 2: How do we find the most likely state sequence $\mathbf{z}$ that could have generated the data? 
- Problem 3: How do we train the model?

In the rest of the notebook, we will see how to solve each problem and implement the solutions in PyTorch.

### Problem 1: How do we compute $p(\mathbf{x})$?


#### *Why?*
Why might we care about computing $p(\mathbf{x})$? Here's two reasons.
* Given two HMMs, $\theta_1$ and $\theta_2$, we can compute the likelihood of some data $\mathbf{x}$ under each model, $p_{\theta_1}(\mathbf{x})$ and $p_{\theta_2}(\mathbf{x})$, to decide which model is a better fit to the data. 

  (For example, given an HMM for English speech and an HMM for French speech, we could compute the likelihood given each model, and pick the model with the higher likelihood to infer whether the person is speaking English or French.)
* Being able to compute $p(\mathbf{x})$ gives us a way to train the model, as we will see later.

#### *How?*
Given that we want $p(\mathbf{x})$, how do we compute it?

We've assumed that the data is generated by visiting some sequence of states $\mathbf{z}$ and picking an output $x_t$ for each $z_t$ from the emission distribution $p(x_t|z_t)$. So if we knew $\mathbf{z}$, then the probability of $\mathbf{x}$ could be computed as follows:

$$p(\mathbf{x}|\mathbf{z}) = \prod_{t} p(x_t|z_t) p(z_t|z_{t-1})$$

However, we don't know $\mathbf{z}$; it's hidden. But we do know the probability of any given $\mathbf{z}$, independent of what we observe. So we could get the probability of $\mathbf{x}$ by summing over the different possibilities for $\mathbf{z}$, like this:

$$p(\mathbf{x}) = \sum_{\mathbf{z}} p(\mathbf{x}|\mathbf{z}) p(\mathbf{z}) = \sum_{\mathbf{z}} \prod_{t} p(x_t|z_t) p(z_t|z_{t-1})$$

The problem is: if you try to take that sum directly, you will need to compute $N^T$ terms. This is impossible to do for anything but very short sequences. For example, let's say the sequence is of length $T=100$ and there are $N=2$ possible states. Then we would need to check $N^T = 2^{100} \approx 10^{30}$ different possible state sequences.

We need a way to compute $p(\mathbf{x})$ that doesn't require us to explicitly calculate all $N^T$ terms. For this, we use the forward algorithm.

________

<u><b>The Forward Algorithm</b></u>

> for $s=1 \rightarrow N$:\
> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$\alpha_{s,1} := b_s(x_1) \cdot \pi_s$ 
> 
> for $t = 2 \rightarrow T$:\
> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;for $s = 1 \rightarrow N$:\
> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
> $\alpha_{s,t} := b_s(x_t) \cdot \underset{s'}{\sum} A_{s, s'} \cdot \alpha_{s',t-1} $
> 
> $p(\mathbf{x}) := \underset{s}{\sum} \alpha_{s,T}$\
> return $p(\mathbf{x})$
________


The forward algorithm is much faster than enumerating all $N^T$ possible state sequences: it requires only $O(N^2T)$ operations to run, since each step is mostly multiplying the vector of forward variables by the transition matrix. (And very often we can reduce that complexity even further, if the transition matrix is sparse.)

There is one practical problem with the forward algorithm as presented above: it is prone to underflow due to multiplying a long chain of small numbers, since probabilities are always between 0 and 1. Instead, let's do everything in the log domain. In the log domain, a multiplication becomes a sum, and a sum becomes a [logsumexp](https://en.wikipedia.org/wiki/LogSumExp).  

________

<u><b>The Forward Algorithm (Log Domain)</b></u>

> for $s=1 \rightarrow N$:\
> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$\text{log }\alpha_{s,1} := \text{log }b_s(x_1) + \text{log }\pi_s$ 
> 
> for $t = 2 \rightarrow T$:\
> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;for $s = 1 \rightarrow N$:\
> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
> $\text{log }\alpha_{s,t} := \text{log }b_s(x_t) +  \underset{s'}{\text{logsumexp}} \left( \text{log }A_{s, s'} + \text{log }\alpha_{s',t-1} \right)$
> 
> $\text{log }p(\mathbf{x}) := \underset{s}{\text{logsumexp}} \left( \text{log }\alpha_{s,T} \right)$\
> return $\text{log }p(\mathbf{x})$
________

Now that we have a numerically stable version of the forward algorithm, let's implement it in PyTorch. 


```
def HMM_forward(self, x, T):
  """
  x : IntTensor of shape (batch size, T_max)
  T : IntTensor of shape (batch size)

  Compute log p(x) for each example in the batch.
  T = length of each example
  """
  if self.is_cuda:
  	x = x.cuda()
  	T = T.cuda()

  batch_size = x.shape[0]; T_max = x.shape[1]
  log_state_priors = torch.nn.functional.log_softmax(self.unnormalized_state_priors, dim=0)
  log_alpha = torch.zeros(batch_size, T_max, self.N)
  if self.is_cuda: log_alpha = log_alpha.cuda()

  log_alpha[:, 0, :] = self.emission_model(x[:,0]) + log_state_priors
  for t in range(1, T_max):
    log_alpha[:, t, :] = self.emission_model(x[:,t]) + self.transition_model(log_alpha[:, t-1, :])

  # Select the sum for the final timestep (each x may have different length).
  log_sums = log_alpha.logsumexp(dim=2)
  log_probs = torch.gather(log_sums, 1, T.view(-1,1) - 1)
  return log_probs

def emission_model_forward(self, x_t):
  log_emission_matrix = torch.nn.functional.log_softmax(self.unnormalized_emission_matrix, dim=1)
  out = log_emission_matrix[:, x_t].transpose(0,1)
  return out

def transition_model_forward(self, log_alpha):
  """
  log_alpha : Tensor of shape (batch size, N)
  Multiply previous timestep's alphas by transition matrix (in log domain)
  """
  log_transition_matrix = torch.nn.functional.log_softmax(self.unnormalized_transition_matrix, dim=1)

  # Matrix multiplication in the log domain
  out = log_domain_matmul(log_transition_matrix, log_alpha.transpose(0,1)).transpose(0,1)
  return out

def log_domain_matmul(log_A, log_B):
	"""
	log_A : m x n
	log_B : n x p
	output : m x p matrix

	Normally, a matrix multiplication
	computes out_{i,j} = sum_k A_{i,k} x B_{k,j}

	A log domain matrix multiplication
	computes out_{i,j} = logsumexp_k log_A_{i,k} + log_B_{k,j}
	"""
	m = log_A.shape[0]
	n = log_A.shape[1]
	p = log_B.shape[1]

	log_A_expanded = torch.stack([log_A] * p, dim=2)
	log_B_expanded = torch.stack([log_B] * m, dim=0)

	elementwise_sum = log_A_expanded + log_B_expanded
	out = torch.logsumexp(elementwise_sum, dim=1)

	return out

TransitionModel.forward = transition_model_forward
EmissionModel.forward = emission_model_forward
HMM.forward = HMM_forward
```

Try running the forward algorithm on our vowels/consonants model from before:


```
x = torch.stack( [torch.tensor(encode("cat"))] )
T = torch.tensor([3])
print(model.forward(x, T))

x = torch.stack( [torch.tensor(encode("aba")), torch.tensor(encode("abb"))] )
T = torch.tensor([3,3])
print(model.forward(x, T))
```

    tensor([[-10.5923]], device='cuda:0', grad_fn=<GatherBackward>)
    tensor([[-8.7869],
            [   -inf]], device='cuda:0', grad_fn=<GatherBackward>)


When using the vowel <-> consonant HMM from above, notice that the forward algorithm returns $-\infty$ for $\mathbf{x} = \text{"abb"}$. That's because our transition matrix says the probability of vowel -> vowel and consonant -> consonant is 0, so the probability of $\text{"abb"}$ happening is 0, and thus the log probability is $-\infty$.

#### *Side note: deriving the forward algorithm*

If you're interested in understanding how the forward algorithm actually computes $p(\mathbf{x})$, read this section; if not, skip to the next part on "Problem 2" (finding the most likely state sequence).



To derive the forward algorithm, start by deriving the forward variable:

$$\begin{align} 
    \alpha_{s,t} &= p(x_1, x_2, \dots, x_t, z_t=s) \\
     &= p(x_t | x_1, x_2, \dots, x_{t-1}, z_t = s) \cdot p(x_1, x_2, \dots, x_{t-1}, z_t = s)  \\ 
    &= p(x_t | z_t = s) \cdot p(x_1, x_2, \dots, x_{t-1}, z_t = s) \\
    &= p(x_t | z_t = s) \cdot \left( \sum_{s'} p(x_1, x_2, \dots, x_{t-1}, z_{t-1}=s', z_t = s) \right)\\
    &= p(x_t | z_t = s) \cdot \left( \sum_{s'} p(z_t = s | x_1, x_2, \dots, x_{t-1}, z_{t-1}=s') \cdot p(x_1, x_2, \dots, x_{t-1}, z_{t-1}=s') \right)\\
    &= \underbrace{p(x_t | z_t = s)}_{\text{emission model}} \cdot \left( \sum_{s'} \underbrace{p(z_t = s | z_{t-1}=s')}_{\text{transition model}} \cdot \underbrace{p(x_1, x_2, \dots, x_{t-1}, z_{t-1}=s')}_{\text{forward variable for previous timestep}} \right)\\
    &= b_s(x_t) \cdot \left( \sum_{s'} A_{s, s'} \cdot \alpha_{s',t-1} \right)
    \end{align}$$

I'll explain how to get to each line of this equation from the previous line. 

Line 1 is the definition of the forward variable $\alpha_{s,t}$.

Line 2 is the chain rule ($p(A,B) = p(A|B) \cdot p(B)$, where $A$ is $x_t$ and $B$ is all the other variables).

In Line 3, we apply Assumption 2: the probability of observation $x_t$ depends only on the current state $z_t$.

In Line 4, we marginalize over all the possible states in the previous timestep $t-1$.

In Line 5, we apply the chain rule again.

In Line 6, we apply Assumption 1: the current state depends only on the previous state.

In Line 7, we substitute in the emission probability, the transition probability, and the forward variable for the previous timestep, to get the complete recursion.

The formula above can be used for $t = 2 \rightarrow T$. At $t=1$, there is no previous state, so instead of the transition matrix $A$, we use the state priors $\pi$, which tell us the probability of starting in each state. Thus for $t=1$, the forward variables are computed as follows:

$$\begin{align} 
\alpha_{s,1} &= p(x_1, z_1=s) \\
  &= p(x_1 | z_1 = s) \cdot p(z_1 = s)  \\ 
&= b_s(x_1) \cdot \pi_s
\end{align}$$

Finally, to compute $p(\mathbf{x}) = p(x_1, x_2, \dots, x_T)$, we marginalize over $\alpha_{s,T}$, the forward variables computed in the last timestep:

$$\begin{align*} 
p(\mathbf{x}) &= \sum_{s} p(x_1, x_2, \dots, x_T, z_T = s) \\ 
&= \sum_{s} \alpha_{s,T}
\end{align*}$$

You can get from this formulation to the log domain formulation by taking the log of the forward variable, and using these identities:
- $\text{log }(a \cdot b) = \text{log }a + \text{log }b$
- $\text{log }(a + b) = \text{log }(e^{\text{log }a} + e^{\text{log }b}) = \text{logsumexp}(\text{log }a, \text{log }b)$

### Problem 2: How do we compute $\underset{\mathbf{z}}{\text{argmax }} p(\mathbf{z}|\mathbf{x})$?

Given an observation sequence $\mathbf{x}$, we may want to find the most likely sequence of states that could have generated $\mathbf{x}$. (Given the sequence of selfies, we want to infer what cities the friend visited.) In other words, we want $\underset{\mathbf{z}}{\text{argmax }} p(\mathbf{z}|\mathbf{x})$.

We can use Bayes' rule to rewrite this expression:
    $$\begin{align*} 
    \underset{\mathbf{z}}{\text{argmax }} p(\mathbf{z}|\mathbf{x}) &= \underset{\mathbf{z}}{\text{argmax }} \frac{p(\mathbf{x}|\mathbf{z}) p(\mathbf{z})}{p(\mathbf{x})} \\ 
    &= \underset{\mathbf{z}}{\text{argmax }} p(\mathbf{x}|\mathbf{z}) p(\mathbf{z})
    \end{align*}$$

Hmm! That last expression, $\underset{\mathbf{z}}{\text{argmax }} p(\mathbf{x}|\mathbf{z}) p(\mathbf{z})$, looks suspiciously similar to the intractable expression we encountered before introducing the forward algorithm, $\underset{\mathbf{z}}{\sum} p(\mathbf{x}|\mathbf{z}) p(\mathbf{z})$.

And indeed, just as the intractable *sum* over all $\mathbf{z}$ can be implemented efficiently using the forward algorithm, so too this intractable *argmax* can be implemented efficiently using a similar divide-and-conquer algorithm: the legendary Viterbi algorithm!

________

<u><b>The Viterbi Algorithm</b></u>

> for $s=1 \rightarrow N$:\
> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$\delta_{s,1} := b_s(x_1) \cdot \pi_s$\
> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$\psi_{s,1} := 0$
>
> for $t = 2 \rightarrow T$:\
> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;for $s = 1 \rightarrow N$:\
> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$\delta_{s,t} := b_s(x_t) \cdot \left( \underset{s'}{\text{max }} A_{s, s'} \cdot \delta_{s',t-1} \right)$\
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$\psi_{s,t} := \underset{s'}{\text{argmax }} A_{s, s'} \cdot \delta_{s',t-1}$
> 
> $z_T^* := \underset{s}{\text{argmax }} \delta_{s,T}$\
> for $t = T-1 \rightarrow 1$:\
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$z_{t}^* := \psi_{z_{t+1}^*,t+1}$
> 
> $\mathbf{z}^* := \{z_{1}^*, \dots, z_{T}^* \}$\
return $\mathbf{z}^*$
________

The Viterbi algorithm looks somewhat gnarlier than the forward algorithm, but it is essentially the same algorithm, with two tweaks: 1) instead of taking the sum over previous states, we take the max; and 2) we record the argmax of the previous states in a table, and loop back over this table at the end to get $\mathbf{z}^*$, the most likely state sequence. (And like the forward algorithm, we should run the Viterbi algorithm in the log domain for better numerical stability.) 

Let's add the Viterbi algorithm to our PyTorch model:


```
def viterbi(self, x, T):
  """
  x : IntTensor of shape (batch size, T_max)
  T : IntTensor of shape (batch size)
  Find argmax_z log p(x|z) for each (x) in the batch.
  """
  if self.is_cuda:
    x = x.cuda()
    T = T.cuda()

  batch_size = x.shape[0]; T_max = x.shape[1]
  log_state_priors = torch.nn.functional.log_softmax(self.unnormalized_state_priors, dim=0)
  log_delta = torch.zeros(batch_size, T_max, self.N).float()
  psi = torch.zeros(batch_size, T_max, self.N).long()
  if self.is_cuda:
    log_delta = log_delta.cuda()
    psi = psi.cuda()

  log_delta[:, 0, :] = self.emission_model(x[:,0]) + log_state_priors
  for t in range(1, T_max):
    max_val, argmax_val = self.transition_model.maxmul(log_delta[:, t-1, :])
    log_delta[:, t, :] = self.emission_model(x[:,t]) + max_val
    psi[:, t, :] = argmax_val

  # Get the log probability of the best path
  log_max = log_delta.max(dim=2)[0]
  best_path_scores = torch.gather(log_max, 1, T.view(-1,1) - 1)

  # This next part is a bit tricky to parallelize across the batch,
  # so we will do it separately for each example.
  z_star = []
  for i in range(0, batch_size):
    z_star_i = [ log_delta[i, T[i] - 1, :].max(dim=0)[1].item() ]
    for t in range(T[i] - 1, 0, -1):
      z_t = psi[i, t, z_star_i[0]].item()
      z_star_i.insert(0, z_t)

    z_star.append(z_star_i)

  return z_star, best_path_scores # return both the best path and its log probability

def transition_model_maxmul(self, log_alpha):
  log_transition_matrix = torch.nn.functional.log_softmax(self.unnormalized_transition_matrix, dim=1)

  out1, out2 = maxmul(log_transition_matrix, log_alpha.transpose(0,1))
  return out1.transpose(0,1), out2.transpose(0,1)

def maxmul(log_A, log_B):
	"""
	log_A : m x n
	log_B : n x p
	output : m x p matrix

	Similar to the log domain matrix multiplication,
	this computes out_{i,j} = max_k log_A_{i,k} + log_B_{k,j}
	"""
	m = log_A.shape[0]
	n = log_A.shape[1]
	p = log_B.shape[1]

	log_A_expanded = torch.stack([log_A] * p, dim=2)
	log_B_expanded = torch.stack([log_B] * m, dim=0)

	elementwise_sum = log_A_expanded + log_B_expanded
	out1,out2 = torch.max(elementwise_sum, dim=1)

	return out1,out2

TransitionModel.maxmul = transition_model_maxmul
HMM.viterbi = viterbi
```

Try running Viterbi on an input sequence, given the vowel/consonant HMM:


```
x = torch.stack( [torch.tensor(encode("aba")), torch.tensor(encode("abb"))] )
T = torch.tensor([3,3])
print(model.viterbi(x, T))
```

    ([[1, 0, 1], [1, 0, 0]], tensor([[-8.7869],
            [   -inf]], device='cuda:0', grad_fn=<GatherBackward>))


For $\mathbf{x} = \text{"aba"}$, the Viterbi algorithm returns $\mathbf{z}^* = \{1,0,1\}$. This corresponds to "vowel, consonant, vowel" according to the way we defined the states above, which is correct for this input sequence. Yay!

For $\mathbf{x} = \text{"abb"}$, the Viterbi algorithm still returns a $\mathbf{z}^*$, but we know this is gibberish because "vowel, consonant, consonant" is impossible under this HMM, and indeed the log probability of this path is $-\infty$.

Let's compare the "forward score" (the log probability of all possible paths, returned by the forward algorithm) with the "Viterbi score" (the log probability of the maximum likelihood path, returned by the Viterbi algorithm):


```
print(model.forward(x, T))
print(model.viterbi(x, T)[1])
```

    tensor([[-8.7869],
            [   -inf]], device='cuda:0', grad_fn=<GatherBackward>)
    tensor([[-8.7869],
            [   -inf]], device='cuda:0', grad_fn=<GatherBackward>)


The two scores are the same! That's because in this instance there is only one possible path through the HMM, so the probability of the most likely path is the same as the sum of the probabilities of all possible paths.

In general, though, the forward score and Viterbi score will always be somewhat close. This is because of a property of the $\text{logsumexp}$ function: $\text{logsumexp}(\mathbf{x}) \approx \max (\mathbf{x})$. ($\text{logsumexp}$ is sometimes referred to as the "smooth maximum" function.)


```
x = torch.tensor([1., 2., 3.])
print(x.max(dim=0)[0])
print(x.logsumexp(dim=0))
```

    tensor(3.)
    tensor(3.4076)


### Problem 3: How do we train the model?





Earlier, we hard-coded an HMM to have certain behavior. What we would like to do instead is have the HMM learn to model the data on its own. And while it is possible to use supervised learning with an HMM (by hard-coding the emission model or the transition model) so that the states have a particular interpretation, the really cool thing about HMMs is that they are naturally unsupervised learners, so they can learn to use their different states to represent different patterns in the data, without the programmer needing to indicate what each state means.

Like many machine learning models, an HMM can be trained using maximum likelihood estimation, i.e.:

$$\theta^* = \underset{\theta}{\text{argmin }} -\sum_{\mathbf{x}^i}\text{log }p_{\theta}(\mathbf{x}^i)$$

where $\mathbf{x}^1, \mathbf{x}^2, \dots$ are training examples. 

The standard method for doing this is the Expectation-Maximization (EM) algorithm, which for HMMs is also called the "Baum-Welch" algorithm. In EM training, we alternate between an "E-step", where we estimate the values of the latent variables, and an "M-step", where the model parameters are updated given the estimated latent variables. (Think $k$-means, where you guess which cluster each data point belongs to, then reestimate where the clusters are, and repeat.) The EM algorithm has some nice properties: it is guaranteed at each step to decrease the loss function, and the E-step and M-step may have an exact closed form solution, in which case no pesky learning rates are required.

But because the HMM forward algorithm is differentiable with respect to all the model parameters, we can also just take advantage of automatic differentiation methods in libraries like PyTorch and try to minimize $-\text{log }p_{\theta}(\mathbf{x})$ directly, by backpropagating through the forward algorithm and running stochastic gradient descent. That means we don't need to write any additional HMM code to implement training: `loss.backward()` is all you need.

Here we will implement SGD training for an HMM in PyTorch. First, some helper classes:


```
import torch.utils.data
from collections import Counter
from sklearn.model_selection import train_test_split

class TextDataset(torch.utils.data.Dataset):
  def __init__(self, lines):
    self.lines = lines # list of strings
    collate = Collate() # function for generating a minibatch from strings
    self.loader = torch.utils.data.DataLoader(self, batch_size=1024, num_workers=1, shuffle=True, collate_fn=collate)

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

  def __getitem__(self, idx):
    line = self.lines[idx].lstrip(" ").rstrip("\n").rstrip(" ").rstrip("\n")
    return line

class Collate:
  def __init__(self):
    pass

  def __call__(self, batch):
    """
    Returns a minibatch of strings, padded to have the same length.
    """
    x = []
    batch_size = len(batch)
    for index in range(batch_size):
      x_ = batch[index]

      # convert letters to integers
      x.append(encode(x_))

    # pad all sequences with 0 to have same length
    x_lengths = [len(x_) for x_ in x]
    T = max(x_lengths)
    for index in range(batch_size):
      x[index] += [0] * (T - len(x[index]))
      x[index] = torch.tensor(x[index])

    # stack into single tensor
    x = torch.stack(x)
    x_lengths = torch.tensor(x_lengths)
    return (x,x_lengths)
```

Let's load some training/testing data. By default, this will use the unix "words" file, but you could also use your own text file.


```
!wget https://raw.githubusercontent.com/lorenlugosch/pytorch_HMM/master/data/train/training.txt

filename = "training.txt"

with open(filename, "r") as f:
  lines = f.readlines() # each line of lines will have one word

alphabet = list(Counter(("".join(lines))).keys())
train_lines, valid_lines = train_test_split(lines, test_size=0.1, random_state=42)
train_dataset = TextDataset(train_lines)
valid_dataset = TextDataset(valid_lines)

M = len(alphabet)
```

    --2020-01-28 19:13:21--  https://raw.githubusercontent.com/lorenlugosch/pytorch_HMM/master/data/train/training.txt
    Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 151.101.0.133, 151.101.64.133, 151.101.128.133, ...
    Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|151.101.0.133|:443... connected.
    HTTP request sent, awaiting response... 200 OK
    Length: 2493109 (2.4M) [text/plain]
    Saving to: ‘training.txt’
    
    training.txt        100%[===================>]   2.38M  --.-KB/s    in 0.1s    
    
    2020-01-28 19:13:26 (22.5 MB/s) - ‘training.txt’ saved [2493109/2493109]
    


We will use a Trainer class for training and testing the model:




```
from tqdm import tqdm # for displaying progress bar

class Trainer:
  def __init__(self, model, lr):
    self.model = model
    self.lr = lr
    self.optimizer = torch.optim.Adam(model.parameters(), lr=self.lr, weight_decay=0.00001)
  
  def train(self, dataset):
    train_loss = 0
    num_samples = 0
    self.model.train()
    print_interval = 50
    for idx, batch in enumerate(tqdm(dataset.loader)):
      x,T = batch
      batch_size = len(x)
      num_samples += batch_size
      log_probs = self.model(x,T)
      loss = -log_probs.mean()
      self.optimizer.zero_grad()
      loss.backward()
      self.optimizer.step()
      train_loss += loss.cpu().data.numpy().item() * batch_size
      if idx % print_interval == 0:
        print("loss:", loss.item())
        for _ in range(5):
          sampled_x, sampled_z = self.model.sample()
          print(decode(sampled_x))
          print(sampled_z)
    train_loss /= num_samples
    return train_loss

  def test(self, dataset):
    test_loss = 0
    num_samples = 0
    self.model.eval()
    print_interval = 50
    for idx, batch in enumerate(dataset.loader):
      x,T = batch
      batch_size = len(x)
      num_samples += batch_size
      log_probs = self.model(x,T)
      loss = -log_probs.mean()
      test_loss += loss.cpu().data.numpy().item() * batch_size
      if idx % print_interval == 0:
        print("loss:", loss.item())
        sampled_x, sampled_z = self.model.sample()
        print(decode(sampled_x))
        print(sampled_z)
    test_loss /= num_samples
    return test_loss
```

Finally, initialize the model and run the main training loop. Every 50 batches, the code will produce a few samples from the model. Over time, these samples should look more and more realistic.


```
# Initialize model
model = HMM(N=64, M=M)

# Train the model
num_epochs = 10
trainer = Trainer(model, lr=0.01)

for epoch in range(num_epochs):
        print("========= Epoch %d of %d =========" % (epoch+1, num_epochs))
        train_loss = trainer.train(train_dataset)
        valid_loss = trainer.test(valid_dataset)

        print("========= Results: epoch %d of %d =========" % (epoch+1, num_epochs))
        print("train loss: %.2f| valid loss: %.2f\n" % (train_loss, valid_loss) )
```

      0%|          | 0/208 [00:00<?, ?it/s]

    ========= Epoch 1 of 10 =========


      0%|          | 1/208 [00:00<01:25,  2.42it/s]

    loss: 37.582481384277344
    VxKGP
    
    OCJ
    [31, 37, 40, 4, 3, 29, 37, 45, 11, 29]
    tlrZYbAzdd
    [55, 31, 47, 55, 44, 40, 43, 49, 36, 20]
    bdNS
    jakwe
    [55, 42, 5, 16, 26, 37, 49, 57, 55, 8]
    guTrnXmdUh
    [8, 54, 40, 7, 28, 35, 35, 6, 37, 25]
    CasaRIOZpa
    [40, 4, 5, 55, 5, 58, 53, 46, 32, 48]


     25%|██▍       | 51/208 [00:16<00:53,  2.96it/s]

    loss: 33.11034393310547
    oZteXuAqdo
    [12, 46, 5, 13, 22, 57, 20, 23, 63, 10]
    oFgcusjdDW
    [47, 47, 38, 31, 9, 16, 34, 20, 59, 9]
    LxSHijFVtz
    [59, 28, 3, 1, 22, 9, 32, 53, 42, 4]
    -YgiishZtX
    [43, 1, 31, 7, 53, 52, 54, 35, 62, 22]
    BHMITaHpLs
    [26, 52, 39, 58, 56, 18, 36, 45, 4, 44]


     49%|████▊     | 101/208 [00:32<00:33,  3.17it/s]

    loss: 29.39785385131836
    pgvlabflda
    [45, 39, 11, 51, 19, 31, 51, 25, 38, 12]
    rZih
    gjYdo
    [57, 52, 61, 39, 37, 39, 1, 39, 51, 3]
    alistcnloe
    [55, 12, 7, 8, 33, 24, 25, 28, 3, 49]
    Tndodjmtpq
    [26, 61, 44, 24, 49, 10, 26, 8, 59, 9]
    indTtlraVb
    [10, 44, 18, 23, 18, 28, 53, 35, 31, 31]


     73%|███████▎  | 151/208 [00:48<00:18,  3.10it/s]

    loss: 26.592235565185547
    
    Ocappmuml
    [63, 62, 21, 50, 21, 3, 41, 30, 60, 37]
    rnpWelsfaT
    [59, 11, 53, 56, 43, 7, 60, 28, 14, 0]
    aHeRysKVTy
    [62, 42, 13, 19, 49, 29, 36, 43, 0, 27]
    stgngcukIs
    [55, 3, 0, 56, 33, 54, 16, 50, 54, 58]
    heruudcaqc
    [38, 8, 5, 54, 24, 30, 51, 55, 50, 37]


     97%|█████████▋| 201/208 [01:03<00:02,  3.18it/s]

    loss: 24.756166458129883
    nrSgirgjgg
    [41, 47, 49, 34, 0, 2, 39, 2, 39, 39]
    SteaPhpnyg
    [16, 30, 61, 35, 7, 21, 45, 29, 37, 24]
    aededlmlhL
    [6, 43, 51, 15, 42, 55, 60, 41, 21, 46]
    hlndySefCe
    [55, 41, 0, 20, 50, 20, 23, 58, 37, 26]
    teitiQpqng
    [55, 8, 61, 5, 4, 24, 63, 45, 11, 32]


    100%|██████████| 208/208 [01:05<00:00,  3.94it/s]


    loss: 24.631101608276367
    hybcycbnYn
    [38, 27, 24, 12, 15, 61, 31, 51, 46, 46]


      0%|          | 0/208 [00:00<?, ?it/s]

    ========= Results: epoch 1 of 10 =========
    train loss: 30.02| valid loss: 24.83
    
    ========= Epoch 2 of 10 =========


      0%|          | 1/208 [00:00<01:20,  2.58it/s]

    loss: 24.459197998046875
    laorHXsnld
    [38, 6, 57, 26, 62, 22, 7, 29, 5, 3]
    dIardPbgNy
    [16, 30, 49, 7, 45, 53, 56, 43, 15, 1]
    thznbGrjsI
    [55, 3, 13, 49, 24, 54, 54, 26, 18, 18]
    soIiedlwcd
    [55, 10, 9, 61, 58, 58, 3, 60, 41, 49]
    nytogaxaed
    [59, 9, 5, 12, 46, 12, 60, 48, 3, 41]


     25%|██▍       | 51/208 [00:16<00:48,  3.21it/s]

    loss: 23.961589813232422
    cBoadrxahm
    [55, 46, 45, 45, 24, 56, 36, 12, 0, 53]
    ryoxsyuyts
    [38, 15, 60, 9, 9, 63, 22, 35, 3, 29]
    dlendsnenl
    [55, 61, 32, 41, 20, 26, 54, 13, 49, 0]
    sieddWsavy
    [55, 41, 11, 20, 42, 21, 61, 63, 61, 45]
    furdBtNeoh
    [55, 59, 32, 20, 33, 23, 3, 8, 26, 8]


     49%|████▊     | 101/208 [00:32<00:35,  2.97it/s]

    loss: 23.018342971801758
    pelydtulEc
    [55, 8, 25, 27, 24, 51, 22, 35, 34, 26]
    nglmngkced
    [44, 30, 0, 2, 29, 39, 28, 44, 50, 20]
    tdikoKmgds
    [11, 49, 60, 43, 20, 20, 46, 37, 49, 36]
    tessTitAns
    [55, 4, 18, 18, 49, 62, 32, 53, 11, 18]
    siedrmrwxe
    [55, 6, 13, 49, 43, 7, 42, 33, 60, 4]


     73%|███████▎  | 151/208 [00:47<00:17,  3.22it/s]

    loss: 22.27695655822754
    bevatWetey
    [55, 8, 5, 56, 7, 31, 14, 63, 34, 15]
    dredWpyhdl
    [55, 38, 4, 42, 25, 28, 1, 17, 3, 0]
    mhyyssWdra
    [55, 38, 27, 21, 18, 18, 2, 41, 34, 48]
    iysglnddee
    [6, 19, 2, 30, 63, 44, 40, 49, 13, 19]
    doynsserrn
    [55, 57, 21, 44, 11, 60, 4, 47, 40, 56]


     97%|█████████▋| 201/208 [01:03<00:02,  3.15it/s]

    loss: 22.124229431152344
    tRndssyaNe
    [55, 17, 49, 31, 60, 41, 27, 19, 60, 23]
    lulmKmljdl
    [55, 59, 9, 2, 61, 0, 40, 4, 42, 25]
    naoranidon
    [55, 17, 57, 49, 19, 44, 48, 31, 57, 54]
    acNnlsunIk
    [6, 51, 48, 46, 25, 28, 19, 45, 58, 33]
    AuydJypanr
    [55, 6, 34, 41, 31, 21, 19, 49, 46, 45]


    100%|██████████| 208/208 [01:05<00:00,  3.76it/s]


    loss: 22.349966049194336
    mecskynmmn
    [55, 8, 62, 34, 25, 28, 9, 3, 3, 56]


      0%|          | 0/208 [00:00<?, ?it/s]

    ========= Results: epoch 2 of 10 =========
    train loss: 23.12| valid loss: 22.21
    
    ========= Epoch 3 of 10 =========


      0%|          | 1/208 [00:00<01:37,  2.11it/s]

    loss: 22.131309509277344
    yahoconeRi
    [23, 62, 8, 32, 2, 60, 33, 43, 9, 28]
    toyaYtrltj
    [55, 14, 53, 26, 2, 62, 61, 50, 31, 53]
    RacAynanas
    [55, 17, 52, 34, 19, 46, 48, 53, 56, 18]
    nheyoenved
    [55, 8, 13, 19, 46, 60, 29, 5, 4, 42]
    aonmdNywnG
    [55, 57, 21, 40, 42, 25, 27, 37, 54, 8]


     25%|██▍       | 51/208 [00:16<00:53,  2.94it/s]

    loss: 21.87742805480957
    bofsZedgus
    [55, 57, 54, 60, 9, 9, 20, 43, 22, 60]
    ockegNlydl
    [6, 26, 40, 43, 39, 25, 25, 28, 41, 44]
    ackstatarA
    [6, 12, 9, 53, 2, 19, 31, 48, 25, 27]
    cefnaeaded
    [55, 8, 57, 54, 17, 4, 24, 31, 13, 49]
    aaanewrgRU
    [6, 51, 48, 50, 56, 29, 39, 25, 15, 31]


     49%|████▊     | 101/208 [00:32<00:33,  3.15it/s]

    loss: 21.491273880004883
    tencbalycl
    [55, 6, 29, 2, 37, 48, 53, 19, 12, 25]
    hhledlyraE
    [55, 8, 38, 14, 20, 25, 28, 55, 17, 36]
    ceeonqnene
    [55, 17, 8, 57, 54, 17, 29, 13, 44, 11]
    icmssanakn
    [6, 45, 3, 58, 60, 5, 1, 48, 50, 25]
    qenesslyec
    [55, 59, 44, 11, 18, 58, 25, 15, 61, 62]


     73%|███████▎  | 151/208 [00:48<00:18,  3.13it/s]

    loss: 21.693378448486328
    grknedtnme
    [55, 59, 14, 44, 11, 20, 32, 21, 38, 14]
    ronandeed
    
    [55, 57, 54, 48, 50, 20, 56, 53, 40, 54]
    lowcaZcedn
    [55, 6, 36, 45, 17, 3, 45, 4, 42, 44]
    shyedidlal
    [55, 38, 27, 4, 42, 61, 41, 44, 48, 37]
    bealaesusm
    [55, 59, 48, 53, 56, 43, 60, 11, 18, 60]


     97%|█████████▋| 201/208 [01:03<00:02,  3.24it/s]

    loss: 21.936307907104492
    andaZlygly
    [6, 29, 31, 48, 37, 25, 28, 39, 25, 1]
    arnalonane
    [6, 57, 21, 48, 50, 57, 54, 48, 50, 17]
    oanclresUs
    [6, 10, 40, 45, 63, 44, 11, 18, 35, 60]
    chfussnedp
    [55, 59, 57, 22, 35, 35, 44, 11, 20, 19]
    sisheablyt
    [55, 6, 55, 38, 61, 48, 37, 25, 27, 56]


    100%|██████████| 208/208 [01:05<00:00,  3.81it/s]


    loss: 21.37592315673828
    idyntksdid
    [6, 36, 19, 56, 31, 33, 58, 31, 19, 24]


      0%|          | 0/208 [00:00<?, ?it/s]

    ========= Results: epoch 3 of 10 =========
    train loss: 21.76| valid loss: 21.52
    
    ========= Epoch 4 of 10 =========


      0%|          | 1/208 [00:00<01:31,  2.25it/s]

    loss: 21.31800079345703
    tfuslliOdn
    [55, 57, 22, 7, 1, 52, 22, 60, 30, 44]
    ghufnnesss
    [55, 8, 36, 57, 21, 44, 11, 18, 60, 35]
    t-ljdnessn
    [55, 19, 56, 46, 20, 44, 11, 18, 60, 44]
    cytleymdne
    [55, 19, 39, 25, 11, 17, 0, 20, 44, 11]
    nremdlessd
    [55, 38, 14, 0, 42, 25, 11, 18, 58, 49]


     25%|██▍       | 51/208 [00:16<00:49,  3.18it/s]

    loss: 21.071056365966797
    Qydmklynes
    [55, 19, 20, 40, 33, 25, 15, 44, 11, 18]
    thessaalXk
    [55, 8, 13, 35, 35, 44, 48, 50, 23, 25]
    mletlyyyhy
    [55, 38, 13, 32, 25, 28, 9, 28, 8, 27]
    maladypesd
    [55, 17, 25, 56, 31, 19, 55, 59, 2, 49]
    lylytdvtal
    [55, 17, 2, 17, 9, 20, 49, 32, 48, 53]


     49%|████▊     | 101/208 [00:31<00:33,  3.20it/s]

    loss: 21.18721580505371
    icteusmenn
    [6, 36, 5, 43, 24, 35, 34, 17, 46, 44]
    driVeredle
    [55, 38, 61, 41, 56, 47, 4, 42, 25, 11]
    enhsyeysne
    [6, 26, 8, 2, 17, 3, 43, 58, 44, 11]
    ilydvyrhzl
    [6, 12, 15, 20, 13, 19, 55, 8, 32, 25]
    lhnynessus
    [55, 59, 46, 30, 44, 11, 18, 60, 22, 7]


     73%|███████▎  | 151/208 [00:47<00:17,  3.22it/s]

    loss: 21.164073944091797
    ibtleyylli
    [6, 16, 32, 25, 13, 19, 17, 12, 53, 61]
    cenesseyet
    [55, 59, 44, 11, 18, 60, 10, 40, 8, 32]
    edalessnes
    [6, 36, 48, 53, 56, 18, 35, 44, 11, 18]
    cyheablaft
    [55, 19, 55, 59, 48, 37, 25, 56, 32, 49]
    cyhyyckydQ
    [55, 19, 8, 19, 3, 51, 33, 27, 20, 45]


     97%|█████████▋| 201/208 [01:02<00:02,  3.29it/s]

    loss: 21.0625
    damlhhenes
    [55, 17, 3, 49, 8, 38, 14, 44, 11, 18]
    cledeylusl
    [55, 38, 14, 20, 9, 27, 9, 22, 52, 25]
    ctaaidenss
    [55, 55, 48, 53, 61, 41, 56, 56, 2, 60]
    synsezglec
    [55, 19, 40, 52, 56, 29, 39, 25, 56, 36]
    anennnckor
    [6, 16, 23, 56, 54, 46, 51, 33, 4, 47]


    100%|██████████| 208/208 [01:04<00:00,  4.03it/s]


    loss: 21.235027313232422
    nocuslethm
    [55, 6, 26, 22, 52, 25, 15, 32, 38, 14]


      0%|          | 0/208 [00:00<?, ?it/s]

    ========= Results: epoch 4 of 10 =========
    train loss: 21.22| valid loss: 21.03
    
    ========= Epoch 5 of 10 =========


      0%|          | 1/208 [00:00<01:25,  2.41it/s]

    loss: 21.163387298583984
    nerydeydus
    [55, 4, 47, 19, 55, 8, 19, 36, 22, 7]
    lhyyt-dere
    [55, 8, 19, 17, 30, 17, 31, 4, 24, 56]
    vharlessal
    [55, 8, 4, 24, 25, 11, 18, 58, 48, 53]
    phylynessT
    [55, 8, 19, 25, 15, 44, 11, 18, 60, 34]
    yndnessyrd
    [6, 16, 40, 44, 11, 18, 58, 17, 47, 31]


     25%|██▍       | 51/208 [00:16<00:46,  3.34it/s]

    loss: 20.970998764038086
    Aalfnlyyne
    [55, 48, 53, 57, 21, 25, 28, 27, 21, 11]
    enodenesse
    [6, 29, 6, 55, 59, 44, 11, 18, 60, 23]
    seablyhetd
    [55, 4, 48, 37, 25, 27, 3, 45, 9, 20]
    vonrnTedce
    [55, 57, 21, 10, 46, 40, 4, 42, 25, 56]
    cedelylmes
    [55, 17, 31, 4, 25, 28, 53, 34, 17, 2]


     49%|████▊     | 101/208 [00:31<00:32,  3.31it/s]

    loss: 20.771623611450195
    aOdandlasm
    [6, 10, 31, 48, 50, 42, 25, 27, 7, 31]
    vcitkausly
    [55, 38, 61, 51, 33, 57, 22, 7, 25, 27]
    tymterseeh
    [55, 17, 2, 5, 4, 24, 2, 43, 17, 3]
    tyblykhrdy
    [55, 19, 37, 25, 15, 33, 38, 14, 20, 27]
    gyymmlyytl
    [55, 8, 19, 9, 0, 25, 28, 27, 32, 25]


     73%|███████▎  | 151/208 [00:47<00:18,  3.03it/s]

    loss: 20.630603790283203
    saledlyuse
    [55, 48, 53, 14, 20, 25, 27, 22, 52, 56]
    gyllylesss
    [55, 19, 37, 25, 15, 44, 11, 18, 58, 2]
    breakescke
    [55, 38, 14, 48, 5, 43, 2, 51, 33, 4]
    bintncnemt
    [55, 6, 16, 23, 9, 62, 54, 6, 16, 63]
    cyphledlye
    [55, 19, 55, 59, 44, 11, 20, 25, 27, 13]


     97%|█████████▋| 201/208 [01:02<00:02,  3.22it/s]

    loss: 20.628002166748047
    drybredide
    [55, 38, 19, 55, 38, 14, 20, 61, 41, 56]
    brinedness
    [55, 38, 61, 44, 11, 20, 44, 11, 18, 60]
    pidaltidAs
    [55, 61, 41, 48, 50, 32, 61, 41, 56, 2]
    fedessaesm
    [55, 4, 20, 11, 18, 60, 62, 56, 2, 0]
    sertedeyrt
    [55, 4, 24, 32, 4, 20, 14, 27, 26, 5]


    100%|██████████| 208/208 [01:04<00:00,  4.03it/s]


    loss: 21.04818344116211
    pasedsealf
    [55, 17, 2, 14, 20, 2, 59, 48, 53, 49]


      0%|          | 0/208 [00:00<?, ?it/s]

    ========= Results: epoch 5 of 10 =========
    train loss: 20.83| valid loss: 20.78
    
    ========= Epoch 6 of 10 =========


      0%|          | 1/208 [00:00<01:24,  2.44it/s]

    loss: 20.581947326660156
    chyfnablic
    [55, 8, 19, 57, 54, 48, 37, 25, 61, 45]
    unymantess
    [6, 16, 30, 0, 48, 50, 44, 11, 18, 58]
    gyaltlyhtd
    [55, 19, 62, 46, 32, 25, 27, 8, 32, 42]
    chwvsnessu
    [55, 8, 38, 27, 52, 44, 11, 18, 58, 22]
    rhypalcten
    [55, 8, 19, 55, 48, 53, 36, 5, 43, 44]


     25%|██▍       | 51/208 [00:16<00:48,  3.23it/s]

    loss: 20.88625144958496
    phyessness
    [55, 8, 19, 11, 18, 60, 44, 11, 18, 60]
    lhymtalics
    [55, 8, 19, 55, 38, 48, 53, 61, 45, 2]
    onideryhys
    [6, 16, 61, 41, 56, 24, 27, 3, 30, 2]
    mhyetlyyne
    [55, 8, 19, 14, 32, 38, 27, 9, 44, 11]
    treydsyssm
    [55, 38, 14, 14, 20, 2, 30, 2, 58, 0]


     49%|████▊     | 101/208 [00:31<00:32,  3.31it/s]

    loss: 20.23219871520996
    bhedexonid
    [55, 8, 4, 20, 15, 26, 57, 46, 61, 41]
    elidenesss
    [6, 12, 61, 41, 56, 44, 11, 18, 60, 2]
    crenmabled
    [55, 38, 14, 40, 0, 48, 37, 25, 56, 41]
    blicaeonak
    [55, 38, 61, 51, 48, 13, 57, 54, 48, 50]
    bhticnenes
    [55, 8, 32, 61, 62, 44, 11, 44, 11, 18]


     73%|███████▎  | 151/208 [00:46<00:17,  3.24it/s]

    loss: 20.1969051361084
    trynsashea
    [55, 38, 27, 46, 2, 17, 2, 59, 14, 48]
    phednessym
    [55, 8, 4, 42, 44, 11, 18, 58, 30, 0]
    soHknesGly
    [55, 6, 36, 33, 44, 11, 18, 58, 25, 28]
    phrnalness
    [55, 8, 57, 54, 48, 50, 44, 11, 18, 58]
    lythiondee
    [55, 19, 55, 8, 61, 57, 46, 20, 14, 9]


     97%|█████████▋| 201/208 [01:02<00:02,  3.29it/s]

    loss: 20.51156234741211
    sasnessede
    [55, 17, 60, 44, 11, 18, 60, 14, 20, 13]
    tytinablyd
    [55, 14, 32, 61, 29, 48, 37, 25, 28, 20]
    andlyeonal
    [6, 16, 31, 25, 27, 59, 57, 46, 17, 25]
    lrytismned
    [55, 38, 14, 32, 61, 35, 3, 44, 11, 20]
    Faninglene
    [55, 57, 54, 61, 29, 39, 25, 56, 44, 11]


    100%|██████████| 208/208 [01:04<00:00,  4.07it/s]


    loss: 20.681076049804688
    toussyness
    [55, 57, 22, 2, 60, 30, 44, 11, 18, 60]


      0%|          | 0/208 [00:00<?, ?it/s]

    ========= Results: epoch 6 of 10 =========
    train loss: 20.65| valid loss: 20.64
    
    ========= Epoch 7 of 10 =========


      0%|          | 1/208 [00:00<01:27,  2.36it/s]

    loss: 20.322513580322266
    gysthyatyn
    [55, 19, 36, 32, 38, 14, 48, 5, 15, 44]
    ullessness
    [6, 12, 25, 11, 18, 60, 44, 11, 18, 58]
    cletreedng
    [55, 38, 14, 32, 38, 14, 4, 20, 29, 39]
    bhyceriden
    [55, 8, 19, 55, 4, 47, 61, 41, 56, 44]
    elyleneEsi
    [6, 12, 19, 25, 15, 44, 11, 18, 58, 61]


     25%|██▍       | 51/208 [00:16<00:46,  3.38it/s]

    loss: 20.572463989257812
    petiacless
    [55, 6, 26, 61, 62, 45, 25, 11, 18, 60]
    chednedyli
    [55, 38, 14, 20, 44, 4, 20, 30, 12, 61]
    sitaliactl
    [55, 61, 5, 48, 53, 61, 62, 36, 32, 25]
    fyenessete
    [55, 14, 56, 44, 11, 18, 58, 17, 32, 4]
    ceeelaynls
    [55, 59, 56, 43, 25, 15, 14, 44, 11, 18]


     49%|████▊     | 101/208 [00:31<00:31,  3.38it/s]

    loss: 20.399456024169922
    deaneryhti
    [55, 59, 57, 54, 4, 47, 27, 8, 32, 61]
    gausnodmon
    [55, 57, 22, 52, 44, 11, 20, 0, 57, 54]
    mealingles
    [55, 59, 48, 53, 61, 29, 39, 25, 11, 18]
    nlessLcsel
    [55, 38, 11, 18, 58, 25, 51, 2, 9, 25]
    rhhytyldOa
    [55, 8, 38, 19, 55, 19, 12, 31, 61, 57]


     73%|███████▎  | 151/208 [00:46<00:18,  3.11it/s]

    loss: 20.67449951171875
    bueymaling
    [55, 59, 14, 30, 0, 48, 50, 61, 29, 39]
    ceeummonal
    [55, 59, 9, 22, 7, 0, 57, 54, 48, 53]
    BattyGedne
    [55, 6, 9, 5, 15, 44, 11, 20, 44, 11]
    colonnglen
    [55, 6, 12, 57, 54, 29, 39, 25, 56, 44]
    ilyldnessn
    [6, 12, 19, 12, 31, 44, 11, 18, 60, 44]


     97%|█████████▋| 201/208 [01:02<00:02,  2.99it/s]

    loss: 20.53281021118164
    mulusleals
    [55, 6, 12, 22, 2, 12, 9, 48, 50, 2]
    wytellyIes
    [55, 19, 55, 59, 12, 25, 28, 5, 13, 35]
    pordnessne
    [55, 6, 10, 40, 44, 11, 18, 60, 44, 11]
    dulyeetsee
    [55, 59, 25, 28, 13, 9, 9, 2, 13, 43]
    lhideEessn
    [55, 8, 61, 41, 56, 44, 11, 18, 60, 44]


    100%|██████████| 208/208 [01:04<00:00,  3.95it/s]


    loss: 19.893932342529297
    onthyenedl
    [6, 16, 63, 8, 19, 23, 44, 11, 20, 25]


      0%|          | 0/208 [00:00<?, ?it/s]

    ========= Results: epoch 7 of 10 =========
    train loss: 20.54| valid loss: 20.55
    
    ========= Epoch 8 of 10 =========


      0%|          | 1/208 [00:00<01:39,  2.09it/s]

    loss: 20.745155334472656
    athyolymon
    [6, 36, 8, 19, 6, 25, 30, 0, 57, 54]
    dylRtymsla
    [55, 19, 12, 14, 32, 30, 0, 2, 38, 48]
    ometumglyn
    [6, 34, 17, 32, 22, 7, 39, 25, 27, 21]
    deermnglyn
    [55, 14, 4, 24, 0, 29, 39, 25, 28, 44]
    araeeumdre
    [6, 12, 48, 50, 13, 22, 7, 20, 44, 11]


     25%|██▍       | 51/208 [00:15<00:48,  3.22it/s]

    loss: 20.89170265197754
    zfalessdne
    [55, 55, 48, 53, 11, 18, 58, 42, 44, 11]
    neneumedly
    [55, 6, 16, 9, 22, 7, 23, 20, 25, 28]
    piausgedne
    [55, 61, 45, 22, 7, 39, 4, 20, 44, 11]
    kedmymarip
    [55, 59, 31, 0, 30, 0, 48, 47, 61, 45]
    hysmonllon
    [55, 19, 35, 0, 57, 21, 12, 12, 57, 54]


     49%|████▊     | 101/208 [00:31<00:34,  3.14it/s]

    loss: 20.404035568237305
    needynatri
    [55, 59, 14, 20, 19, 55, 48, 32, 38, 61]
    berdudicsy
    [55, 4, 24, 20, 10, 49, 61, 45, 2, 17]
    falnmonono
    [55, 48, 53, 21, 0, 57, 54, 57, 21, 57]
    epkymallys
    [6, 36, 33, 30, 0, 48, 37, 25, 27, 7]
    xelennssse
    [55, 59, 25, 56, 44, 11, 18, 58, 2, 59]


     73%|███████▎  | 151/208 [00:46<00:17,  3.17it/s]

    loss: 20.2503662109375
    ristfyryge
    [55, 61, 35, 3, 5, 1, 47, 27, 39, 59]
    dhyletikly
    [55, 8, 19, 12, 17, 32, 61, 62, 25, 28]
    ayyenessne
    [6, 26, 19, 1, 44, 11, 18, 58, 44, 14]
    tupnessnes
    [55, 59, 17, 44, 11, 18, 60, 44, 11, 18]
    loneelyedn
    [55, 57, 46, 59, 9, 25, 28, 14, 20, 44]


     97%|█████████▋| 201/208 [01:02<00:02,  3.17it/s]

    loss: 20.75147247314453
    beidlymsde
    [55, 6, 10, 49, 25, 30, 0, 7, 31, 4]
    acystnesst
    [6, 55, 19, 35, 3, 44, 11, 18, 60, 3]
    dhtylymgny
    [55, 8, 32, 30, 25, 27, 0, 57, 46, 14]
    slylydalre
    [55, 38, 30, 12, 19, 41, 48, 50, 44, 11]
    cukymdylye
    [55, 59, 33, 30, 0, 49, 30, 25, 27, 9]


    100%|██████████| 208/208 [01:04<00:00,  3.99it/s]


    loss: 20.438739776611328
    eydstgeabl
    [6, 16, 31, 35, 3, 39, 59, 48, 37, 25]


      0%|          | 0/208 [00:00<?, ?it/s]

    ========= Results: epoch 8 of 10 =========
    train loss: 20.47| valid loss: 20.50
    
    ========= Epoch 9 of 10 =========


      0%|          | 1/208 [00:00<01:20,  2.58it/s]

    loss: 19.996936798095703
    thedleness
    [55, 59, 9, 20, 25, 56, 44, 11, 18, 58]
    aednedmada
    [6, 4, 42, 44, 11, 20, 7, 10, 41, 48]
    delidallym
    [55, 6, 12, 61, 41, 48, 37, 25, 28, 0]
    reeymeness
    [55, 59, 9, 19, 34, 17, 44, 11, 18, 58]
    hermonelys
    [55, 4, 24, 0, 57, 46, 9, 25, 28, 60]


     25%|██▍       | 51/208 [00:15<00:47,  3.29it/s]

    loss: 20.890419006347656
    Briallenes
    [55, 38, 14, 48, 37, 25, 56, 44, 11, 18]
    thiteednes
    [55, 38, 61, 5, 1, 11, 20, 44, 11, 18]
    pupksylymn
    [55, 6, 36, 33, 35, 30, 25, 28, 0, 44]
    ciofalsnes
    [55, 6, 10, 40, 48, 50, 52, 44, 11, 18]
    hoafednesf
    [55, 6, 10, 40, 4, 42, 44, 11, 18, 60]


     49%|████▊     | 101/208 [00:31<00:34,  3.11it/s]

    loss: 20.577880859375
    anlyggness
    [6, 26, 25, 28, 29, 39, 44, 11, 18, 60]
    yuynedness
    [6, 16, 30, 44, 11, 20, 44, 11, 18, 60]
    imalnessly
    [6, 34, 48, 53, 44, 11, 18, 58, 25, 28]
    sednedmene
    [55, 4, 42, 44, 11, 20, 34, 17, 44, 11]
    deefsheson
    [55, 59, 9, 40, 35, 3, 9, 31, 57, 21]


     73%|███████▎  | 151/208 [00:46<00:17,  3.21it/s]

    loss: 20.995319366455078
    ubketerony
    [6, 16, 33, 14, 32, 4, 24, 57, 21, 30]
    feabessnes
    [55, 14, 48, 37, 11, 18, 58, 44, 11, 18]
    qettermabl
    [55, 6, 36, 32, 4, 24, 0, 48, 37, 25]
    suananlyln
    [55, 59, 57, 46, 57, 21, 25, 30, 50, 44]
    Shyrlyacai
    [55, 38, 27, 37, 25, 27, 62, 51, 48, 50]


     97%|█████████▋| 201/208 [01:02<00:02,  2.98it/s]

    loss: 20.560609817504883
    rnyerynerm
    [55, 55, 14, 4, 47, 27, 21, 4, 24, 0]
    nhonlyxabl
    [55, 38, 57, 46, 25, 30, 26, 48, 37, 25]
    to
    hylleal
    [55, 6, 36, 8, 19, 12, 12, 9, 48, 37]
    ovusdledne
    [6, 55, 22, 2, 41, 25, 56, 20, 44, 11]
    cecnaleAti
    [55, 6, 34, 54, 48, 50, 14, 23, 32, 61]


    100%|██████████| 208/208 [01:04<00:00,  3.81it/s]


    loss: 20.599403381347656
    aitylydled
    [6, 10, 40, 30, 25, 30, 20, 25, 56, 20]


      0%|          | 0/208 [00:00<?, ?it/s]

    ========= Results: epoch 9 of 10 =========
    train loss: 20.43| valid loss: 20.47
    
    ========= Epoch 10 of 10 =========


      0%|          | 1/208 [00:00<01:28,  2.34it/s]

    loss: 20.2786865234375
    rphyenessn
    [55, 55, 38, 30, 17, 44, 11, 18, 58, 44]
    onglymntry
    [6, 29, 39, 25, 27, 0, 16, 63, 38, 19]
    celednledm
    [55, 14, 25, 56, 49, 44, 25, 56, 20, 7]
    ceeeonumea
    [55, 59, 9, 14, 57, 54, 22, 7, 56, 48]
    ghalulneto
    [55, 38, 48, 50, 22, 52, 44, 11, 32, 4]


     25%|██▍       | 51/208 [00:15<00:48,  3.27it/s]

    loss: 20.243629455566406
    adedstness
    [6, 41, 56, 20, 35, 3, 44, 11, 18, 58]
    teleyctonl
    [55, 6, 16, 23, 19, 36, 32, 57, 21, 25]
    miackmonle
    [55, 61, 62, 51, 33, 0, 57, 46, 25, 11]
    raldlynall
    [55, 6, 10, 49, 25, 27, 54, 48, 37, 25]
    grgumsnems
    [55, 38, 57, 22, 7, 60, 44, 11, 18, 60]


     49%|████▊     | 101/208 [00:31<00:34,  3.08it/s]

    loss: 20.28844451904297
    srymseondi
    [55, 38, 30, 0, 2, 23, 57, 54, 41, 61]
    genessnedu
    [55, 14, 44, 11, 18, 60, 44, 11, 20, 22]
    gyalnaeyck
    [55, 14, 48, 50, 54, 48, 50, 19, 36, 33]
    wylalustor
    [55, 19, 12, 48, 53, 22, 2, 32, 4, 20]
    nueylyetid
    [55, 59, 9, 30, 25, 28, 14, 32, 61, 41]


     73%|███████▎  | 151/208 [00:46<00:17,  3.20it/s]

    loss: 20.66337013244629
    realnesses
    [55, 59, 48, 50, 44, 11, 18, 58, 11, 18]
    vlogmiackl
    [55, 38, 6, 34, 0, 61, 62, 51, 33, 25]
    faeonsCess
    [55, 48, 13, 57, 54, 7, 44, 11, 18, 58]
    leonsssraF
    [55, 59, 57, 21, 2, 2, 7, 59, 48, 53]
    tanessxess
    [55, 6, 44, 11, 18, 58, 44, 11, 18, 60]


     97%|█████████▋| 201/208 [01:02<00:02,  3.23it/s]

    loss: 20.529830932617188
    orslyedeel
    [6, 26, 52, 25, 28, 59, 41, 59, 14, 25]
    piymonalsb
    [55, 38, 30, 0, 57, 54, 48, 53, 2, 37]
    jeolkarity
    [55, 14, 6, 12, 33, 48, 47, 61, 5, 15]
    tismalingl
    [55, 61, 35, 0, 48, 53, 61, 29, 39, 25]
    Zipkymusye
    [55, 6, 36, 33, 30, 0, 22, 2, 27, 9]


    100%|██████████| 208/208 [01:04<00:00,  4.05it/s]


    loss: 20.503211975097656
    tianatenes
    [55, 61, 57, 54, 48, 5, 43, 44, 11, 18]
    ========= Results: epoch 10 of 10 =========
    train loss: 20.41| valid loss: 20.45
    


You may wish to try different values of $N$ and see what the impact on sample quality is. 

It's also interesting to look at the visited states. For instance, I noticed the following interesting behavior: 
- If weight decay is used (`weight_decay=0.00001` in the initialization of the optimizer), the model almost always picks one of two states as the initial state, and uses one of these states to emit vowels and the other to emit consonants (without us programming that behavior or telling the model which letters are vowels!).
- But if no weight decay is used, then the model always starts from one particular state. I suspect that this is because weight decay encourages the state priors to be not too big, and if one state prior is very big, the model will always start from that state.

## Conclusion

HMMs used to be very popular in natural language processing, but they have largely been overshadowed by neural network models like RNNs and Transformers. Still, it is fun and instructive to study the HMM; some commonly used machine learning techniques like [Connectionist Temporal Classification](https://www.cs.toronto.edu/~graves/icml_2006.pdf) are inspired by HMM methods. HMMs are [still used in conjunction with neural networks in speech recognition](https://arxiv.org/abs/1811.07453), where the assumption of a one-hot state makes sense for modelling phonemes, which are spoken one at a time.

## Acknowledgments

This notebook is based partly on Lawrence Rabiner's excellent article "[A Tutorial on Hidden Markov Models and Selected Applications in Speech Recognition](https://www.cs.cmu.edu/~cga/behavior/rabiner1.pdf)", which you may also like to check out. Thanks also to Dima Serdyuk and Kyle Gorman for their feedback on the draft.

5941dbbb636f8e726bb77df83024bd073837daee
ipynb
Jupyter Notebook
HMM.ipynb
dendisuhubdy/pytorch_HMM
3235326027328e1b0377b17f9dad8fcc56a3668c
Apache-2.0
HMM.ipynb
dendisuhubdy/pytorch_HMM
3235326027328e1b0377b17f9dad8fcc56a3668c
Apache-2.0
HMM.ipynb
dendisuhubdy/pytorch_HMM
3235326027328e1b0377b17f9dad8fcc56a3668c
Apache-2.0
2022-01-12T12:14:05.000Z
2022-01-12T12:14:05.000Z
Qwen/Qwen-72B
1. YES
2. YES