Files
e3b8de5da9 ASF-3099 Implement IQN in pytorch-ts (#21)
* ASF-3099 Bootstrap: write backbones of test, distribution and distribution output

* ASF-3099 First proposition for IQN distribution output
Mostly for backbones, the functions themselves are far from final

* ASF-3099 Add sample() to ImplicitQuantile and its test

* ASF-3099 Test prediction, sampling and convergence logic for IQN

* ASF-3099 IQN module takes the data input and taus in

* ASF-3099 Add torch.no_grad in the sampling

* ASF-3099 Add tests on quantiles (10%, 90%), for both normal and uniform

* ASF-3099 Improve feeting of quantile function:
Increase depth of quantile network, change activation to PReLU

* ASF-3099 Fix distribution attributes and module imports

* ASF-3099 Fix implicit quantile init

* ASF-3099 Add integration test with deepAR

* ASF-3099 Add a transformed distribution

* ASF-3099 Fix init of ImplicitQuantile

* ASF-3099 Make iqn distribution compatible with forecast-length>1

* ASF-3099 Fix device for new tensors

* ASF-3099 Fix device for new tensors: device is not a function...

* ASF-3099 Fix output size of the network

* ASF-3099 Define torch network in the DistributionOutput only
Distribution takes only the predicted quantiles, or the parameters
of the trained model to define a new quantile function

* ASF-3099 Test: create quantile function on compatible device
Attempt: class method might force the module to be created only once,
not necessarily with the right device

* ASF-3099 Second attempt: create quantile function on compatible device

* ASF-3099 Sampling returns a tensor of the correct shape
Shape is (num_sample, batch_size, forecast_length)

* ASF-3099 Handle empty sample shapes

* ASF-3099 Fix tau device at inference time

* ASF-3099 Fix device of the layer

* ASF-3099 Handle empty sample shapes (fix output)

* ASF-3099 Last activation of quantile layer should be removed
That way, embedded quantiles are symetrically distributed around the 0.5
quantile. Otherwise we distort part of their distribution before applying
it to the forecasted quantities

* ASF-3099 (test) Add a bunch of layers

* ASF-3099 [test] reduce the embedding size of tau

* ASF-3099 [test] Use same IQN version as in sales forecaster

* ASF-3099 Put original parameters back

* use @torch.no_grad() decorator

* ASF-3099 [test, to be reverted] Remove - in front of the loss

* ASF-3099 Revert former commit: put - back in the loss

* ASF-3099 [fix] Add log_prob method in piecewise linear

* ASF-3099 [test] ImplicitQuantileModule should be instanciated only once
Current problem: it's instanciated once at training and once at prediction,
as if the model was never trained. Thus it is now defined as a
global variable. However, this can only be a temporary hack: it means that
only one model can be trained during a session.

* ASF-3099 [test] ImplicitQuantileModule should be instanciated only once
Current problem: it's instanciated once at training and once at prediction,
as if the model was never trained.
However here, if the same model is retrained in the same session,
the module is not reset.

* ASF-3099 Add notebooks for experiments

* ASF-3099 [test] Move module to the distribution

* ASF-3099 Class method for args_proj

* ASF-3099 Clean up

* ASF-3099 More clean up

* ASF-3099 Define options for domain of preditected quantiles
Predicted quantiles can be either positive, either real

* ASF-3099 Set quantile_arg_proj in the init of the distribution output
Before it was instanciated once per python session, thus when retraining
the same models, the previously trained module was used, and not a fresh
one

* ASF-3099 Add test on number of instantiation of the quantile_arg_proj

* ASF-3099 Add an example notebook

* ASF-3099 Remove some notebooks

* ASF-3099 Remove diff vs master

Co-authored-by: Kashif Rasul <kashif.rasul@zalando.de>
Co-authored-by: Mateusz Koren <mateusz.koren@zalando.de>
Co-authored-by: Adele Gouttes <agouttes@bm1-lxslurmctl01.corp.ad.zalando.net>
2020-10-01 15:52:04 +02:00

147 lines
4.8 KiB
Python

# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license" file accompanying this file. This file is distributed
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied. See the License for the specific language governing
# permissions and limitations under the License.
import torch
import torch.nn.functional as F
from torch.distributions import (
constraints,
NegativeBinomial,
Poisson,
Distribution,
TransformedDistribution,
AffineTransform,
)
from torch.distributions.utils import broadcast_all, lazy_property
from .utils import broadcast_shape
class PiecewiseLinear(Distribution):
def __init__(self, gamma, slopes, knot_spacings, validate_args=None):
self.gamma = gamma
self.slopes = slopes
self.knot_spacings = knot_spacings
self.b, self.knot_positions = PiecewiseLinear._to_orig_params(
slopes=slopes, knot_spacings=knot_spacings
)
super(PiecewiseLinear, self).__init__(
batch_shape=self.gamma.shape, validate_args=validate_args
)
@staticmethod
def _to_orig_params(slopes, knot_spacings):
# b: the difference between slopes of consecutive pieces
b = slopes[..., 1:] - slopes[..., 0:-1]
# Add slope of first piece to b: b_0 = m_0
m_0 = slopes[..., 0:1]
b = torch.cat((m_0, b), dim=-1)
# The actual position of the knots is obtained by cumulative sum of
# the knot spacings. The first knot position is always 0 for quantile
# functions.
knot_positions = torch.cumsum(knot_spacings, dim=-1) - knot_spacings
return b, knot_positions
@torch.no_grad()
def sample(self, sample_shape=torch.Size()):
shape = self._extended_shape(sample_shape)
u = torch.rand_like(self.gamma.expand(shape))
sample = self.quantile(u)
if len(sample_shape) == 0:
sample = sample.squeeze(0)
return sample
def quantile(self, level):
return self.quantile_internal(level, dim=0)
def quantile_internal(self, x, dim=None):
if dim is not None:
gamma = self.gamma.unsqueeze(dim=dim if dim == 0 else -1)
knot_positions = self.knot_positions.unsqueeze(dim)
b = self.b.unsqueeze(dim)
else:
gamma, knot_positions, b = self.gamma, self.knot_positions, self.b
x_minus_knots = x.unsqueeze(-1) - knot_positions
quantile = gamma + (b * F.relu(x_minus_knots)).sum(-1)
return quantile
def log_prob(self, value):
return -self.crps(value)
def cdf(self, x):
gamma, b, knot_positions = self.gamma, self.b, self.knot_positions
quantiles_at_knots = self.quantile_internal(knot_positions, dim=-2)
# Mask to nullify the terms corresponding to knots larger than l_0,
# which is the largest knot (quantile level) such that the quantile
# at l_0, s(l_0) < x.
mask = torch.le(quantiles_at_knots, x.unsqueeze(-1))
slope_l0 = (b * mask).sum(-1)
# slope_l0 can be zero in which case a_tilde = 0.
# The following is to circumvent an issue where the
# backward() returns nans when slope_l0 is zero in the where
slope_l0_nz = torch.where(slope_l0 == 0.0, torch.ones_like(x), slope_l0)
a_tilde = torch.where(
slope_l0 == 0.0,
torch.zeros_like(x),
(x - gamma + (b * knot_positions * mask).sum(-1)) / slope_l0_nz,
)
return torch.clamp(a_tilde, min=0.0, max=1.0)
def crps(self, x):
gamma, b, knot_positions = self.gamma, self.b, self.knot_positions
a_tilde = self.cdf(x)
max_a_tilde_knots = torch.max(a_tilde.unsqueeze(-1), knot_positions)
knots_cubed = torch.pow(knot_positions, 3.0)
coeff = (
(1.0 - knots_cubed) / 3.0
- knot_positions
- torch.square(max_a_tilde_knots)
+ 2 * max_a_tilde_knots * knot_positions
)
return (2 * a_tilde - 1) * x + (1 - 2 * a_tilde) * gamma + (b * coeff).sum(-1)
class TransformedPiecewiseLinear(TransformedDistribution):
def __init__(self, base_distribution, transforms):
super().__init__(base_distribution, transforms)
def crps(self, x):
scale = 1.0
for transform in reversed(self.transforms):
assert isinstance(transform, AffineTransform), "Not an AffineTransform"
x = transform.inv(x)
scale *= transform.scale
p = self.base_dist.crps(x)
return p * scale