Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
labmlai
GitHub Repository: labmlai/annotated_deep_learning_paper_implementations
Path: blob/master/labml_nn/sampling/temperature.py
4918 views
1
"""
2
---
3
title: Sampling from Language Models with Temperature
4
summary: A PyTorch implementation of sampling from language models with temperature.
5
---
6
7
# Sampling from Language Models with Temperature
8
9
Here we sample from the following probability distribution where $V$ is the vocabulary,
10
$u_{1:|V|}$ are the logits of the distribution and T is the temperature:
11
12
$$P(x_i=V_l | x_{1:i-1}) = \frac{\exp(\frac{u_l}{T})}{\sum_j \exp(\frac{u_j}{T})}$$
13
14
$T = 1$ is normal random sampling.
15
16
Here's an [experiment](experiment.html) that uses these sampling techniques.
17
"""
18
19
import torch
20
from torch.distributions import Categorical
21
22
from labml_nn.sampling import Sampler
23
24
25
class TemperatureSampler(Sampler):
26
"""
27
## Sampler with Temperature
28
"""
29
def __init__(self, temperature: float = 1.0):
30
"""
31
:param temperature: is the temperature to sample with
32
"""
33
self.temperature = temperature
34
35
def __call__(self, logits: torch.Tensor):
36
"""
37
Sample from logits
38
"""
39
40
# Create a categorical distribution with temperature adjusted logits
41
dist = Categorical(logits=logits / self.temperature)
42
43
# Sample
44
return dist.sample()
45
46