python_code
stringlengths 0
1.02M
| repo_name
stringlengths 9
48
| file_path
stringlengths 5
114
|
---|---|---|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
"""A basic variational autoencoder (VAE) on binarized MNIST using Numpy and JAX.
This file uses the stax network definition library and the optimizers
optimization library.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import time
import matplotlib.pyplot as plt
import jax.numpy as np
from jax.config import config
from jax import jit, grad, lax, random
from jax.experimental import optimizers
from jax.experimental import stax
from jax.experimental.stax import Dense, FanOut, Relu, Softplus
from examples import datasets
def gaussian_kl(mu, sigmasq):
"""KL divergence from a diagonal Gaussian to the standard Gaussian."""
return -0.5 * np.sum(1. + np.log(sigmasq) - mu**2. - sigmasq)
def gaussian_sample(rng, mu, sigmasq):
"""Sample a diagonal Gaussian."""
return mu + np.sqrt(sigmasq) * random.normal(rng, mu.shape)
def bernoulli_logpdf(logits, x):
"""Bernoulli log pdf of data x given logits."""
return -np.sum(np.logaddexp(0., np.where(x, -1., 1.) * logits))
def elbo(rng, params, images):
"""Monte Carlo estimate of the negative evidence lower bound."""
enc_params, dec_params = params
mu_z, sigmasq_z = encode(enc_params, images)
logits_x = decode(dec_params, gaussian_sample(rng, mu_z, sigmasq_z))
return bernoulli_logpdf(logits_x, images) - gaussian_kl(mu_z, sigmasq_z)
def image_sample(rng, params, nrow, ncol):
"""Sample images from the generative model."""
_, dec_params = params
code_rng, img_rng = random.split(rng)
logits = decode(dec_params, random.normal(code_rng, (nrow * ncol, 10)))
sampled_images = random.bernoulli(img_rng, np.logaddexp(0., logits))
return image_grid(nrow, ncol, sampled_images, (28, 28))
def image_grid(nrow, ncol, imagevecs, imshape):
"""Reshape a stack of image vectors into an image grid for plotting."""
images = iter(imagevecs.reshape((-1,) + imshape))
return np.vstack([np.hstack([next(images).T for _ in range(ncol)][::-1])
for _ in range(nrow)]).T
encoder_init, encode = stax.serial(
Dense(512), Relu,
Dense(512), Relu,
FanOut(2),
stax.parallel(Dense(10), stax.serial(Dense(10), Softplus)),
)
decoder_init, decode = stax.serial(
Dense(512), Relu,
Dense(512), Relu,
Dense(28 * 28),
)
if __name__ == "__main__":
step_size = 0.001
num_epochs = 100
batch_size = 32
nrow, ncol = 10, 10 # sampled image grid size
test_rng = random.PRNGKey(1) # fixed prng key for evaluation
imfile = os.path.join(os.getenv("TMPDIR", "/tmp/"), "mnist_vae_{:03d}.png")
train_images, _, test_images, _ = datasets.mnist(permute_train=True)
num_complete_batches, leftover = divmod(train_images.shape[0], batch_size)
num_batches = num_complete_batches + bool(leftover)
enc_init_rng, dec_init_rng = random.split(random.PRNGKey(2))
_, init_encoder_params = encoder_init(enc_init_rng, (batch_size, 28 * 28))
_, init_decoder_params = decoder_init(dec_init_rng, (batch_size, 10))
init_params = init_encoder_params, init_decoder_params
opt_init, opt_update, get_params = optimizers.momentum(step_size, mass=0.9)
def binarize_batch(rng, i, images):
i = i % num_batches
batch = lax.dynamic_slice_in_dim(images, i * batch_size, batch_size)
return random.bernoulli(rng, batch)
@jit
def run_epoch(rng, opt_state):
def body_fun(i, opt_state):
elbo_rng, data_rng = random.split(random.fold_in(rng, i))
batch = binarize_batch(data_rng, i, train_images)
loss = lambda params: -elbo(elbo_rng, params, batch) / batch_size
g = grad(loss)(get_params(opt_state))
return opt_update(i, g, opt_state)
return lax.fori_loop(0, num_batches, body_fun, opt_state)
@jit
def evaluate(opt_state, images):
params = get_params(opt_state)
elbo_rng, data_rng, image_rng = random.split(test_rng, 3)
binarized_test = random.bernoulli(data_rng, images)
test_elbo = elbo(elbo_rng, params, binarized_test) / images.shape[0]
sampled_images = image_sample(image_rng, params, nrow, ncol)
return test_elbo, sampled_images
opt_state = opt_init(init_params)
for epoch in range(num_epochs):
tic = time.time()
opt_state = run_epoch(random.PRNGKey(epoch), opt_state)
test_elbo, sampled_images = evaluate(opt_state, test_images)
print("{: 3d} {} ({:.3f} sec)".format(epoch, test_elbo, time.time() - tic))
plt.imsave(imfile.format(epoch), sampled_images, cmap=plt.cm.gray)
|
jax-master
|
examples/mnist_vae.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
"""Automatic differentiation variational inference in Numpy and JAX.
This demo fits a Gaussian approximation to an intractable, unnormalized
density, by differentiating through a Monte Carlo estimate of the
variational evidence lower bound (ELBO)."""
from __future__ import absolute_import
from __future__ import print_function
from functools import partial
import matplotlib.pyplot as plt
from jax.api import jit, grad, vmap
from jax import random
from jax.experimental import optimizers
import jax.numpy as np
import jax.scipy.stats.norm as norm
# ========= Functions to define the evidence lower bound. =========
def diag_gaussian_sample(rng, mean, log_std):
# Take a single sample from a diagonal multivariate Gaussian.
return mean + np.exp(log_std) * random.normal(rng, mean.shape)
def diag_gaussian_logpdf(x, mean, log_std):
# Evaluate a single point on a diagonal multivariate Gaussian.
return np.sum(vmap(norm.logpdf)(x, mean, np.exp(log_std)))
def elbo(logprob, rng, mean, log_std):
# Single-sample Monte Carlo estimate of the variational lower bound.
sample = diag_gaussian_sample(rng, mean, log_std)
return logprob(sample) - diag_gaussian_logpdf(sample, mean, log_std)
def batch_elbo(logprob, rng, params, num_samples):
# Average over a batch of random samples.
rngs = random.split(rng, num_samples)
vectorized_elbo = vmap(partial(elbo, logprob), in_axes=(0, None, None))
return np.mean(vectorized_elbo(rngs, *params))
# ========= Helper function for plotting. =========
@partial(jit, static_argnums=(0, 1, 2, 4))
def mesh_eval(func, x_limits, y_limits, params, num_ticks=101):
# Evaluate func on a 2D grid defined by x_limits and y_limits.
x = np.linspace(*x_limits, num=num_ticks)
y = np.linspace(*y_limits, num=num_ticks)
X, Y = np.meshgrid(x, y)
xy_vec = np.stack([X.ravel(), Y.ravel()]).T
zs = vmap(func, in_axes=(0, None))(xy_vec, params)
return X, Y, zs.reshape(X.shape)
# ========= Define an intractable unnormalized density =========
def funnel_log_density(params):
return norm.logpdf(params[0], 0, np.exp(params[1])) + \
norm.logpdf(params[1], 0, 1.35)
if __name__ == "__main__":
num_samples = 40
@jit
def objective(params, t):
rng = random.PRNGKey(t)
return -batch_elbo(funnel_log_density, rng, params, num_samples)
# Set up figure.
fig = plt.figure(figsize=(8,8), facecolor='white')
ax = fig.add_subplot(111, frameon=False)
plt.ion()
plt.show(block=False)
x_limits = [-2, 2]
y_limits = [-4, 2]
target_dist = lambda x, _: np.exp(funnel_log_density(x))
approx_dist = lambda x, params: np.exp(diag_gaussian_logpdf(x, *params))
def callback(params, t):
print("Iteration {} lower bound {}".format(t, objective(params, t)))
plt.cla()
X, Y, Z = mesh_eval(target_dist, x_limits, y_limits, 1)
ax.contour(X, Y, Z, cmap='summer')
X, Y, Z = mesh_eval(approx_dist, x_limits, y_limits, params)
ax.contour(X, Y, Z, cmap='winter')
ax.set_xlim(x_limits)
ax.set_ylim(y_limits)
ax.set_yticks([])
ax.set_xticks([])
# Plot random samples from variational distribution.
# Here we clone the rng used in computing the objective
# so that we can show exactly the same samples.
rngs = random.split(random.PRNGKey(t), num_samples)
samples = vmap(diag_gaussian_sample, in_axes=(0, None, None))(rngs, *params)
ax.plot(samples[:, 0], samples[:, 1], 'b.')
plt.draw()
plt.pause(1.0/60.0)
# Set up optimizer.
D = 2
init_mean = np.zeros(D)
init_std = np.zeros(D)
init_params = (init_mean, init_std)
opt_init, opt_update, get_params = optimizers.momentum(step_size=0.1, mass=0.9)
opt_state = opt_init(init_params)
@jit
def update(i, opt_state):
params = get_params(opt_state)
gradient = grad(objective)(params, i)
return opt_update(i, gradient, opt_state)
# Main loop.
print("Optimizing variational parameters...")
for t in range(100):
opt_state = update(t, opt_state)
params = get_params(opt_state)
callback(params, t)
plt.show(block=True)
|
jax-master
|
examples/advi.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
"""An ONNX to XLA compiler by JAX-tracing a Numpy-backed ONNX interpreter."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from cStringIO import StringIO
from functools import partial
import hashlib
import sys
import onnx
from onnx import numpy_helper
from onnx import onnx_pb2
from six.moves.urllib.request import urlopen
import jax.numpy as np
from jax import jit, grad
from jax import lax
def _asarray(proto):
return numpy_helper.to_array(proto).reshape(tuple(proto.dims))
attr_types = dict(onnx_pb2.AttributeProto.AttributeType.items())
attribute_handlers = {
attr_types['FLOAT']: lambda a: a.f,
attr_types['INT']: lambda a: a.i,
attr_types['STRING']: lambda a: a.s,
attr_types['TENSOR']: lambda a: _asarray(a.t),
attr_types['FLOATS']: lambda a: a.floats,
attr_types['INTS']: lambda a: a.ints,
attr_types['STRINGS']: lambda a: a.strings,
attr_types['TENSORS']: lambda a: [_asarray(x) for x in a.tensors],
}
def onnx_maxpool(x, kernel_shape, pads=None, strides=None):
"""Numpy-backed implementation of ONNX MaxPool op."""
prefix = (1,) * (x.ndim - len(kernel_shape))
dims = prefix + tuple(kernel_shape)
pads = tuple(pads) if pads else [0] * len(kernel_shape)
strides = (prefix + tuple(strides)) if strides else [1] * len(kernel_shape)
return [lax.reduce_window(x, -np.inf, lax.max, dims, strides, 'VALID')]
def onnx_conv(x, w, b=0, group=1, kernel_shape=None, pads=None, strides=None,
dilations=None, auto_pad=None):
"""Numpy-backed implementation of ONNX Conv op."""
assert group == 1
kernel_shape = kernel_shape or w.shape
strides = strides or [1] * (w.ndim - 2)
if auto_pad:
auto_pad = 'SAME' if auto_pad.startswith('SAME') else 'VALID'
pads = lax.padtype_to_pads(x.shape[2:], w.shape[2:], strides, auto_pad)
else:
pads = pads or [0] * (w.ndim - 2)
lhs_dilation = [1] * (w.ndim - 2)
rhs_dilation = dilations or [1] * (w.ndim - 2)
return [lax.conv_with_general_padding(x, w, strides, pads,
lhs_dilation, rhs_dilation) + b]
def onnx_add(a, b, axis=None, broadcast=True):
"""Numpy-backed implementation of ONNX Add op."""
if broadcast:
axis = (a.dim - b.ndim) if axis is None else axis % a.ndim
assert a.shape[axis:][:b.ndim] == b.shape
b_shape = np.ones(a.ndim, dtype='int64').copy()
b_shape[axis:axis + b.ndim] = b.shape
b = np.reshape(b, b_shape)
return [a + b]
onnx_ops = {
'Add': onnx_add,
'Constant': lambda value: [value],
'Conv': onnx_conv,
'MatMul': lambda x, y: [np.matmul(x, y)],
'MaxPool': onnx_maxpool,
'Relu': lambda x: [np.maximum(x, 0)],
'Reshape': lambda x, shape: [np.reshape(x, shape)],
}
def interpret_onnx(graph, *args):
vals = dict({n.name: a for n, a in zip(graph.input, args)},
**{n.name: _asarray(n) for n in graph.initializer})
for node in graph.node:
args = (vals[name] for name in node.input)
attrs = {a.name: attribute_handlers[a.type](a) for a in node.attribute}
outputs = onnx_ops[node.op_type](*args, **attrs)
for name, output in zip(node.output, outputs):
vals[name] = output
return [vals[n.name] for n in graph.output]
if __name__ == "__main__":
# It seems that there are several ONNX proto versions (you had one job!) but
# this implementation works with at least this one mnist example file.
url = ('https://github.com/onnx/models/blob/'
'81c4779096d1205edd0b809e191a924c58c38fef/'
'mnist/model.onnx?raw=true')
download = urlopen(url).read()
if hashlib.md5(download).hexdigest() != 'bc8ad9bd19c5a058055dc18d0f089dad':
print("onnx file checksum mismatch")
sys.exit(1)
model = onnx.load(StringIO(download))
predict = lambda inputs: interpret_onnx(model.graph, inputs)[0]
# Run inference in Numpy-backed interpreter
print("interpreted:")
print(predict(np.ones((1, 1, 28, 28))))
# JIT compile to XLA device, run inference on device
compiled_predict = jit(predict)
print("compiled:")
print(compiled_predict(np.ones((1, 1, 28, 28))))
# The interpreter is differentiable too! Even the compiled one:
fun = lambda inputs: np.sum(compiled_predict(inputs))
print("a derivative with respect to inputs:")
print(grad(fun)(np.ones((1, 1, 28, 28)))[..., :3, :3])
|
jax-master
|
examples/onnx2xla.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
"""A mock-up showing a ResNet50 network with training on synthetic data.
This file uses the stax neural network definition library and the optimizers
optimization library.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy.random as npr
from six.moves import xrange
import jax.numpy as np
from jax.config import config
from jax import jit, grad, random
from jax.experimental import optimizers
from jax.experimental import stax
from jax.experimental.stax import (AvgPool, BatchNorm, Conv, Dense, FanInSum,
FanOut, Flatten, GeneralConv, Identity,
MaxPool, Relu, LogSoftmax)
# ResNet blocks compose other layers
def ConvBlock(kernel_size, filters, strides=(2, 2)):
ks = kernel_size
filters1, filters2, filters3 = filters
Main = stax.serial(
Conv(filters1, (1, 1), strides), BatchNorm(), Relu,
Conv(filters2, (ks, ks), padding='SAME'), BatchNorm(), Relu,
Conv(filters3, (1, 1)), BatchNorm())
Shortcut = stax.serial(Conv(filters3, (1, 1), strides), BatchNorm())
return stax.serial(FanOut(2), stax.parallel(Main, Shortcut), FanInSum, Relu)
def IdentityBlock(kernel_size, filters):
ks = kernel_size
filters1, filters2 = filters
def make_main(input_shape):
# the number of output channels depends on the number of input channels
return stax.serial(
Conv(filters1, (1, 1)), BatchNorm(), Relu,
Conv(filters2, (ks, ks), padding='SAME'), BatchNorm(), Relu,
Conv(input_shape[3], (1, 1)), BatchNorm())
Main = stax.shape_dependent(make_main)
return stax.serial(FanOut(2), stax.parallel(Main, Identity), FanInSum, Relu)
# ResNet architectures compose layers and ResNet blocks
def ResNet50(num_classes):
return stax.serial(
GeneralConv(('HWCN', 'OIHW', 'NHWC'), 64, (7, 7), (2, 2), 'SAME'),
BatchNorm(), Relu, MaxPool((3, 3), strides=(2, 2)),
ConvBlock(3, [64, 64, 256], strides=(1, 1)),
IdentityBlock(3, [64, 64]),
IdentityBlock(3, [64, 64]),
ConvBlock(3, [128, 128, 512]),
IdentityBlock(3, [128, 128]),
IdentityBlock(3, [128, 128]),
IdentityBlock(3, [128, 128]),
ConvBlock(3, [256, 256, 1024]),
IdentityBlock(3, [256, 256]),
IdentityBlock(3, [256, 256]),
IdentityBlock(3, [256, 256]),
IdentityBlock(3, [256, 256]),
IdentityBlock(3, [256, 256]),
ConvBlock(3, [512, 512, 2048]),
IdentityBlock(3, [512, 512]),
IdentityBlock(3, [512, 512]),
AvgPool((7, 7)), Flatten, Dense(num_classes), LogSoftmax)
if __name__ == "__main__":
rng_key = random.PRNGKey(0)
batch_size = 8
num_classes = 1001
input_shape = (224, 224, 3, batch_size)
step_size = 0.1
num_steps = 10
init_fun, predict_fun = ResNet50(num_classes)
_, init_params = init_fun(rng_key, input_shape)
def loss(params, batch):
inputs, targets = batch
logits = predict_fun(params, inputs)
return -np.sum(logits * targets)
def accuracy(params, batch):
inputs, targets = batch
target_class = np.argmax(targets, axis=-1)
predicted_class = np.argmax(predict_fun(params, inputs), axis=-1)
return np.mean(predicted_class == target_class)
def synth_batches():
rng = npr.RandomState(0)
while True:
images = rng.rand(*input_shape).astype('float32')
labels = rng.randint(num_classes, size=(batch_size, 1))
onehot_labels = labels == np.arange(num_classes)
yield images, onehot_labels
opt_init, opt_update, get_params = optimizers.momentum(step_size, mass=0.9)
batches = synth_batches()
@jit
def update(i, opt_state, batch):
params = get_params(opt_state)
return opt_update(i, grad(loss)(params, batch), opt_state)
opt_state = opt_init(init_params)
for i in xrange(num_steps):
opt_state = update(i, opt_state, next(batches))
trained_params = get_params(opt_state)
|
jax-master
|
examples/resnet50.py
|
#!/usr/bin/python
#
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
#
# Helper script for building JAX's libjax easily.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import collections
import hashlib
import os
import platform
import re
import shutil
import stat
import subprocess
import sys
import urllib
# pylint: disable=g-import-not-at-top
if hasattr(urllib, "urlretrieve"):
urlretrieve = urllib.urlretrieve
else:
import urllib.request
urlretrieve = urllib.request.urlretrieve
if hasattr(shutil, "which"):
which = shutil.which
else:
from distutils.spawn import find_executable as which
# pylint: enable=g-import-not-at-top
def shell(cmd):
output = subprocess.check_output(cmd)
return output.decode("UTF-8").strip()
# Python
def get_python_bin_path(python_bin_path_flag):
"""Returns the path to the Python interpreter to use."""
return python_bin_path_flag or sys.executable
# Bazel
BAZEL_BASE_URI = "https://github.com/bazelbuild/bazel/releases/download/0.29.1/"
BazelPackage = collections.namedtuple("BazelPackage", ["file", "sha256"])
bazel_packages = {
"Linux":
BazelPackage(
file="bazel-0.29.1-linux-x86_64",
sha256=
"da3031d811f42f6208d24a87984b5b07e1c75afede184cad86eb02bef6c3b9b0"),
"Darwin":
BazelPackage(
file="bazel-0.29.1-darwin-x86_64",
sha256=
"34daae4caafbdb0952415ed6f97f47f03df84df9af146e9eb910ba65c073efdd"),
}
def download_and_verify_bazel():
"""Downloads a bazel binary from Github, verifying its SHA256 hash."""
package = bazel_packages.get(platform.system())
if package is None:
return None
if not os.access(package.file, os.X_OK):
uri = BAZEL_BASE_URI + package.file
sys.stdout.write("Downloading bazel from: {}\n".format(uri))
def progress(block_count, block_size, total_size):
if total_size <= 0:
total_size = 170**6
progress = (block_count * block_size) / total_size
num_chars = 40
progress_chars = int(num_chars * progress)
sys.stdout.write("{} [{}{}] {}%\r".format(
package.file, "#" * progress_chars,
"." * (num_chars - progress_chars), int(progress * 100.0)))
tmp_path, _ = urlretrieve(uri, None, progress)
sys.stdout.write("\n")
# Verify that the downloaded Bazel binary has the expected SHA256.
downloaded_file = open(tmp_path, "rb")
contents = downloaded_file.read()
downloaded_file.close()
digest = hashlib.sha256(contents).hexdigest()
if digest != package.sha256:
print(
"Checksum mismatch for downloaded bazel binary (expected {}; got {})."
.format(package.sha256, digest))
sys.exit(-1)
# Write the file as the bazel file name.
out_file = open(package.file, "wb")
out_file.write(contents)
out_file.close()
# Mark the file as executable.
st = os.stat(package.file)
os.chmod(package.file,
st.st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
return "./" + package.file
def get_bazel_path(bazel_path_flag):
"""Returns the path to a Bazel binary, downloading Bazel if not found."""
if bazel_path_flag:
return bazel_path_flag
bazel = which("bazel")
if bazel:
return bazel
bazel = download_and_verify_bazel()
if bazel:
return bazel
print("Cannot find or download bazel. Please install bazel.")
sys.exit(-1)
def check_bazel_version(bazel_path, min_version, max_version):
"""Checks Bazel's version is in the range [`min_version`, `max_version`)."""
version_output = shell([bazel_path, "--bazelrc=/dev/null", "version"])
match = re.search("Build label: *([0-9\\.]+)[^0-9\\.]", version_output)
if match is None:
print("Warning: bazel installation is not a release version. Make sure "
"bazel is at least {}".format(min_version))
return
version = match.group(1)
min_ints = [int(x) for x in min_version.split(".")]
actual_ints = [int(x) for x in match.group(1).split(".")]
if min_ints > actual_ints:
print("Outdated bazel revision (>= {} required, found {})".format(
min_version, version))
sys.exit(0)
if max_version is not None:
max_ints = [int(x) for x in max_version.split(".")]
if actual_ints >= max_ints:
print("Please downgrade your bazel revision to build JAX (>= {} and < {}"
" required, found {})".format(min_version, max_version, version))
sys.exit(0)
BAZELRC_TEMPLATE = """
build --repo_env PYTHON_BIN_PATH="{python_bin_path}"
build --python_path="{python_bin_path}"
build --repo_env TF_NEED_CUDA="{tf_need_cuda}"
build --distinct_host_configuration=false
build --copt=-Wno-sign-compare
build -c opt
build:opt --copt=-march=native
build:opt --host_copt=-march=native
build:mkl_open_source_only --define=tensorflow_mkldnn_contraction_kernel=1
# Sets the default Apple platform to macOS.
build --apple_platform_type=macos
build --macos_minimum_os=10.9
# Make Bazel print out all options from rc files.
build --announce_rc
# Disable enabled-by-default TensorFlow features that we don't care about.
build --define=no_aws_support=true
build --define=no_gcp_support=true
build --define=no_hdfs_support=true
build --define=no_kafka_support=true
build --define=no_ignite_support=true
build --define=grpc_no_ares=true
build:cuda --crosstool_top=@local_config_cuda//crosstool:toolchain
build:cuda --define=using_cuda=true --define=using_cuda_nvcc=true
build --spawn_strategy=standalone
build --strategy=Genrule=standalone
build --cxxopt=-std=c++14
build --host_cxxopt=-std=c++14
"""
def write_bazelrc(cuda_toolkit_path=None, cudnn_install_path=None, **kwargs):
f = open("../.bazelrc", "w")
f.write(BAZELRC_TEMPLATE.format(**kwargs))
if cuda_toolkit_path:
f.write("build --action_env CUDA_TOOLKIT_PATH=\"{cuda_toolkit_path}\"\n"
.format(cuda_toolkit_path=cuda_toolkit_path))
if cudnn_install_path:
f.write("build --action_env CUDNN_INSTALL_PATH=\"{cudnn_install_path}\"\n"
.format(cudnn_install_path=cudnn_install_path))
f.close()
BANNER = r"""
_ _ __ __
| | / \ \ \/ /
_ | |/ _ \ \ /
| |_| / ___ \/ \
\___/_/ \/_/\_\
"""
EPILOG = """
From the 'build' directory in the JAX repository, run
python build.py
or
python3 build.py
to download and build JAX's XLA (jaxlib) dependency.
"""
def _parse_string_as_bool(s):
"""Parses a string as a boolean argument."""
lower = s.lower()
if lower == "true":
return True
elif lower == "false":
return False
else:
raise ValueError("Expected either 'true' or 'false'; got {}".format(s))
def add_boolean_argument(parser, name, default=False, help_str=None):
"""Creates a boolean flag."""
group = parser.add_mutually_exclusive_group()
group.add_argument(
"--" + name,
nargs="?",
default=default,
const=True,
type=_parse_string_as_bool,
help=help_str)
group.add_argument("--no" + name, dest=name, action="store_false")
def main():
parser = argparse.ArgumentParser(
description="Builds libjax from source.", epilog=EPILOG)
parser.add_argument(
"--bazel_path",
help="Path to the Bazel binary to use. The default is to find bazel via "
"the PATH; if none is found, downloads a fresh copy of bazel from "
"GitHub.")
parser.add_argument(
"--python_bin_path",
help="Path to Python binary to use. The default is the Python "
"interpreter used to run the build script.")
add_boolean_argument(
parser,
"enable_march_native",
default=False,
help_str="Generate code targeted to the current machine? This may "
"increase performance, but may generate code that does not run on "
"older machines.")
add_boolean_argument(
parser,
"enable_mkl_dnn",
default=True,
help_str="Should we build with MKL-DNN enabled?")
add_boolean_argument(
parser,
"enable_cuda",
help_str="Should we build with CUDA enabled? Requires CUDA and CuDNN.")
parser.add_argument(
"--cuda_path",
default=None,
help="Path to the CUDA toolkit.")
parser.add_argument(
"--cudnn_path",
default=None,
help="Path to CUDNN libraries.")
parser.add_argument(
"--bazel_startup_options",
action="append", default=[],
help="Additional startup options to pass to bazel.")
parser.add_argument(
"--bazel_options",
action="append", default=[],
help="Additional options to pass to bazel.")
args = parser.parse_args()
print(BANNER)
os.chdir(os.path.dirname(__file__ or args.prog) or '.')
# Find a working Bazel.
bazel_path = get_bazel_path(args.bazel_path)
check_bazel_version(bazel_path, min_version="0.24.0", max_version=None)
print("Bazel binary path: {}".format(bazel_path))
python_bin_path = get_python_bin_path(args.python_bin_path)
print("Python binary path: {}".format(python_bin_path))
print("MKL-DNN enabled: {}".format("yes" if args.enable_mkl_dnn else "no"))
print("-march=native: {}".format("yes" if args.enable_march_native else "no"))
cuda_toolkit_path = args.cuda_path
cudnn_install_path = args.cudnn_path
print("CUDA enabled: {}".format("yes" if args.enable_cuda else "no"))
if args.enable_cuda:
if cuda_toolkit_path:
print("CUDA toolkit path: {}".format(cuda_toolkit_path))
if cudnn_install_path:
print("CUDNN library path: {}".format(cudnn_install_path))
write_bazelrc(
python_bin_path=python_bin_path,
tf_need_cuda=1 if args.enable_cuda else 0,
cuda_toolkit_path=cuda_toolkit_path,
cudnn_install_path=cudnn_install_path)
print("\nBuilding XLA and installing it in the jaxlib source tree...")
config_args = args.bazel_options
if args.enable_march_native:
config_args += ["--config=opt"]
if args.enable_mkl_dnn:
config_args += ["--config=mkl_open_source_only"]
if args.enable_cuda:
config_args += ["--config=cuda"]
config_args += ["--define=xla_python_enable_gpu=true"]
command = ([bazel_path] + args.bazel_startup_options +
["run", "--verbose_failures=true"] + config_args +
[":install_xla_in_source_tree", os.getcwd()])
print(" ".join(command))
shell(command)
shell([bazel_path, "shutdown"])
if __name__ == "__main__":
main()
|
jax-master
|
build/build.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from setuptools import setup
from glob import glob
import os
global __version__
__version__ = None
with open('jaxlib/version.py') as f:
exec(f.read(), globals())
binary_libs = [os.path.basename(f) for f in glob('jaxlib/*.so*')]
setup(
name='jaxlib',
version=__version__,
description='XLA library for JAX',
author='JAX team',
author_email='jax-dev@google.com',
packages=['jaxlib'],
install_requires=['scipy', 'numpy>=1.12', 'six', 'protobuf>=3.6.0', 'absl-py'],
url='https://github.com/google/jax',
license='Apache-2.0',
package_data={'jaxlib': binary_libs},
)
|
jax-master
|
build/setup.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from .version import __version__
|
jax-master
|
build/jaxlib/__init__.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as onp
import six
from . import core
from . import ad_util
from . import dtypes
from . util import prod, partialmethod
def concretization_err_msg(fun):
fname = getattr(fun, "__name__", fun)
msg = ("Abstract value passed to `{}`, which requires a concrete value. "
"The function to be transformed can't be traced at the required level "
"of abstraction. If using `jit`, try using `static_argnums` or "
"applying `jit` to smaller subfunctions instead.")
return msg.format(fname)
def concretization_function_error(fun):
def error(self, *args):
raise TypeError(concretization_err_msg(fun))
return error
class UnshapedArray(core.AbstractValue):
__slots__ = ['dtype', 'weak_type']
array_abstraction_level = 2
def __init__(self, dtype, weak_type=False):
self.dtype = onp.dtype(dtypes.canonicalize_dtype(dtype))
self.weak_type = weak_type
def __eq__(self, other):
return (type(self) is type(other) and self.dtype == other.dtype and
self.weak_type == other.weak_type)
def __ne__(self, other):
return not self == other
def __hash__(self):
# can use hash(self.dtype) and rely on the fact that numpy reuses base dtype
# objects, e.g. `onp.zeros(3).dtype is onp.zeros(4).dtype`, or we can use
# the unique character code via hash(self.dtype.char)
return hash((self.dtype, self.weak_type))
def __repr__(self):
return '{}({}{})'.format(self.__class__.__name__, self.str_short(),
", weak_type=True" if self.weak_type else "")
_bool = _nonzero = concretization_function_error(bool)
_float = concretization_function_error(float)
_int = concretization_function_error(int)
if six.PY2:
_long = concretization_function_error(long) # noqa: F821
_complex = concretization_function_error(complex)
_hex = concretization_function_error(hex)
_oct = concretization_function_error(oct)
def at_least_vspace(self):
return self
def join(self, other):
if self.dtype == other.dtype:
if self.weak_type == other.weak_type:
return self
else:
return UnshapedArray(self.dtype, weak_type=False)
else:
raise TypeError(self, other)
def str_short(self):
return self.dtype.name
def strip_weak_type(self):
"""Returns a copy of the aval with weak_type=False."""
return UnshapedArray(self.dtype) if self.weak_type else self
class ShapedArray(UnshapedArray):
__slots__ = ['shape']
array_abstraction_level = 1
def __init__(self, shape, dtype, weak_type=False):
super(ShapedArray, self).__init__(dtype, weak_type=weak_type)
self.shape = shape
ndim = property(lambda self: len(self.shape))
size = property(lambda self: prod(self.shape))
def __eq__(self, other):
return (type(self) is type(other)
and self.dtype == other.dtype and self.shape == other.shape
and self.weak_type == other.weak_type)
def __hash__(self):
# can use hash(self.dtype) and rely on the fact that numpy reuses base dtype
# objects, e.g. `onp.zeros(3).dtype is onp.zeros(4).dtype`, or we can use
# the unique character code via hash(self.dtype.char)
return hash((self.shape, self.dtype, self.weak_type))
def at_least_vspace(self):
return self
def join(self, other):
if self.shape == other.shape and self.dtype == other.dtype:
if self.weak_type == other.weak_type:
return self
else:
return ShapedArray(self.shape, self.dtype, weak_type=False)
elif self.dtype == other.dtype:
return UnshapedArray(self.dtype)
else:
raise TypeError(self, other)
def str_short(self):
shapestr = ','.join(map(str, self.shape))
return '{}[{}]'.format(self.dtype.name, shapestr)
def __len__(self):
try:
return self.shape[0]
except IndexError:
raise TypeError("len() of unsized object") # same as numpy error
def _len(self, ignored_tracer):
return len(self)
def strip_weak_type(self):
return ShapedArray(self.shape, self.dtype) if self.weak_type else self
def _forward_to_value(self, fun, ignored_tracer, *args):
return fun(self.val, *args)
class ConcreteArray(ShapedArray):
__slots__ = ['val']
array_abstraction_level = 0
def __init__(self, val, weak_type=False):
super(ConcreteArray, self).__init__(onp.shape(val), onp.result_type(val),
weak_type=weak_type)
# Note: canonicalized self.dtype doesn't necessarily match self.val
self.val = val
assert self.dtype != onp.dtype('O')
def __eq__(self, other):
return (type(self) is type(other) and self.dtype == other.dtype
and self.shape == other.shape and self.weak_type == other.weak_type
and onp.all(self.val == other.val))
def __hash__(self):
return id(self.val)
def at_least_vspace(self):
return ShapedArray(self.shape, self.dtype, weak_type=self.weak_type)
def join(self, other):
if self == other:
return self
elif self.shape == other.shape and self.dtype == other.dtype:
return ShapedArray(self.shape, self.dtype,
weak_type=self.weak_type and other.weak_type)
elif self.dtype == other.dtype:
return UnshapedArray(self.dtype,
weak_type=self.weak_type and other.weak_type)
else:
raise TypeError(self, other)
def str_short(self):
return str(self.val)
def strip_weak_type(self):
return ConcreteArray(self.val) if self.weak_type else self
_bool = _nonzero = partialmethod(_forward_to_value, bool)
_float = partialmethod(_forward_to_value, float)
_int = partialmethod(_forward_to_value, int)
if six.PY2:
_long = partialmethod(_forward_to_value, long) # noqa: F821
_complex = partialmethod(_forward_to_value, complex)
_hex = partialmethod(_forward_to_value, hex)
_oct = partialmethod(_forward_to_value, oct)
class AbstractToken(core.AbstractValue): pass
abstract_token = AbstractToken()
def make_shaped_array(x):
dtype = dtypes.canonicalize_dtype(dtypes.result_type(x))
return ShapedArray(onp.shape(x), dtype)
def zeros_like_array(x):
dtype = dtypes.canonicalize_dtype(dtypes.result_type(x))
return onp.broadcast_to(onp.array(0, dtype), onp.shape(x))
array_types = {onp.ndarray, onp.bool_,
onp.int8, onp.int16, onp.int32, onp.int64,
onp.uint8, onp.uint16, onp.uint32, onp.uint64,
dtypes.bfloat16, onp.float16, onp.float32, onp.float64,
onp.complex64, onp.complex128,
onp.longlong}
for t in array_types:
core.pytype_aval_mappings[t] = ConcreteArray
ad_util.jaxval_zeros_likers[t] = zeros_like_array
def zeros_like_shaped_array(aval):
assert isinstance(aval, ShapedArray)
return onp.zeros(aval.shape, dtype=aval.dtype)
ad_util.aval_zeros_likers[ShapedArray] = zeros_like_shaped_array
def raise_to_shaped(aval, weak_type=False):
if isinstance(aval, ShapedArray):
return ShapedArray(aval.shape, aval.dtype, weak_type=weak_type)
elif aval is core.abstract_unit:
return core.abstract_unit
elif aval is abstract_token:
return abstract_token
else:
raise TypeError(type(aval))
core.literalable_types.update(array_types)
def _zeros_like_python_scalar(x):
return onp.array(0, dtypes.python_scalar_dtypes[type(x)])
def _make_concrete_python_scalar(x):
return ConcreteArray(
onp.array(x, dtype=dtypes.python_scalar_dtypes[type(x)]),
weak_type=True)
for t in dtypes.python_scalar_dtypes.keys():
core.pytype_aval_mappings[t] = _make_concrete_python_scalar
ad_util.jaxval_zeros_likers[t] = _zeros_like_python_scalar
core.literalable_types.update(dtypes.python_scalar_dtypes.keys())
|
jax-master
|
jax/abstract_arrays.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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 sys
class Config(object):
def __init__(self):
self.values = {}
self.meta = {}
self.FLAGS = NameSpace(self.read)
self.use_absl = False
def update(self, name, val):
if self.use_absl:
setattr(self.absl_flags.FLAGS, name, val)
else:
self.check_exists(name)
if name not in self.values:
raise Exception("Unrecognized config option: {}".format(name))
self.values[name] = val
def read(self, name):
if self.use_absl:
return getattr(self.absl_flags.FLAGS, name)
else:
self.check_exists(name)
return self.values[name]
def add_option(self, name, default, opt_type, meta_args, meta_kwargs):
if name in self.values:
raise Exception("Config option {} already defined".format(name))
self.values[name] = default
self.meta[name] = (opt_type, meta_args, meta_kwargs)
def check_exists(self, name):
if name not in self.values:
raise Exception("Unrecognized config option: {}".format(name))
def DEFINE_bool(self, name, default, *args, **kwargs):
self.add_option(name, default, bool, args, kwargs)
def DEFINE_integer(self, name, default, *args, **kwargs):
self.add_option(name, default, int, args, kwargs)
def DEFINE_string(self, name, default, *args, **kwargs):
self.add_option(name, default, str, args, kwargs)
def DEFINE_enum(self, name, default, *args, **kwargs):
self.add_option(name, default, 'enum', args, kwargs)
def config_with_absl(self):
# Run this before calling `app.run(main)` etc
import absl.flags as absl_FLAGS
from absl import app, flags as absl_flags
self.use_absl = True
self.absl_flags = absl_flags
absl_defs = { bool: absl_flags.DEFINE_bool,
int: absl_flags.DEFINE_integer,
str: absl_flags.DEFINE_string,
'enum': absl_flags.DEFINE_enum }
for name, val in self.values.items():
flag_type, meta_args, meta_kwargs = self.meta[name]
absl_defs[flag_type](name, val, *meta_args, **meta_kwargs)
app.call_after_init(lambda: self.complete_absl_config(absl_flags))
def complete_absl_config(self, absl_flags):
for name, _ in self.values.items():
self.update(name, getattr(absl_flags.FLAGS, name))
def parse_flags_with_absl(self):
global already_configured_with_absl
if not already_configured_with_absl:
import absl.flags
self.config_with_absl()
absl.flags.FLAGS(sys.argv, known_only=True)
self.complete_absl_config(absl.flags)
already_configured_with_absl = True
class NameSpace(object):
def __init__(self, getter):
self._getter = getter
def __getattr__(self, name):
return self._getter(name)
config = Config()
flags = config
already_configured_with_absl = False
|
jax-master
|
jax/config.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
__version__ = "0.1.56"
|
jax-master
|
jax/version.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .core import lattice_join, Primitive, Unit, unit, AbstractUnit, abstract_unit
from .tree_util import register_pytree_node
from .util import safe_map
map = safe_map
jaxval_adders = {}
jaxval_adders[Unit] = lambda _, __: unit
def add_jaxvals(x, y):
return add_jaxvals_p.bind(x, y)
add_jaxvals_p = Primitive('add_any')
@add_jaxvals_p.def_impl
def add_impl(xs, ys):
# assert type(xs) == type(ys), (xs, ys)
return jaxval_adders[type(xs)](xs, ys)
@add_jaxvals_p.def_abstract_eval
def add_abstract(xs, ys):
return lattice_join(xs, ys)
def zeros_like_impl_jaxtuple(xs):
return JaxTuple(map(zeros_like_impl, xs))
jaxval_zeros_likers = {}
def zeros_like_aval(aval):
return aval_zeros_likers[type(aval)](aval)
aval_zeros_likers = {}
aval_zeros_likers[AbstractUnit] = lambda _: unit
def zeros_like_jaxval(val):
return zeros_like_p.bind(val)
zeros_like_p = Primitive('zeros_like')
@zeros_like_p.def_impl
def zeros_like_impl(example):
return jaxval_zeros_likers[type(example)](example)
zeros_like_p.def_abstract_eval(lambda x: x)
class Zero(object):
def __repr__(self):
return "Zero"
zero = Zero()
register_pytree_node(Zero, lambda z: ((), None), lambda _, xs: zero)
|
jax-master
|
jax/ad_util.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import functools
import itertools as it
import types
import fastcache
import numpy as onp
def safe_zip(*args):
n = len(args[0])
for arg in args[1:]:
assert len(arg) == n, 'length mismatch: {}'.format(list(map(len, args)))
return list(zip(*args))
def safe_map(f, *args):
args = list(map(list, args))
n = len(args[0])
for arg in args[1:]:
assert len(arg) == n, 'length mismatch: {}'.format(list(map(len, args)))
return list(map(f, *args))
def unzip2(xys):
xs = []
ys = []
for x, y in xys:
xs.append(x)
ys.append(y)
return tuple(xs), tuple(ys)
def unzip3(xyzs):
xs = []
ys = []
zs = []
for x, y, z in xyzs:
xs.append(x)
ys.append(y)
zs.append(z)
return tuple(xs), tuple(ys), tuple(zs)
def split_list(args, ns):
assert type(ns) is list
args = list(args)
lists = []
for n in ns:
lists.append(args[:n])
args = args[n:]
lists.append(args)
return lists
def split_dict(dct, names):
dct = dict(dct)
lst = [dct.pop(name) for name in names]
assert not dct
return lst
def concatenate(xs):
return list(it.chain.from_iterable(xs))
def partial(fun, *args, **kwargs):
wrapped = functools.partial(fun, *args, **kwargs)
functools.update_wrapper(wrapped, fun)
wrapped._bound_args = args
return wrapped
class partialmethod(functools.partial):
def __get__(self, instance, owner):
if instance is None:
return self
else:
return partial(self.func, instance,
*(self.args or ()), **(self.keywords or {}))
def curry(f):
"""Curries arguments of f, returning a function on any remaining arguments.
For example:
>>> f = lambda x, y, z, w: x * y + z * w
>>> f(2,3,4,5)
26
>>> curry(f)(2)(3, 4, 5)
26
>>> curry(f)(2, 3)(4, 5)
26
>>> curry(f)(2, 3, 4, 5)()
26
"""
return partial(partial, f)
def toposort(end_nodes):
if not end_nodes: return []
end_nodes = _remove_duplicates(end_nodes)
child_counts = {}
stack = list(end_nodes)
while stack:
node = stack.pop()
if id(node) in child_counts:
child_counts[id(node)] += 1
else:
child_counts[id(node)] = 1
stack.extend(node.parents)
for node in end_nodes:
child_counts[id(node)] -= 1
sorted_nodes = []
childless_nodes = [node for node in end_nodes if child_counts[id(node)] == 0]
assert childless_nodes
while childless_nodes:
node = childless_nodes.pop()
sorted_nodes.append(node)
for parent in node.parents:
if child_counts[id(parent)] == 1:
childless_nodes.append(parent)
else:
child_counts[id(parent)] -= 1
check_toposort(sorted_nodes[::-1])
return sorted_nodes[::-1]
def check_toposort(nodes):
visited = set()
for node in nodes:
assert all(id(parent) in visited for parent in node.parents)
visited.add(id(node))
def _remove_duplicates(node_list):
seen = set()
out = []
for n in node_list:
if id(n) not in seen:
seen.add(id(n))
out.append(n)
return out
def split_merge(predicate, xs):
sides = list(map(predicate, xs))
lhs = [x for x, s in zip(xs, sides) if s]
rhs = [x for x, s in zip(xs, sides) if not s]
def merge(new_lhs, new_rhs):
out = []
for s in sides:
if s:
out.append(new_lhs[0])
new_lhs = new_lhs[1:]
else:
out.append(new_rhs[0])
new_rhs = new_rhs[1:]
assert not new_rhs
assert not new_lhs
return out
return lhs, rhs, merge
def cache(max_size=4096):
return fastcache.clru_cache(maxsize=max_size)
memoize = fastcache.clru_cache(maxsize=None)
def prod(xs):
out = 1
for x in xs:
out *= x
return out
class WrapHashably(object):
__slots__ = ["val"]
def __init__(self, val):
self.val = val
def __hash__(self):
return id(self.val)
def __eq__(self, other):
return self.val is other.val
class Hashable(object):
__slots__ = ["val"]
def __init__(self, val):
self.val = val
def __hash__(self):
return hash(self.val)
def __eq__(self, other):
return self.val == other.val
def get_module_functions(module):
"""Finds functions in module.
Args:
module: A Python module.
Returns:
module_fns: A set of functions, builtins or ufuncs in `module`.
"""
module_fns = set()
for key in dir(module):
# Omitting module level __getattr__, __dir__ which was added in Python 3.7
# https://www.python.org/dev/peps/pep-0562/
if key in ('__getattr__', '__dir__'):
continue
attr = getattr(module, key)
if isinstance(
attr, (types.BuiltinFunctionType, types.FunctionType, onp.ufunc)):
module_fns.add(attr)
return module_fns
|
jax-master
|
jax/util.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import itertools
import numpy as onp
import opt_einsum
import scipy.special
from six.moves import builtins
from . import dtypes
_slice = builtins.slice
_max = builtins.max
_min = builtins.min
_map = builtins.map
neg = onp.negative
sign = onp.sign
floor = onp.floor
ceil = onp.ceil
round = onp.round
nextafter = onp.nextafter
is_finite = onp.isfinite
exp = onp.exp
expm1 = onp.expm1
log = onp.log
log1p = onp.log1p
tanh = onp.tanh
sin = onp.sin
cos = onp.cos
atan2 = onp.arctan2
sqrt = onp.sqrt
rsqrt = lambda x: 1. / onp.sqrt(x)
square = onp.square
reciprocal = onp.reciprocal
tan = onp.tan
asin = onp.arcsin
acos = onp.arccos
atan = onp.arctan
sinh = onp.sinh
cosh = onp.cosh
lgamma = scipy.special.gammaln
digamma = scipy.special.digamma
erf = scipy.special.erf
erfc = scipy.special.erfc
erf_inv = scipy.special.erfinv
bessel_i0e = scipy.special.i0e
bessel_i1e = scipy.special.i1e
real = onp.real
imag = onp.imag
def conj(x):
return onp.conj(x) + onp.complex64(0)
def complex(x, y):
return x + onp.complex64(1j) * y
abs = onp.absolute
pow = onp.power
bitwise_not = onp.bitwise_not
bitwise_and = onp.bitwise_and
bitwise_or = onp.bitwise_or
bitwise_xor = onp.bitwise_xor
add = onp.add
sub = onp.subtract
mul = onp.multiply
def div(lhs, rhs):
if dtypes.issubdtype(dtypes.result_type(lhs), onp.integer):
quotient = onp.floor_divide(lhs, rhs)
select = onp.logical_and(onp.sign(lhs) != onp.sign(rhs),
onp.remainder(lhs, rhs) != 0)
return onp.where(select, quotient + 1, quotient)
else:
return onp.divide(lhs, rhs)
def rem(lhs, rhs):
return onp.sign(lhs) * onp.remainder(onp.abs(lhs), onp.abs(rhs))
max = onp.maximum
min = onp.minimum
shift_left = onp.left_shift
shift_right_arithmetic = onp.right_shift
# TODO shift_right_logical
eq = onp.equal
ne = onp.not_equal
ge = onp.greater_equal
gt = onp.greater
le = onp.less_equal
lt = onp.less
def convert_element_type(operand, dtype):
return onp.asarray(operand, dtype=dtype)
def bitcast_convert_type(operand, dtype):
return onp.asarray(operand).view(dtype)
def clamp(min, operand, max):
return onp.clip(operand, onp.clip(min, None, max), max)
def concatenate(operands, dimension):
return onp.concatenate(operands, axis=dimension)
def conv(lhs, rhs, window_strides, padding):
pads = padtype_to_pads(lhs.shape[2:], rhs.shape[2:], window_strides, padding)
return _conv(lhs, rhs, window_strides, pads)
def conv_with_general_padding(
lhs, rhs, window_strides, padding, lhs_dilation, rhs_dilation):
return _conv(_dilate(lhs, lhs_dilation), _dilate(rhs, rhs_dilation),
window_strides, padding)
def conv_general_dilated(lhs, rhs, window_strides, padding, lhs_dilation,
rhs_dilation, dimension_numbers):
lhs_perm, rhs_perm, out_perm = _conv_general_permutations(dimension_numbers)
if isinstance(padding, str):
padding = padtype_to_pads(onp.take(lhs.shape, lhs_perm)[2:],
onp.take(rhs.shape, rhs_perm)[2:],
window_strides, padding)
trans_lhs = transpose(lhs, lhs_perm)
trans_rhs = transpose(rhs, rhs_perm)
out = conv_with_general_padding(trans_lhs, trans_rhs, window_strides, padding,
lhs_dilation, rhs_dilation)
return transpose(out, onp.argsort(out_perm))
dot = onp.dot
def dot_general(lhs, rhs, dimension_numbers):
(lhs_contracting, rhs_contracting), (lhs_batch, rhs_batch) = dimension_numbers
new_id = itertools.count()
lhs_axis_ids = [next(new_id) for _ in lhs.shape]
rhs_axis_ids = [next(new_id) for _ in rhs.shape]
lhs_out_axis_ids = lhs_axis_ids[:]
rhs_out_axis_ids = rhs_axis_ids[:]
for lhs_axis, rhs_axis in zip(lhs_contracting, rhs_contracting):
shared_id = next(new_id)
lhs_axis_ids[lhs_axis] = shared_id
rhs_axis_ids[rhs_axis] = shared_id
lhs_out_axis_ids[lhs_axis] = None
rhs_out_axis_ids[rhs_axis] = None
batch_ids = []
for lhs_axis, rhs_axis in zip(lhs_batch, rhs_batch):
shared_id = next(new_id)
lhs_axis_ids[lhs_axis] = shared_id
rhs_axis_ids[rhs_axis] = shared_id
lhs_out_axis_ids[lhs_axis] = None
rhs_out_axis_ids[rhs_axis] = None
batch_ids.append(shared_id)
not_none = lambda x: x is not None
out_axis_ids = filter(not_none,
batch_ids + lhs_out_axis_ids + rhs_out_axis_ids)
assert lhs.dtype == rhs.dtype
dtype = onp.float32 if lhs.dtype == dtypes.bfloat16 else None
out = onp.einsum(lhs, lhs_axis_ids, rhs, rhs_axis_ids, out_axis_ids,
dtype=dtype)
return out.astype(dtypes.bfloat16) if lhs.dtype == dtypes.bfloat16 else out
def broadcast(operand, sizes):
return onp.broadcast_to(operand, sizes + onp.shape(operand))
def broadcast_in_dim(operand, shape, broadcast_dimensions):
inshape = tuple(1 if i not in broadcast_dimensions else d
for i, d in enumerate(shape))
return onp.broadcast_to(onp.reshape(operand, inshape), shape)
sum = onp.sum
def reshape(operand, new_sizes, dimensions=None):
if dimensions is None:
dimensions = range(len(onp.shape(operand)))
return onp.reshape(onp.transpose(operand, dimensions), new_sizes)
def pad(operand, padding_value, padding_config):
lo, hi, interior = zip(*padding_config)
outshape = onp.add(onp.add(onp.add(lo, hi), operand.shape),
onp.multiply(interior, onp.subtract(operand.shape, 1)))
out = onp.full(outshape, padding_value, operand.dtype)
lhs_slices = tuple(_slice(l if l > 0 else 0, -h if h > 0 else None, step)
for l, h, step in zip(lo, hi, onp.add(1, interior)))
rhs_slices = tuple(_slice(l if l < 0 else 0, -h if h < 0 else None)
for l, h in zip(lo, hi))
out[lhs_slices] = operand[rhs_slices]
return out
def rev(operand, dimensions):
dimensions = frozenset(dimensions)
indexer = (_slice(None, None, -1) if d in dimensions else _slice(None)
for d in range(onp.ndim(operand)))
return operand[tuple(indexer)]
select = onp.where
def slice(operand, start_indices, limit_indices, strides=None): # pylint: disable=redefined-builtin
if strides is None:
strides = onp.ones(len(start_indices)).astype(int)
slices = tuple(_map(_slice, start_indices, limit_indices, strides))
return operand[slices]
def dynamic_slice(operand, start_indices, slice_sizes):
out = onp.zeros(slice_sizes, dtype=operand.dtype)
idx = tuple(_slice(start, start+size)
for start, size in zip(start_indices, slice_sizes))
section = operand[idx]
out[tuple(_slice(None, stop) for stop in section.shape)] = section
return out
def dynamic_update_slice(operand, update, start_indices):
slices = tuple(_map(_slice, start_indices, onp.add(start_indices, update.shape)))
updated_operand = onp.copy(operand)
updated_operand[slices] = update
return updated_operand
transpose = onp.transpose
def reduce(operand, init_value, computation, dimensions): # pylint: disable=redefined-builtin
reducer = _make_reducer(computation, init_value)
return reducer(operand, tuple(dimensions)).astype(onp.asarray(operand).dtype)
def reduce_window(operand, init_value, computation, window_dimensions,
window_strides, padding):
op, dims, strides = operand, window_dimensions, window_strides
pads = padtype_to_pads(op.shape, dims, strides, padding)
view = _conv_view(op.reshape((1, 1) + op.shape), (1, 1) + dims, strides, pads,
pad_value=init_value)[0]
view = view.reshape(view.shape[1:1+len(dims)] + (-1,))
reducer = _make_reducer(computation, init_value)
return reducer(view, axis=-1)
# TODO(mattjj): select_and_scatter
sort = onp.sort
def sort_key_val(keys, values, dimension=-1):
idxs = list(onp.ix_(*[onp.arange(d) for d in keys.shape]))
idxs[dimension] = onp.argsort(keys, axis=dimension)
return keys[idxs], values[idxs]
# TODO untake
### conv util
def _conv(lhs, rhs, window_strides, pads):
view, view_axes, rhs_axes, out_axes = _conv_view(
lhs, rhs.shape, window_strides, pads, 0.)
return opt_einsum.contract(
view, view_axes, rhs, rhs_axes, out_axes, use_blas=True)
def padtype_to_pads(in_shape, filter_shape, window_strides, padding):
if padding.upper() == 'SAME':
out_shape = onp.ceil(onp.true_divide(in_shape, window_strides)).astype(int)
pad_sizes = [_max((out_size - 1) * stride + filter_size - in_size, 0)
for out_size, stride, filter_size, in_size
in zip(out_shape, window_strides, filter_shape, in_shape)]
return [(pad_size // 2, pad_size - pad_size // 2) for pad_size in pad_sizes]
else:
return [(0, 0)] * len(in_shape)
def _conv_view(lhs, rhs_shape, window_strides, pads, pad_value):
"""Compute the view (and its axes) of a convolution or window reduction."""
if (_min(lhs.ndim, len(rhs_shape)) < 2 or lhs.ndim != len(rhs_shape)
or lhs.shape[1] != rhs_shape[1]):
raise ValueError('Dimension mismatch')
if len(window_strides) != len(rhs_shape) - 2:
raise ValueError('Wrong number of strides for spatial dimensions')
if len(pads) != len(rhs_shape) - 2:
raise ValueError('Wrong number of pads for spatial dimensions')
lhs = _pad(lhs, [(0, 0)] * 2 + list(pads), pad_value)
in_shape = lhs.shape[2:]
filter_shape = rhs_shape[2:]
dim = len(filter_shape) # number of 'spatial' dimensions in convolution
out_strides = onp.multiply(window_strides, lhs.strides[2:])
view_strides = lhs.strides[:1] + tuple(out_strides) + lhs.strides[1:]
out_shape = onp.floor_divide(
onp.subtract(in_shape, filter_shape), window_strides) + 1
view_shape = lhs.shape[:1] + tuple(out_shape) + rhs_shape[1:]
view = onp.lib.stride_tricks.as_strided(lhs, view_shape, view_strides)
view_axes = list(range(view.ndim))
sum_axes = view_axes[-dim-1:]
rhs_axes = [view.ndim] + sum_axes
out_axes = [0, view.ndim] + list(range(1, dim+1))
return view, view_axes, rhs_axes, out_axes
def _pad(arr, pads, pad_value):
out = onp.pad(arr, onp.maximum(0, pads), mode='constant',
constant_values=pad_value).astype(arr.dtype)
slices = tuple(_slice(abs(lo) if lo < 0 else 0, hi % dim if hi < 0 else None)
for (lo, hi), dim in zip(pads, onp.shape(arr)))
return out[slices]
def _dilate(operand, factors):
# this logic is like lax.pad, but with two leading dimensions, no edge
# padding, and factors are at least 1 (interior padding is at least 0)
outspace = onp.add(operand.shape[2:],
onp.multiply(onp.subtract(factors, 1),
onp.subtract(operand.shape[2:], 1)))
out = onp.zeros(operand.shape[:2] + tuple(outspace), operand.dtype)
lhs_slices = tuple(_slice(None, None, step) for step in factors)
out[(_slice(None),) * 2 + lhs_slices] = operand
return out
def _conv_general_permutations(dimension_numbers):
lhs_spec, rhs_spec, out_spec = dimension_numbers
rhs_perm = ((rhs_spec.index('O'), rhs_spec.index('I'))
+ tuple(i for i, c in enumerate(rhs_spec) if c not in {'O', 'I'}))
lhs_perm = ((lhs_spec.index('N'), lhs_spec.index('C'))
+ tuple(sorted((i for i, c in enumerate(lhs_spec)
if c not in {'N', 'C'}),
key=lambda i: rhs_spec.index(lhs_spec[i]))))
out_perm = ((out_spec.index('N'), out_spec.index('C'))
+ tuple(sorted((i for i, c in enumerate(out_spec)
if c not in {'N', 'C'}),
key=lambda i: rhs_spec.index(out_spec[i]))))
return lhs_perm, rhs_perm, out_perm
### reduce util
def _make_reducer(py_binop, init_val):
"""Make a reducer function given a Python binop and an initial value."""
# It's tempting to use onp.ufunc.reduce (even with a ufunc generated by
# onp.frompyfunc(py_binop)), but this may not agree with custom init_val.
# We make an attempt to uncover an underlying numpy ufunc (which might be
# wrapped by autograd or lax) and check its identity against init_val.
monoid_record = _monoids.get(getattr(py_binop, '__name__'))
if monoid_record:
reducer, monoid_identity = monoid_record
if init_val == monoid_identity(dtypes.result_type(init_val)):
return reducer
return _reducer_from_pyfunc(py_binop, init_val)
def _get_max_identity(dt):
return -onp.inf if dtypes.issubdtype(dt, onp.floating) else onp.iinfo(dt).min
def _get_min_identity(dt):
return onp.inf if dtypes.issubdtype(dt, onp.floating) else onp.iinfo(dt).max
def _identity_getter(op):
return lambda dtype: onp.asarray(op.identity, dtype=dtype)
MonoidRecord = collections.namedtuple('MonoidRecord', ['reducer', 'identity'])
_monoids = {
'max': MonoidRecord(onp.maximum.reduce, _get_max_identity),
'min': MonoidRecord(onp.minimum.reduce, _get_min_identity),
'add': MonoidRecord(onp.add.reduce, _identity_getter(onp.add)),
'mul': MonoidRecord(onp.multiply.reduce, _identity_getter(onp.multiply)),
'multiply': MonoidRecord(onp.multiply.reduce,
_identity_getter(onp.multiply)),
'logical_and': MonoidRecord(onp.logical_and.reduce,
_identity_getter(onp.logical_and)),
'logical_or': MonoidRecord(onp.logical_or.reduce,
_identity_getter(onp.logical_or)),
}
def _reducer_from_pyfunc(py_binop, init_val):
def reducer(operand, axis=0):
axis = range(onp.ndim(operand)) if axis is None else axis
result = onp.full(onp.delete(onp.shape(operand), axis), init_val,
dtype=onp.asarray(operand).dtype)
for idx, _ in onp.ndenumerate(operand):
out_idx = tuple(onp.delete(idx, axis))
result[out_idx] = py_binop(result[out_idx], operand[idx])
return result
return reducer
|
jax-master
|
jax/lax_reference.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
"""
Utilities for defining functions composed with transformations.
For example,
from jax import linear_util as lu
wf = lu.wrap_init(f) # Produce a WrappedFun for applying transformations on `f`
A `WrappedFun` object represents a function `f`, together with a sequence of
nested transformations that are to be applied to the positional and keyword
arguments at call time and function return values at return time.
A transformation can take some static positional arguments that are given
at the wrapping time, and may also return some auxiliary output:
wf, aux_out_thunk = trans1(wf, static_arg)
We can call the transformed function. First, the transformation is applied
to the dynamic args and keyword args to produce new dynamic and keyword args.
Then the underlying function is called and the transformation is applied to
the results.
If there are multiple transformations, they form a stack. The arguments are
transformed first with the last applied transformation; the results are
transformed first with the first applied transformation.
res = wf.call_wrapped(dynamic_args, kwargs)
# Now `aux_out_thunk()` is the auxiliary output.
A transformation is written as a generator function that takes zero or more
static positional arguments (given when the transformation is instantiated),
along with positional and keyword arguments to be transformed.
The generator will yield twice:
@lu.transformation_with_aux
def trans1(static_arg, *dynamic_args, **kwargs):
...
# First yield: pair of transformed (args, kwargs). Get back the results.
results = yield (new_dynamic_args, new_kwargs)
...
# Second yield: pair of (transformed results, and auxiliary output)
yield new_results, auxiliary_output
`WrappedFun` objects explicitly represent the set of transformations so that
they can be used as dictionary keys for memoization. `WrappedFun` objects
compare as equal only if they compute the same function. The static and the
dynamic positional arguments for the generators, and also the auxiliary output
data must be immutable, because it will be stored in function memoization tables.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import weakref
from .util import curry
class StoreException(Exception): pass
class EmptyStoreValue(object): pass
_EMPTY_STORE_VALUE = EmptyStoreValue()
class Store(object):
"""Storage for a value, with checks for overwriting or reading empty store."""
__slots__ = ("_val",)
def __init__(self):
self._val = _EMPTY_STORE_VALUE
def store(self, val):
assert self._val is _EMPTY_STORE_VALUE, "Store occupied"
self._val = val
@property
def val(self):
if not self:
raise StoreException("Store empty")
return self._val
def __nonzero__(self):
return self._val is not _EMPTY_STORE_VALUE
__bool__ = __nonzero__
class WrappedFun(object):
"""Represents a function `f` to which `transforms` are to be applied.
Arguments:
f: the function to be transformed.
transforms: a list of `(gen, gen_static_args)` tuples representing
transformations to apply to `f.` Here `gen` is a generator function
and `gen_static_args` is a tuple of static arguments for the generator. See
description at the start of this module for the expected behavior of the
generator.
stores: a list of out_store for the auxiliary output of the `transforms`.
params: extra parameters to pass as keyword arguments to `f`, along with the
transformed keyword arguments.
"""
__slots__ = ("f", "transforms", "stores", "params")
def __init__(self, f, transforms, stores, params):
self.f = f
self.transforms = transforms
self.stores = stores
self.params = params
@property
def __name__(self):
return getattr(self.f, '__name__', '<unnamed wrapped function>')
def wrap(self, gen, gen_static_args, out_store):
"""Add another transform and its store."""
return WrappedFun(self.f, ((gen, gen_static_args),) + self.transforms,
(out_store,) + self.stores, self.params)
def populate_stores(self, stores):
"""Copy the values from the `stores` into `self.stores`."""
for self_store, other_store in zip(self.stores, stores):
if self_store is not None:
self_store.store(other_store.val)
def call_wrapped(self, *args, **kwargs):
"""Calls the underlying function, applying the transforms.
The positional `args` and keyword `kwargs` are passed to the first
transformation generator.
"""
stack = []
for (gen, gen_static_args), out_store in zip(self.transforms, self.stores):
gen = gen(*(gen_static_args + tuple(args)), **kwargs)
args, kwargs = next(gen)
stack.append((gen, out_store))
gen = None
ans = self.f(*args, **dict(self.params, **kwargs))
del args
while stack:
gen, out_store = stack.pop()
ans = gen.send(ans)
if out_store is not None:
ans, side = ans
out_store.store(side)
return ans
def __repr__(self):
def transform_to_str(x):
i, (gen, args) = x
return "{} : {} {}".format(i, fun_name(gen), fun_name(args))
transformation_stack = map(transform_to_str, enumerate(self.transforms))
return "Wrapped function:\n" + '\n'.join(transformation_stack) + '\nCore: ' + fun_name(self.f) + '\n'
def __hash__(self):
return hash((self.f, self.transforms, self.params))
def __eq__(self, other):
return (self.f == other.f and self.transforms == other.transforms and
self.params == other.params)
@curry
def transformation(gen, fun, *gen_static_args):
"""Adds one more transformation to a WrappedFun.
Args:
gen: the transformation generator function
fun: a WrappedFun on which to apply the transformation
gen_static_args: static args for the generator function
"""
return fun.wrap(gen, gen_static_args, None)
@curry
def transformation_with_aux(gen, fun, *gen_static_args):
"""Adds one more transformation with auxiliary output to a WrappedFun."""
out_store = Store()
out_thunk = lambda: out_store.val
return fun.wrap(gen, gen_static_args, out_store), out_thunk
def fun_name(f):
try:
return f.__name__
except:
return str(f)
def wrap_init(f, params={}):
"""Wraps function `f` as a `WrappedFun`, suitable for transformation."""
return WrappedFun(f, (), (), tuple(sorted(params.items())))
def cache(call):
"""Cache decorator for WrappedFun calls.
Args:
call: a function that takes a WrappedFun as a first argument
Returns:
the memoized `call` function.
"""
fun_caches = weakref.WeakKeyDictionary()
def memoized_fun(fun, *args):
cache = fun_caches.setdefault(fun.f, {})
key = (fun.transforms, fun.params, args)
result = cache.get(key, None)
if result is not None:
ans, stores = result
fun.populate_stores(stores)
else:
ans = call(fun, *args)
cache[key] = (ans, fun.stores)
return ans
memoized_fun.cache_clear = fun_caches.clear
return memoized_fun
@transformation
def hashable_partial(x, *args):
ans = yield (x,) + args, {}
yield ans
|
jax-master
|
jax/linear_util.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .tree_util import tree_flatten, tree_unflatten
from . import linear_util as lu
from .util import safe_zip
import jax.numpy as np
from jax.api import vjp
zip = safe_zip
def ravel_pytree(pytree):
leaves, treedef = tree_flatten(pytree)
flat, unravel_list = vjp(ravel_list, *leaves)
unravel_pytree = lambda flat: tree_unflatten(treedef, unravel_list(flat))
return flat, unravel_pytree
def ravel_list(*lst):
return np.concatenate([np.ravel(elt) for elt in lst]) if lst else np.array([])
@lu.transformation_with_aux
def ravel_fun(unravel_inputs, flat_in, **kwargs):
pytree_args = unravel_inputs(flat_in)
ans = yield pytree_args, {}
yield ravel_pytree(ans)
|
jax-master
|
jax/flatten_util.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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 os
os.environ.setdefault('TF_CPP_MIN_LOG_LEVEL', '1')
from jax.version import __version__
from jax.api import *
from jax import nn
from jax import random
import jax.numpy as np # side-effecting import sets up operator overloads
|
jax-master
|
jax/__init__.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from operator import attrgetter
from contextlib import contextmanager
from collections import namedtuple, Counter, defaultdict
import itertools as it
from weakref import ref
import threading
import types
import six
from . import linear_util as lu
from .util import safe_zip, safe_map, partial, curry
from .pprint_util import pp, vcat, hcat, pp_kv_pairs
# TODO(dougalm): the trace cache breaks the leak detector. Consisder solving.
check_leaks = False
# TODO(dougalm): put this behind a flag that's enabled during testing
skip_checks = True # not __debug__ # google doesn't use -O
zip = safe_zip
map = safe_map
# -------------------- jaxprs --------------------
class Jaxpr(object):
def __init__(self, constvars, freevars, invars, outvars, eqns):
self.constvars = list(constvars)
self.freevars = list(freevars)
self.invars = list(invars)
self.outvars = list(outvars)
self.eqns = list(eqns)
def __str__(self):
return str(pp_jaxpr(self))
__repr__ = __str__
class TypedJaxpr(object):
def __init__(self, jaxpr, literals, in_avals, out_avals):
assert type(jaxpr) is Jaxpr
assert len(literals) == len(jaxpr.constvars)
assert len(in_avals) == len(jaxpr.invars)
assert all(isinstance(aval, AbstractValue) for aval in in_avals)
assert all(isinstance(aval, AbstractValue) for aval in out_avals)
assert not jaxpr.freevars
self.jaxpr = jaxpr
self.literals = list(literals)
self.in_avals = list(in_avals)
self.out_avals = list(out_avals)
def __iter__(self):
return iter((self.jaxpr, self.literals, self.in_avals, self.out_avals))
def __str__(self):
# TODO(mattjj): improve this with type annotations?
return str(pp_jaxpr(self.jaxpr))
__repr__ = __str__
@curry
def jaxpr_as_fun(typed_jaxpr, *args):
return eval_jaxpr(typed_jaxpr.jaxpr, typed_jaxpr.literals, (), *args)
JaxprEqn = namedtuple('JaxprEqn', ['invars', 'outvars', 'primitive',
'bound_subjaxprs', 'params'])
JaxprEqn.__repr__ = JaxprEqn.__str__ = lambda eqn: str(pp_eqn(eqn)).rstrip()
new_jaxpr_eqn = JaxprEqn
class Var(object):
def __init__(self, count, suffix):
self.count = count
self.suffix = suffix
def __repr__(self):
rem = self.count
s = ''
while True:
rem, i = rem // 26, rem % 26
s = chr(97 + i % 26) + s
if not rem:
break
return s + self.suffix
def gensym(suffix):
counter = it.count()
return lambda: Var(next(counter), suffix)
class Literal(object):
__slots__ = ["val", "hash"]
def __init__(self, val):
self.val = val
try:
self.hash = hash(val)
except TypeError:
if type(val) in literalable_types:
try:
self.hash = hash((val.item(), val.dtype))
except (TypeError, AttributeError):
self.hash = None
def __hash__(self):
return id(self.val) if self.hash is None else self.hash
def __eq__(self, other):
return self.val is other.val if self.hash is None else self.val == other.val
def __repr__(self):
if self.hash is None:
return 'Literal(val={}, hashable={})'.format(self.val, self.hashable)
else:
return '{}'.format(self.val)
literalable_types = set()
class Primitive(object):
multiple_results = False # override for multi-output primitives
def __init__(self, name):
self.name = name
def __repr__(self):
return '{}'.format(self.name)
def bind(self, *args, **kwargs):
assert skip_checks or all(isinstance(arg, Tracer)
or valid_jaxtype(arg) for arg in args), args
top_trace = find_top_trace(args)
if top_trace is None:
return self.impl(*args, **kwargs)
tracers = map(top_trace.full_raise, args)
out_tracer = top_trace.process_primitive(self, tracers, kwargs)
if self.multiple_results:
return map(full_lower, out_tracer)
else:
return full_lower(out_tracer)
def def_impl(self, impl):
self.impl = impl
return impl
def def_abstract_eval(self, abstract_eval):
self.abstract_eval = abstract_eval
return abstract_eval
def def_custom_bind(self, bind):
self.bind = bind
return bind
def impl(self, *args, **kwargs):
raise NotImplementedError("Evaluation rule for '{}' not implemented"
.format(self.name))
def abstract_eval(self, *args, **kwargs):
raise NotImplementedError("Abstract evaluation for '{}' not implemented"
.format(self.name))
# -------------------- lifting --------------------
def eval_jaxpr(jaxpr, consts, freevar_vals, *args):
def read(v):
if type(v) is Literal:
return v.val
else:
return env[v]
def write(v, val):
env[v] = val
env = {}
write(unitvar, unit)
map(write, jaxpr.constvars, consts)
map(write, jaxpr.invars, args)
map(write, jaxpr.freevars, freevar_vals)
for eqn in jaxpr.eqns:
in_vals = map(read, eqn.invars)
subfuns = [partial(eval_jaxpr, subjaxpr, map(read, const_bindings),
map(read, freevar_bindings))
for subjaxpr, const_bindings, freevar_bindings
in eqn.bound_subjaxprs]
subfuns = map(lu.wrap_init, subfuns)
ans = eqn.primitive.bind(*(subfuns + in_vals), **eqn.params)
if eqn.primitive.multiple_results:
map(write, eqn.outvars, ans)
else:
write(eqn.outvars[0], ans)
return map(read, jaxpr.outvars)
def full_lower(val):
if isinstance(val, Tracer):
return val.full_lower()
else:
return val
def find_top_trace(xs):
try:
top_trace = max((x.trace for x in xs if isinstance(x, Tracer)),
key=attrgetter('level'))
except ValueError:
return None
else:
return type(top_trace)(top_trace.master, cur_sublevel())
# -------------------- tracing --------------------
class Trace(object):
def __init__(self, master, sublevel):
self.master = master
self.level = master.level
self.sublevel = sublevel
def full_raise(self, val):
if not isinstance(val, Tracer):
return self.pure(val)
level = self.level
sublevel = self.sublevel
if val.trace.master is self.master:
if val.trace.sublevel == sublevel:
return val
elif val.trace.sublevel < sublevel:
return self.sublift(val)
else:
raise Exception("Can't lift sublevels {} to {}"
.format(val.trace.sublevel, sublevel))
elif val.trace.level < level:
if val.trace.sublevel > sublevel:
raise Exception("Incompatible sublevel: {}, {}"
.format(val.trace, (level, sublevel)))
return self.lift(val)
elif val.trace.level > level:
raise Exception("Can't lift {} to {}".format(val, self))
elif val.trace.level == self.level:
raise Exception("Different traces at same level: {}, {}".format(val, self))
else:
raise Exception("Can't lift {} to {}".format(val, self))
def pure(self, val):
assert False
def lift(self, tracer):
assert False
def sublift(self, tracer):
assert False
def __repr__(self):
return '{}(level={}/{})'.format(
self.__class__.__name__, self.level, self.sublevel)
class Tracer(object):
__array_priority__ = 1000
__slots__ = ['trace', '__weakref__']
def __array__(self, *args, **kw):
raise Exception("Tracer can't be used with raw numpy functions. "
"You might have\n import numpy as np\ninstead of\n import jax.numpy as np")
def __init__(self, trace):
self.trace = trace
def __iter__(self):
return iter(self.aval._iter(self))
def __len__(self):
return self.aval._len(self)
@property
def aval(self):
assert False
def __neg__(self): return self.aval._neg(self)
def __pos__(self): return self.aval._pos(self)
def __eq__(self, other): return self.aval._eq(self, other)
def __ne__(self, other): return self.aval._ne(self, other)
def __lt__(self, other): return self.aval._lt(self, other)
def __le__(self, other): return self.aval._le(self, other)
def __gt__(self, other): return self.aval._gt(self, other)
def __ge__(self, other): return self.aval._ge(self, other)
def __abs__(self): return self.aval._abs(self)
def __add__(self, other): return self.aval._add(self, other)
def __radd__(self, other): return self.aval._radd(self, other)
def __sub__(self, other): return self.aval._sub(self, other)
def __rsub__(self, other): return self.aval._rsub(self, other)
def __mul__(self, other): return self.aval._mul(self, other)
def __rmul__(self, other): return self.aval._rmul(self, other)
def __div__(self, other): return self.aval._div(self, other)
def __rdiv__(self, other): return self.aval._rdiv(self, other)
def __truediv__(self, other): return self.aval._truediv(self, other)
def __rtruediv__(self, other): return self.aval._rtruediv(self, other)
def __floordiv__(self, other): return self.aval._floordiv(self, other)
def __rfloordiv__(self, other): return self.aval._rfloordiv(self, other)
def __divmod__(self, other): return self.aval._divmod(self, other)
def __rdivmod__(self, other): return self.aval._rdivmod(self, other)
def __mod__(self, other): return self.aval._mod(self, other)
def __rmod__(self, other): return self.aval._rmod(self, other)
def __pow__(self, other): return self.aval._pow(self, other)
def __rpow__(self, other): return self.aval._rpow(self, other)
def __matmul__(self, other): return self.aval._matmul(self, other)
def __rmatmul__(self, other): return self.aval._rmatmul(self, other)
def __and__(self, other): return self.aval._and(self, other)
def __rand__(self, other): return self.aval._rand(self, other)
def __or__(self, other): return self.aval._or(self, other)
def __ror__(self, other): return self.aval._ror(self, other)
def __xor__(self, other): return self.aval._xor(self, other)
def __rxor__(self, other): return self.aval._rxor(self, other)
def __invert__(self): return self.aval._invert(self)
def __lshift__(self, other): return self.aval._lshift(self, other)
def __rshift__(self, other): return self.aval._rshift(self, other)
def __getitem__(self, idx): return self.aval._getitem(self, idx)
def __nonzero__(self): return self.aval._nonzero(self)
def __bool__(self): return self.aval._bool(self)
def __float__(self): return self.aval._float(self)
def __int__(self): return self.aval._int(self)
def __long__(self): return self.aval._long(self)
def __complex__(self): return self.aval._complex(self)
def __hex__(self): return self.aval._hex(self)
def __oct__(self): return self.aval._oct(self)
def __setitem__(self, idx, val):
raise TypeError("JAX 'Tracer' objects do not support item assignment")
def __getattr__(self, name):
# if the aval property raises an AttributeError, gets caught here
assert skip_checks or name != "aval"
try:
attr = getattr(self.aval, name)
except KeyError:
raise AttributeError(
"{} has no attribute {}".format(self.__class__.__name__, name))
else:
t = type(attr)
if t is aval_property:
return attr.fget(self)
elif t is aval_method:
if six.PY3:
return types.MethodType(attr.fun, self)
else:
return types.MethodType(attr.fun, self, None)
else:
return attr
def __repr__(self):
return 'Traced<{}>with<{}>'.format(self.aval, self.trace)
def __copy__(self):
return self
def __deepcopy__(self, unused_memo):
return self
# these can be used to set up forwarding of properties and instance methods from
# Tracer instances to the underlying avals
aval_property = namedtuple("aval_property", ["fget"])
aval_method = namedtuple("aval_method", ["fun"])
class MasterTrace(object):
def __init__(self, level, trace_type):
self.level = level
self.trace_type = trace_type
def __repr__(self):
return "MasterTrace({},{})".format(self.level, self.trace_type.__name__)
def __hash__(self):
return hash((self.level, self.trace_type))
def __eq__(self, other):
return self.level == other.level and self.trace_type == other.trace_type
class TraceStack(object):
def __init__(self):
self.upward = []
self.downward = []
def next_level(self, bottom):
if bottom:
return - (len(self.downward) + 1)
else:
return len(self.upward)
def push(self, val, bottom):
if bottom:
self.downward.append(val)
else:
self.upward.append(val)
def pop(self, bottom):
if bottom:
self.downward.pop()
else:
self.upward.pop()
def __repr__(self):
return 'Trace stack\n{} ---\n{}'.format(
map(' {}\n'.format, self.upward[::-1]),
map(' {}\n'.format, self.downward))
class Sublevel(int): pass
# The global state of the tracer is accessed by a thread-local object.
# This allows concurrent tracing in separate threads; passing traced objects
# between threads is forbidden.
class TraceState(threading.local):
def __init__(self):
self.trace_stack = TraceStack()
self.substack = [Sublevel(0)]
trace_state = TraceState()
def cur_sublevel():
return trace_state.substack[-1]
@contextmanager
def new_master(trace_type, bottom=False):
level = trace_state.trace_stack.next_level(bottom)
master = MasterTrace(level, trace_type)
trace_state.trace_stack.push(master, bottom)
try:
yield master
finally:
trace_state.trace_stack.pop(bottom)
if check_leaks:
t = ref(master)
del master
if t() is not None:
print(trace_state.trace_stack)
raise Exception('Leaked trace {}'.format(t()))
@contextmanager
def new_sublevel():
sublevel = Sublevel(len(trace_state.substack))
trace_state.substack.append(sublevel)
try:
yield
finally:
trace_state.substack.pop()
if check_leaks:
t = ref(sublevel)
del sublevel
if t() is not None:
raise Exception('Leaked sublevel {}'.format(t()))
# -------------------- abstract values --------------------
class AbstractValue(object):
__slots__ = []
def at_least_vspace(self):
assert False
def __repr__(self):
try:
kv_pairs = ('{}={}'.format(k, v) for k, v in self.__dict__.items())
return '{}({})'.format(self.__class__.__name__, ','.join(kv_pairs))
except AttributeError:
return self.__class__.__name__
def strip_weak_type(self):
return self
class Bot(AbstractValue): pass
bot = Bot()
class AbstractUnit(AbstractValue):
def join(self, other): return self
def _eq(self, self_traced, other): return get_aval(other) is self
abstract_unit = AbstractUnit()
def lattice_join(x, y):
if x is None:
return y
elif y is None:
return x
elif isinstance(x, type(y)):
return y.join(x)
elif isinstance(y, type(x)):
return x.join(y)
else:
raise TypeError((x, y))
def valid_jaxtype(x):
try:
concrete_aval(x)
except TypeError:
return False
else:
return True
def concrete_aval(x):
try:
return pytype_aval_mappings[type(x)](x)
except KeyError:
raise TypeError("{} is not a valid Jax type".format(type(x)))
def get_aval(x):
if isinstance(x, Tracer):
return x.aval
else:
return concrete_aval(x)
pytype_aval_mappings = {}
class Unit(object):
def __repr__(self): return '*'
unit = Unit()
literalable_types.add(Unit)
class UnitVar(object):
def __repr__(self): return '*'
unitvar = UnitVar()
pytype_aval_mappings[Unit] = lambda _: abstract_unit
identity_p = Primitive('id')
identity_p.def_impl(lambda x: x)
identity_p.def_custom_bind(lambda x: x)
# ------------------- Call -------------------
def apply_todos(todos, outs):
todos_list = list(todos)
while todos_list:
outs = map(full_lower, todos_list.pop()(outs))
return outs
@lu.transformation_with_aux
def process_env_traces(primitive, level, params_tuple, *args):
outs = yield args, {}
params = dict(params_tuple)
todo = []
while True:
tracers = [x for x in outs if isinstance(x, Tracer) and x.trace.level > level]
if tracers:
ans = max(tracers, key=lambda x: x.trace.level)
else:
break
trace = type(ans.trace)(ans.trace.master, cur_sublevel())
outs = map(trace.full_raise, outs)
outs, cur_todo = trace.post_process_call(primitive, outs, params)
todo.append(cur_todo)
yield outs, tuple(todo) # Ensure the aux output is immutable
def call_bind(primitive, f, *args, **params):
top_trace = find_top_trace(args)
level = trace_state.trace_stack.next_level(True) if top_trace is None else top_trace.level
params_tuple = tuple(params.items())
f, env_trace_todo = process_env_traces(f, primitive, level, params_tuple)
if top_trace is None:
with new_sublevel():
outs = primitive.impl(f, *args, **params)
else:
tracers = map(top_trace.full_raise, args)
outs = map(full_lower, top_trace.process_call(primitive, f, tracers, params))
return apply_todos(env_trace_todo(), outs)
def call_impl(f, *args, **params):
del params # params parameterize the call primitive, not the function
return f.call_wrapped(*args)
call_p = Primitive('call')
call = partial(call_bind, call_p)
call_p.def_custom_bind(call)
call_p.def_impl(call_impl)
# ------------------- Jaxpr printed representation -------------------
def check_jaxpr(jaxpr):
def context():
return "\njaxpr:\n{}\n".format(jaxpr)
def read_env(env, v):
if v not in env and type(v) is not Literal:
raise Exception("Variable '{}' not defined".format(v) + context())
def write_env(env, v):
if v in env:
raise Exception("Variable {} already bound".format(v) + context())
env.add(v)
env = set()
read = partial(read_env, env)
write = partial(write_env, env)
write(unitvar)
map(write, jaxpr.constvars)
map(write, jaxpr.freevars)
map(write, jaxpr.invars)
for eqn in jaxpr.eqns:
map(read, eqn.invars)
for subjaxpr, constvars, freevars in eqn.bound_subjaxprs:
map(read, freevars)
map(read, constvars)
check_jaxpr(subjaxpr)
map(write, eqn.outvars)
map(read, jaxpr.outvars)
def pp_vars(vs):
return ' '.join(map(str, vs))
def pp_eqn(eqn):
lhs = pp_vars(eqn.outvars)
pp_subexpr = pp('')
if eqn.bound_subjaxprs:
for subjaxpr, const_vars, bound_vars in eqn.bound_subjaxprs:
pp_subexpr = pp_subexpr + (
pp_jaxpr(subjaxpr).indent(2)
>> pp(' [ {} ; {} ]'.format(pp_vars(const_vars),
pp_vars(bound_vars))))
return (pp('{} = '.format(lhs)) >>
pp(eqn.primitive.name) >> pp_kv_pairs(sorted(eqn.params.items()))
>> pp(' ') >> pp(pp_vars(eqn.invars))) + pp_subexpr
def pp_jaxpr(jaxpr):
return (pp('{{ lambda {} ; {} ; {}.'.format(pp_vars(jaxpr.constvars),
pp_vars(jaxpr.freevars),
pp_vars(jaxpr.invars))) +
((pp('let ') >>
vcat(map(pp_eqn, jaxpr.eqns))) +
pp('in {} }}'.format(jaxpr.outvars))).indent(2))
|
jax-master
|
jax/core.py
|
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
# Array type functions.
#
# JAX dtypes differ from NumPy in both:
# a) their type promotion rules, and
# b) the set of supported types (e.g., bfloat16),
# so we need our own implementation that deviates from NumPy in places.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from distutils.util import strtobool
import functools
import os
import numpy as onp
import six
from . import util
from .config import flags
from .lib import xla_client
FLAGS = flags.FLAGS
flags.DEFINE_bool('jax_enable_x64',
strtobool(os.getenv('JAX_ENABLE_X64', 'False')),
'Enable 64-bit types to be used.')
# bfloat16 support
bfloat16 = xla_client.bfloat16
_bfloat16_dtype = onp.dtype(bfloat16)
class _bfloat16_finfo(object):
bits = 16
eps = bfloat16(float.fromhex("0x1p-7"))
epsneg = bfloat16(float.fromhex("0x1p-8"))
machep = -7
negep = -8
max = bfloat16(float.fromhex("0x1.FEp127"))
min = -max
nexp = 8
nmant = 7
iexp = nexp
precision = 2
resolution = 10 ** -2
tiny = bfloat16(float.fromhex("0x1p-126"))
# Default types.
bool_ = onp.bool_
int_ = onp.int64
float_ = onp.float64
complex_ = onp.complex128
# TODO(phawkins): change the above defaults to:
# int_ = onp.int32
# float_ = onp.float32
# complex_ = onp.complex64
_dtype_to_32bit_dtype = {
onp.dtype('int64'): onp.dtype('int32'),
onp.dtype('uint64'): onp.dtype('uint32'),
onp.dtype('float64'): onp.dtype('float32'),
onp.dtype('complex128'): onp.dtype('complex64'),
}
@util.memoize
def canonicalize_dtype(dtype):
"""Convert from a dtype to a canonical dtype based on FLAGS.jax_enable_x64."""
dtype = onp.dtype(dtype)
if FLAGS.jax_enable_x64:
return dtype
else:
return _dtype_to_32bit_dtype.get(dtype, dtype)
# Default dtypes corresponding to Python scalars.
python_scalar_dtypes = {
bool: onp.dtype(bool_),
int: onp.dtype(int_),
float: onp.dtype(float_),
complex: onp.dtype(complex_),
}
if six.PY2:
python_scalar_dtypes[long] = onp.dtype(int_) # noqa: F821
def scalar_type_of(x):
typ = dtype(x)
if onp.issubdtype(typ, onp.bool_):
return bool
elif onp.issubdtype(typ, onp.integer):
return int
elif onp.issubdtype(typ, onp.floating):
return float
elif onp.issubdtype(typ, onp.complexfloating):
return complex
else:
raise TypeError("Invalid scalar value {}".format(x))
def coerce_to_array(x):
"""Coreces a scalar or NumPy array to an onp.array.
Handles Python scalar type promotion according to JAX's rules, not NumPy's
rules.
"""
dtype = python_scalar_dtypes.get(type(x), None)
return onp.array(x, dtype) if dtype else onp.array(x)
iinfo = onp.iinfo
def finfo(dtype):
# Since NumPy doesn't consider bfloat16 a floating-point type, we have to
# provide an alternative implementation of finfo that does so.
if onp.result_type(dtype) == _bfloat16_dtype:
return _bfloat16_finfo
else:
return onp.finfo(dtype)
def issubdtype(a, b):
if a == bfloat16:
return b in [bfloat16, _bfloat16_dtype, onp.floating, onp.inexact,
onp.number]
if not issubclass(b, onp.generic):
# Workaround for JAX scalar types. NumPy's issubdtype has a backward
# compatibility behavior for the second argument of issubdtype that
# interacts badly with JAX's custom scalar types. As a workaround,
# explicitly cast the second argument to a NumPy type object.
b = onp.dtype(b).type
return onp.issubdtype(a, b)
can_cast = onp.can_cast
issubsctype = onp.issubsctype
# List of all valid JAX dtypes, in the order they appear in the type promotion
# table.
_jax_types = [
onp.dtype('bool'),
onp.dtype('uint8'),
onp.dtype('uint16'),
onp.dtype('uint32'),
onp.dtype('uint64'),
onp.dtype('int8'),
onp.dtype('int16'),
onp.dtype('int32'),
onp.dtype('int64'),
onp.dtype(bfloat16),
onp.dtype('float16'),
onp.dtype('float32'),
onp.dtype('float64'),
onp.dtype('complex64'),
onp.dtype('complex128'),
]
# Mapping from types to their type numbers.
_jax_type_nums = {t: i for i, t in enumerate(_jax_types)}
def _make_type_promotion_table():
b1, u1, u2, u4, u8, s1, s2, s4, s8, bf, f2, f4, f8, c4, c8 = _jax_types
# b1, u1, u2, u4, u8, s1, s2, s4, s8, bf, f2, f4, f8, c4, c8
return onp.array([
[b1, u1, u2, u4, u8, s1, s2, s4, s8, bf, f2, f4, f8, c4, c8], # b1
[u1, u1, u2, u4, u8, s2, s2, s4, s8, bf, f2, f4, f8, c4, c8], # u1
[u2, u2, u2, u4, u8, s4, s4, s4, s8, bf, f2, f4, f8, c4, c8], # u2
[u4, u4, u4, u4, u8, s8, s8, s8, s8, bf, f2, f4, f8, c4, c8], # u4
[u8, u8, u8, u8, u8, f8, f8, f8, f8, bf, f2, f4, f8, c4, c8], # u8
[s1, s2, s4, s8, f8, s1, s2, s4, s8, bf, f2, f4, f8, c4, c8], # s1
[s2, s2, s4, s8, f8, s2, s2, s4, s8, bf, f2, f4, f8, c4, c8], # s2
[s4, s4, s4, s8, f8, s4, s4, s4, s8, bf, f2, f4, f8, c4, c8], # s4
[s8, s8, s8, s8, f8, s8, s8, s8, s8, bf, f2, f4, f8, c4, c8], # s8
[bf, bf, bf, bf, bf, bf, bf, bf, bf, bf, f4, f4, f8, c4, c8], # bf
[f2, f2, f2, f2, f2, f2, f2, f2, f2, f4, f2, f4, f8, c4, c8], # f2
[f4, f4, f4, f4, f4, f4, f4, f4, f4, f4, f4, f4, f8, c4, c8], # f4
[f8, f8, f8, f8, f8, f8, f8, f8, f8, f8, f8, f8, f8, c8, c8], # f8
[c4, c4, c4, c4, c4, c4, c4, c4, c4, c4, c4, c4, c8, c4, c8], # c4
[c8, c8, c8, c8, c8, c8, c8, c8, c8, c8, c8, c8, c8, c8, c8], # c8
])
_type_promotion_table = _make_type_promotion_table()
def promote_types(a, b):
"""Returns the type to which a binary operation should cast its arguments.
For details of JAX's type promotion semantics, see :ref:`type-promotion`.
Args:
a: a :class:`numpy.dtype` or a dtype specifier.
b: a :class:`numpy.dtype` or a dtype specifier.
Returns:
A :class:`numpy.dtype` object.
"""
a = onp.dtype(a)
b = onp.dtype(b)
try:
return _type_promotion_table[_jax_type_nums[a], _jax_type_nums[b]]
except KeyError:
pass
raise TypeError("Invalid type promotion of {} and {}".format(a, b))
def is_python_scalar(x):
try:
return x.aval.weak_type and onp.ndim(x) == 0
except AttributeError:
return type(x) in python_scalar_dtypes
def _dtype_priority(dtype):
if issubdtype(dtype, onp.bool_):
return 0
elif issubdtype(dtype, onp.integer):
return 1
elif issubdtype(dtype, onp.floating):
return 2
elif issubdtype(dtype, onp.complexfloating):
return 3
else:
raise TypeError("Dtype {} is not supported by JAX".format(dtype))
def dtype(x):
if type(x) in python_scalar_dtypes:
return python_scalar_dtypes[type(x)]
return onp.result_type(x)
def result_type(*args):
"""Convenience function to apply Numpy argument dtype promotion."""
# TODO(dougalm,mattjj): This is a performance bottleneck. Consider memoizing.
if len(args) < 2:
return dtype(args[0])
scalars = []
dtypes = []
for x in args:
(scalars if is_python_scalar(x) else dtypes).append(dtype(x))
array_priority = max(map(_dtype_priority, dtypes)) if dtypes else -1
dtypes += [x for x in scalars if _dtype_priority(x) > array_priority]
return canonicalize_dtype(functools.reduce(promote_types, dtypes))
|
jax-master
|
jax/dtypes.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from contextlib import contextmanager
import functools
import re
import itertools as it
import os
from unittest import SkipTest
from absl.testing import absltest
from absl.testing import parameterized
import numpy as onp
import numpy.random as npr
from six.moves import xrange
from . import api
from . import dtypes
from . import lax
from .config import flags
from .util import partial
from .tree_util import tree_multimap, tree_all, tree_map, tree_reduce
from .lib import xla_bridge
from .interpreters import xla
FLAGS = flags.FLAGS
flags.DEFINE_enum(
'jax_test_dut', '',
enum_values=['', 'cpu', 'gpu', 'tpu'],
help=
'Describes the device under test in case special consideration is required.'
)
flags.DEFINE_integer(
'num_generated_cases',
int(os.getenv('JAX_NUM_GENERATED_CASES', 10)),
help='Number of generated cases to test')
EPS = 1e-4
def _dtype(x):
return (getattr(x, 'dtype', None) or
onp.dtype(dtypes.python_scalar_dtypes.get(type(x), None)) or
onp.asarray(x).dtype)
def is_sequence(x):
try:
iter(x)
except TypeError:
return False
else:
return True
_default_tolerance = {
onp.dtype(onp.bool_): 0,
onp.dtype(onp.int8): 0,
onp.dtype(onp.int16): 0,
onp.dtype(onp.int32): 0,
onp.dtype(onp.int64): 0,
onp.dtype(onp.uint8): 0,
onp.dtype(onp.uint16): 0,
onp.dtype(onp.uint32): 0,
onp.dtype(onp.uint64): 0,
onp.dtype(dtypes.bfloat16): 1e-2,
onp.dtype(onp.float16): 1e-3,
onp.dtype(onp.float32): 1e-6,
onp.dtype(onp.float64): 1e-15,
onp.dtype(onp.complex64): 1e-6,
onp.dtype(onp.complex128): 1e-15,
}
def default_tolerance():
if device_under_test() != "tpu":
return _default_tolerance
tol = _default_tolerance.copy()
tol[onp.dtype(onp.float32)] = 1e-3
tol[onp.dtype(onp.complex64)] = 1e-3
return tol
default_gradient_tolerance = {
onp.dtype(dtypes.bfloat16): 1e-1,
onp.dtype(onp.float16): 1e-2,
onp.dtype(onp.float32): 2e-3,
onp.dtype(onp.float64): 1e-5,
onp.dtype(onp.complex64): 1e-3,
onp.dtype(onp.complex128): 1e-5,
}
def _assert_numpy_allclose(a, b, atol=None, rtol=None):
a = a.astype(onp.float32) if a.dtype == dtypes.bfloat16 else a
b = b.astype(onp.float32) if b.dtype == dtypes.bfloat16 else b
kw = {}
if atol: kw["atol"] = atol
if rtol: kw["rtol"] = rtol
onp.testing.assert_allclose(a, b, **kw)
def tolerance(dtype, tol=None):
tol = tol or {}
if not isinstance(tol, dict):
return tol
tol = {onp.dtype(key): value for key, value in tol.items()}
dtype = dtypes.canonicalize_dtype(onp.dtype(dtype))
return tol.get(dtype, default_tolerance()[dtype])
def _normalize_tolerance(tol):
tol = tol or 0
if isinstance(tol, dict):
return {onp.dtype(k): v for k, v in tol.items()}
else:
return {k: tol for k in _default_tolerance.keys()}
def join_tolerance(tol1, tol2):
tol1 = _normalize_tolerance(tol1)
tol2 = _normalize_tolerance(tol2)
out = tol1
for k, v in tol2.items():
out[k] = max(v, tol1.get(k, 0))
return out
def _assert_numpy_close(a, b, atol=None, rtol=None):
assert a.shape == b.shape
atol = max(tolerance(a.dtype, atol), tolerance(b.dtype, atol))
rtol = max(tolerance(a.dtype, rtol), tolerance(b.dtype, rtol))
_assert_numpy_allclose(a, b, atol=atol * a.size, rtol=rtol * b.size)
def check_eq(xs, ys):
tree_all(tree_multimap(_assert_numpy_allclose, xs, ys))
def check_close(xs, ys, atol=None, rtol=None):
assert_close = partial(_assert_numpy_close, atol=atol, rtol=rtol)
tree_all(tree_multimap(assert_close, xs, ys))
def inner_prod(xs, ys):
def contract(x, y):
return onp.real(onp.dot(onp.conj(x).reshape(-1), y.reshape(-1)))
return tree_reduce(onp.add, tree_multimap(contract, xs, ys))
add = partial(tree_multimap, lambda x, y: onp.add(x, y, dtype=_dtype(x)))
sub = partial(tree_multimap, lambda x, y: onp.subtract(x, y, dtype=_dtype(x)))
conj = partial(tree_map, lambda x: onp.conj(x, dtype=_dtype(x)))
def scalar_mul(xs, a):
return tree_map(lambda x: onp.multiply(x, a, dtype=_dtype(x)), xs)
def rand_like(rng, x):
shape = onp.shape(x)
dtype = _dtype(x)
randn = lambda: onp.asarray(rng.randn(*shape), dtype=dtype)
if dtypes.issubdtype(dtype, onp.complexfloating):
return randn() + dtype.type(1.0j) * randn()
else:
return randn()
def numerical_jvp(f, primals, tangents, eps=EPS):
delta = scalar_mul(tangents, eps)
f_pos = f(*add(primals, delta))
f_neg = f(*sub(primals, delta))
return scalar_mul(sub(f_pos, f_neg), 0.5 / eps)
def _merge_tolerance(tol, default):
if tol is None:
return default
if not isinstance(tol, dict):
return tol
out = default.copy()
for k, v in tol.items():
out[onp.dtype(k)] = v
return out
def check_jvp(f, f_jvp, args, atol=None, rtol=None, eps=EPS):
atol = _merge_tolerance(atol, default_gradient_tolerance)
rtol = _merge_tolerance(rtol, default_gradient_tolerance)
rng = onp.random.RandomState(0)
tangent = tree_map(partial(rand_like, rng), args)
v_out, t_out = f_jvp(args, tangent)
v_out_expected = f(*args)
t_out_expected = numerical_jvp(f, args, tangent, eps=eps)
# In principle we should expect exact equality of v_out and v_out_expected,
# but due to nondeterminism especially on GPU (e.g., due to convolution
# autotuning) we only require "close".
check_close(v_out, v_out_expected, atol=atol, rtol=rtol)
check_close(t_out, t_out_expected, atol=atol, rtol=rtol)
def check_vjp(f, f_vjp, args, atol=None, rtol=None, eps=EPS):
atol = _merge_tolerance(atol, default_gradient_tolerance)
rtol = _merge_tolerance(rtol, default_gradient_tolerance)
_rand_like = partial(rand_like, onp.random.RandomState(0))
v_out, vjpfun = f_vjp(*args)
v_out_expected = f(*args)
check_close(v_out, v_out_expected, atol=atol, rtol=rtol)
tangent = tree_map(_rand_like, args)
tangent_out = numerical_jvp(f, args, tangent, eps=eps)
cotangent = tree_map(_rand_like, v_out)
cotangent_out = conj(vjpfun(conj(cotangent)))
ip = inner_prod(tangent, cotangent_out)
ip_expected = inner_prod(tangent_out, cotangent)
check_close(ip, ip_expected, atol=atol, rtol=rtol)
def check_grads(f, args, order,
modes=["fwd", "rev"], atol=None, rtol=None, eps=None):
args = tuple(args)
eps = eps or EPS
_check_jvp = partial(check_jvp, atol=atol, rtol=rtol, eps=eps)
_check_vjp = partial(check_vjp, atol=atol, rtol=rtol, eps=eps)
def _check_grads(f, args, order):
if "fwd" in modes:
_check_jvp(f, partial(api.jvp, f), args)
if order > 1:
_check_grads(partial(api.jvp, f), (args, args), order - 1)
if "rev" in modes:
_check_vjp(f, partial(api.vjp, f), args)
if order > 1:
def f_vjp(*args):
out_primal_py, vjp_py = api.vjp(f, *args)
return vjp_py(out_primal_py)
_check_grads(f_vjp, args, order - 1)
_check_grads(f, args, order)
@contextmanager
def count_primitive_compiles():
xla.xla_primitive_callable.cache_clear()
# We count how many times we call primitive_computation (which is called
# inside xla_primitive_callable) instead of xla_primitive_callable so we don't
# count cache hits.
primitive_computation = xla.primitive_computation
count = [0]
def primitive_computation_and_count(*args, **kwargs):
count[0] += 1
return primitive_computation(*args, **kwargs)
xla.primitive_computation = primitive_computation_and_count
try:
yield count
finally:
xla.primitive_computation = primitive_computation
@contextmanager
def count_jit_and_pmap_compiles():
# No need to clear any caches since we generally jit and pmap fresh callables
# in tests.
jaxpr_subcomp = xla.jaxpr_subcomp
count = [0]
def jaxpr_subcomp_and_count(*args, **kwargs):
count[0] += 1
return jaxpr_subcomp(*args, **kwargs)
xla.jaxpr_subcomp = jaxpr_subcomp_and_count
try:
yield count
finally:
xla.jaxpr_subcomp = jaxpr_subcomp
def device_under_test():
return FLAGS.jax_test_dut or xla_bridge.get_backend().platform
def supported_dtypes():
if device_under_test() == "tpu":
return {onp.bool_, onp.int32, onp.uint32, dtypes.bfloat16, onp.float32,
onp.complex64}
else:
return {onp.bool_, onp.int8, onp.int16, onp.int32, onp.int64,
onp.uint8, onp.uint16, onp.uint32, onp.uint64,
dtypes.bfloat16, onp.float16, onp.float32, onp.float64,
onp.complex64, onp.complex128}
def skip_on_devices(*disabled_devices):
"""A decorator for test methods to skip the test on certain devices."""
def skip(test_method):
@functools.wraps(test_method)
def test_method_wrapper(self, *args, **kwargs):
device = device_under_test()
if device in disabled_devices:
test_name = getattr(test_method, '__name__', '[unknown test]')
raise SkipTest('{} not supported on {}.'
.format(test_name, device.upper()))
return test_method(self, *args, **kwargs)
return test_method_wrapper
return skip
def skip_on_flag(flag_name, skip_value):
"""A decorator for test methods to skip the test when flags are set."""
def skip(test_method): # pylint: disable=missing-docstring
@functools.wraps(test_method)
def test_method_wrapper(self, *args, **kwargs):
flag_value = getattr(FLAGS, flag_name)
if flag_value == skip_value:
test_name = getattr(test_method, '__name__', '[unknown test]')
raise SkipTest('{} not supported when FLAGS.{} is {}'
.format(test_name, flag_name, flag_value))
return test_method(self, *args, **kwargs)
return test_method_wrapper
return skip
def format_test_name_suffix(opname, shapes, dtypes):
arg_descriptions = (format_shape_dtype_string(shape, dtype)
for shape, dtype in zip(shapes, dtypes))
return '{}_{}'.format(opname.capitalize(), '_'.join(arg_descriptions))
# We use special symbols, represented as singleton objects, to distinguish
# between NumPy scalars, Python scalars, and 0-D arrays.
class ScalarShape(object):
def __len__(self): return 0
class _NumpyScalar(ScalarShape): pass
class _PythonScalar(ScalarShape): pass
NUMPY_SCALAR_SHAPE = _NumpyScalar()
PYTHON_SCALAR_SHAPE = _PythonScalar()
def _dims_of_shape(shape):
"""Converts `shape` to a tuple of dimensions."""
if type(shape) in (list, tuple):
return shape
elif isinstance(shape, ScalarShape):
return ()
else:
raise TypeError(type(shape))
def _cast_to_shape(value, shape, dtype):
"""Casts `value` to the correct Python type for `shape` and `dtype`."""
if shape is NUMPY_SCALAR_SHAPE:
# explicitly cast to NumPy scalar in case `value` is a Python scalar.
return onp.dtype(dtype).type(value)
elif shape is PYTHON_SCALAR_SHAPE:
# explicitly cast to Python scalar via https://stackoverflow.com/a/11389998
return onp.asarray(value).item()
elif type(shape) in (list, tuple):
assert onp.shape(value) == tuple(shape)
return value
else:
raise TypeError(type(shape))
def dtype_str(dtype):
return onp.dtype(dtype).name
def format_shape_dtype_string(shape, dtype):
if shape is NUMPY_SCALAR_SHAPE:
return dtype_str(dtype)
elif shape is PYTHON_SCALAR_SHAPE:
return 'py' + dtype_str(dtype)
elif type(shape) in (list, tuple):
shapestr = ','.join(str(dim) for dim in shape)
return '{}[{}]'.format(dtype_str(dtype), shapestr)
elif type(shape) is int:
return '{}[{},]'.format(dtype_str(dtype), shape)
elif isinstance(shape, onp.ndarray):
return '{}[{}]'.format(dtype_str(dtype), shape)
else:
raise TypeError(type(shape))
def _rand_dtype(rand, shape, dtype, scale=1., post=lambda x: x):
"""Produce random values given shape, dtype, scale, and post-processor.
Args:
rand: a function for producing random values of a given shape, e.g. a
bound version of either onp.RandomState.randn or onp.RandomState.rand.
shape: a shape value as a tuple of positive integers.
dtype: a numpy dtype.
scale: optional, a multiplicative scale for the random values (default 1).
post: optional, a callable for post-processing the random values (default
identity).
Returns:
An ndarray of the given shape and dtype using random values based on a call
to rand but scaled, converted to the appropriate dtype, and post-processed.
"""
r = lambda: onp.asarray(scale * rand(*_dims_of_shape(shape)), dtype)
if dtypes.issubdtype(dtype, onp.complexfloating):
vals = r() + 1.0j * r()
else:
vals = r()
return _cast_to_shape(onp.asarray(post(vals), dtype), shape, dtype)
def rand_default(scale=3):
randn = npr.RandomState(0).randn
return partial(_rand_dtype, randn, scale=scale)
def rand_nonzero():
post = lambda x: onp.where(x == 0, onp.array(1, dtype=x.dtype), x)
randn = npr.RandomState(0).randn
return partial(_rand_dtype, randn, scale=3, post=post)
def rand_positive():
post = lambda x: x + 1
rand = npr.RandomState(0).rand
return partial(_rand_dtype, rand, scale=2, post=post)
def rand_small():
randn = npr.RandomState(0).randn
return partial(_rand_dtype, randn, scale=1e-3)
def rand_not_small():
post = lambda x: x + onp.where(x > 0, 10., -10.)
randn = npr.RandomState(0).randn
return partial(_rand_dtype, randn, scale=3., post=post)
def rand_small_positive():
rand = npr.RandomState(0).rand
return partial(_rand_dtype, rand, scale=2e-5)
def rand_uniform(low=0.0, high=1.0):
assert low < high
rand = npr.RandomState(0).rand
post = lambda x: x * (high - low) + low
return partial(_rand_dtype, rand, post=post)
def rand_some_equal():
randn = npr.RandomState(0).randn
rng = npr.RandomState(0)
def post(x):
x_ravel = x.ravel()
if len(x_ravel) == 0:
return x
flips = rng.rand(*onp.shape(x)) < 0.5
return onp.where(flips, x_ravel[0], x)
return partial(_rand_dtype, randn, scale=100., post=post)
def rand_some_inf():
"""Return a random sampler that produces infinities in floating types."""
rng = npr.RandomState(1)
base_rand = rand_default()
"""
TODO: Complex numbers are not correctly tested
If blocks should be switched in order, and relevant tests should be fixed
"""
def rand(shape, dtype):
"""The random sampler function."""
if not dtypes.issubdtype(dtype, onp.floating):
# only float types have inf
return base_rand(shape, dtype)
if dtypes.issubdtype(dtype, onp.complexfloating):
base_dtype = onp.real(onp.array(0, dtype=dtype)).dtype
out = (rand(shape, base_dtype) +
onp.array(1j, dtype) * rand(shape, base_dtype))
return _cast_to_shape(out, shape, dtype)
dims = _dims_of_shape(shape)
posinf_flips = rng.rand(*dims) < 0.1
neginf_flips = rng.rand(*dims) < 0.1
vals = base_rand(shape, dtype)
vals = onp.where(posinf_flips, onp.array(onp.inf, dtype=dtype), vals)
vals = onp.where(neginf_flips, onp.array(-onp.inf, dtype=dtype), vals)
return _cast_to_shape(onp.asarray(vals, dtype=dtype), shape, dtype)
return rand
def rand_some_nan():
"""Return a random sampler that produces nans in floating types."""
rng = npr.RandomState(1)
base_rand = rand_default()
def rand(shape, dtype):
"""The random sampler function."""
if dtypes.issubdtype(dtype, onp.complexfloating):
base_dtype = onp.real(onp.array(0, dtype=dtype)).dtype
out = (rand(shape, base_dtype) +
onp.array(1j, dtype) * rand(shape, base_dtype))
return _cast_to_shape(out, shape, dtype)
if not dtypes.issubdtype(dtype, onp.floating):
# only float types have inf
return base_rand(shape, dtype)
dims = _dims_of_shape(shape)
nan_flips = rng.rand(*dims) < 0.1
vals = base_rand(shape, dtype)
vals = onp.where(nan_flips, onp.array(onp.nan, dtype=dtype), vals)
return _cast_to_shape(onp.asarray(vals, dtype=dtype), shape, dtype)
return rand
def rand_some_inf_and_nan():
"""Return a random sampler that produces infinities in floating types."""
rng = npr.RandomState(1)
base_rand = rand_default()
"""
TODO: Complex numbers are not correctly tested
If blocks should be switched in order, and relevant tests should be fixed
"""
def rand(shape, dtype):
"""The random sampler function."""
if not dtypes.issubdtype(dtype, onp.floating):
# only float types have inf
return base_rand(shape, dtype)
if dtypes.issubdtype(dtype, onp.complexfloating):
base_dtype = onp.real(onp.array(0, dtype=dtype)).dtype
out = (rand(shape, base_dtype) +
onp.array(1j, dtype) * rand(shape, base_dtype))
return _cast_to_shape(out, shape, dtype)
dims = _dims_of_shape(shape)
posinf_flips = rng.rand(*dims) < 0.1
neginf_flips = rng.rand(*dims) < 0.1
nan_flips = rng.rand(*dims) < 0.1
vals = base_rand(shape, dtype)
vals = onp.where(posinf_flips, onp.array(onp.inf, dtype=dtype), vals)
vals = onp.where(neginf_flips, onp.array(-onp.inf, dtype=dtype), vals)
vals = onp.where(nan_flips, onp.array(onp.nan, dtype=dtype), vals)
return _cast_to_shape(onp.asarray(vals, dtype=dtype), shape, dtype)
return rand
# TODO(mattjj): doesn't handle complex types
def rand_some_zero():
"""Return a random sampler that produces some zeros."""
rng = npr.RandomState(1)
base_rand = rand_default()
def rand(shape, dtype):
"""The random sampler function."""
dims = _dims_of_shape(shape)
zeros = rng.rand(*dims) < 0.5
vals = base_rand(shape, dtype)
vals = onp.where(zeros, onp.array(0, dtype=dtype), vals)
return _cast_to_shape(onp.asarray(vals, dtype=dtype), shape, dtype)
return rand
def rand_int(low, high=None):
randint = npr.RandomState(0).randint
def fn(shape, dtype):
return randint(low, high=high, size=shape, dtype=dtype)
return fn
def rand_bool():
rng = npr.RandomState(0)
def generator(shape, dtype):
return _cast_to_shape(rng.rand(*_dims_of_shape(shape)) < 0.5, shape, dtype)
return generator
def check_raises(thunk, err_type, msg):
try:
thunk()
assert False
except err_type as e:
assert str(e).startswith(msg), "\n{}\n\n{}\n".format(e, msg)
def check_raises_regexp(thunk, err_type, pattern):
try:
thunk()
assert False
except err_type as e:
assert re.match(pattern, str(e)), "{}\n\n{}\n".format(e, pattern)
def _iter_eqns(jaxpr):
for eqn in jaxpr.eqns:
yield eqn
for subjaxpr, _, _ in eqn.bound_subjaxprs:
for sub_eqn in _iter_eqns(subjaxpr):
yield sub_eqn
def assert_dot_precision(expected_precision, fun, *args):
jaxpr = api.make_jaxpr(fun)(*args)
precisions = [eqn.params['precision'] for eqn in _iter_eqns(jaxpr.jaxpr)
if eqn.primitive == lax.dot_general_p]
for precision in precisions:
msg = "Unexpected precision: {} != {}".format(expected_precision, precision)
assert precision == expected_precision, msg
_CACHED_INDICES = {}
def cases_from_list(xs):
xs = list(xs)
n = len(xs)
k = min(n, FLAGS.num_generated_cases)
# Random sampling for every parameterized test is expensive. Do it once and
# cache the result.
indices = _CACHED_INDICES.get(n)
if indices is None:
rng = npr.RandomState(42)
_CACHED_INDICES[n] = indices = rng.permutation(n)
return [xs[i] for i in indices[:k]]
def cases_from_gens(*gens):
sizes = [1, 3, 10]
cases_per_size = int(FLAGS.num_generated_cases / len(sizes)) + 1
for size in sizes:
for i in xrange(cases_per_size):
yield ('_{}_{}'.format(size, i),) + tuple(gen(size) for gen in gens)
class JaxTestCase(parameterized.TestCase):
"""Base class for JAX tests including numerical checks and boilerplate."""
def assertArraysAllClose(self, x, y, check_dtypes, atol=None, rtol=None):
"""Assert that x and y are close (up to numerical tolerances)."""
self.assertEqual(x.shape, y.shape)
atol = max(tolerance(_dtype(x), atol), tolerance(_dtype(y), atol))
rtol = max(tolerance(_dtype(x), rtol), tolerance(_dtype(y), rtol))
_assert_numpy_allclose(x, y, atol=atol, rtol=rtol)
if check_dtypes:
self.assertDtypesMatch(x, y)
def assertDtypesMatch(self, x, y):
if FLAGS.jax_enable_x64:
self.assertEqual(_dtype(x), _dtype(y))
def assertAllClose(self, x, y, check_dtypes, atol=None, rtol=None):
"""Assert that x and y, either arrays or nested tuples/lists, are close."""
if isinstance(x, dict):
self.assertIsInstance(y, dict)
self.assertEqual(set(x.keys()), set(y.keys()))
for k in x.keys():
self.assertAllClose(x[k], y[k], check_dtypes, atol=atol, rtol=rtol)
elif is_sequence(x) and not hasattr(x, '__array__'):
self.assertTrue(is_sequence(y) and not hasattr(y, '__array__'))
self.assertEqual(len(x), len(y))
for x_elt, y_elt in zip(x, y):
self.assertAllClose(x_elt, y_elt, check_dtypes, atol=atol, rtol=rtol)
elif hasattr(x, '__array__') or onp.isscalar(x):
self.assertTrue(hasattr(y, '__array__') or onp.isscalar(y))
if check_dtypes:
self.assertDtypesMatch(x, y)
x = onp.asarray(x)
y = onp.asarray(y)
self.assertArraysAllClose(x, y, check_dtypes=False, atol=atol, rtol=rtol)
elif x == y:
return
else:
raise TypeError((type(x), type(y)))
def assertMultiLineStrippedEqual(self, expected, what):
"""Asserts two strings are equal, after stripping each line."""
ignore_space_re = re.compile(r'\s*\n\s*')
expected_clean = re.sub(ignore_space_re, '\n', expected.strip())
what_clean = re.sub(ignore_space_re, '\n', what.strip())
self.assertMultiLineEqual(expected_clean, what_clean,
msg="Expecting\n"+expected)
def _CompileAndCheck(self, fun, args_maker, check_dtypes,
rtol=None, atol=None):
"""Helper method for running JAX compilation and allclose assertions."""
args = args_maker()
def wrapped_fun(*args):
self.assertTrue(python_should_be_executing)
return fun(*args)
python_should_be_executing = True
python_ans = fun(*args)
python_shapes = tree_map(lambda x: onp.shape(x), python_ans)
onp_shapes = tree_map(lambda x: onp.shape(onp.asarray(x)), python_ans)
self.assertEqual(python_shapes, onp_shapes)
cache_misses = xla.xla_primitive_callable.cache_info().misses
python_ans = fun(*args)
self.assertEqual(
cache_misses, xla.xla_primitive_callable.cache_info().misses,
"Compilation detected during second call of {} in op-by-op "
"mode.".format(fun))
cfun = api.jit(wrapped_fun)
python_should_be_executing = True
monitored_ans = cfun(*args)
python_should_be_executing = False
compiled_ans = cfun(*args)
self.assertAllClose(python_ans, monitored_ans, check_dtypes, atol, rtol)
self.assertAllClose(python_ans, compiled_ans, check_dtypes, atol, rtol)
args = args_maker()
python_should_be_executing = True
python_ans = fun(*args)
python_should_be_executing = False
compiled_ans = cfun(*args)
self.assertAllClose(python_ans, compiled_ans, check_dtypes, atol, rtol)
def _CheckAgainstNumpy(self, numpy_reference_op, lax_op, args_maker,
check_dtypes=False, tol=None):
args = args_maker()
numpy_ans = numpy_reference_op(*args)
lax_ans = lax_op(*args)
self.assertAllClose(numpy_ans, lax_ans, check_dtypes=check_dtypes,
atol=tol, rtol=tol)
|
jax-master
|
jax/test_util.py
|
# coding=utf-8
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from functools import partial
import numpy as onp
from jax.numpy import lax_numpy as np
from jax import ad_util
from jax import api
from jax import api_util
from jax import core
from jax import lax
from jax import ops
from jax import dtypes
from jax.interpreters import xla
from jax.interpreters import ad
from jax.interpreters import batching
from jax.util import partial, prod
from jax.abstract_arrays import ShapedArray
from jax.core import Primitive
from jax.lax import (standard_primitive, standard_unop, binop_dtype_rule,
_float, _complex, _input_dtype, _broadcasting_select)
from jax.lib import xla_client
from jax.lib import lapack
from jax.lib import cusolver
# traceables
def cholesky(x, symmetrize_input=True):
if symmetrize_input:
x = symmetrize(x)
return np.tril(cholesky_p.bind(x))
def eig(x):
w, vl, vr = eig_p.bind(x)
return w, vl, vr
def eigh(x, lower=True, symmetrize_input=True):
if symmetrize_input:
x = symmetrize(x)
v, w = eigh_p.bind(x, lower=lower)
return v, w
def lu(x):
lu, pivots = lu_p.bind(x)
return lu, pivots
def qr(x, full_matrices=True):
q, r = qr_p.bind(x, full_matrices=full_matrices)
return q, np.triu(r)
def svd(x, full_matrices=True, compute_uv=True):
s, u, v = svd_p.bind(x, full_matrices=full_matrices, compute_uv=compute_uv)
if compute_uv:
return u, s, v
else:
return s
def triangular_solve(a, b, left_side=False, lower=False, transpose_a=False,
conjugate_a=False, unit_diagonal=False):
conjugate_a = conjugate_a and np.issubdtype(lax.dtype(a), np.complexfloating)
return triangular_solve_p.bind(
a, b, left_side=left_side, lower=lower, transpose_a=transpose_a,
conjugate_a=conjugate_a, unit_diagonal=unit_diagonal)
# utilities
def _T(x): return np.swapaxes(x, -1, -2)
def _H(x): return np.conj(_T(x))
def symmetrize(x): return (x + _H(x)) / 2
def _unpack_tuple(f, n):
def g(c, *args, **kwargs):
t = f(c, *args, **kwargs)
return (c.GetTupleElement(t, i) for i in range(n))
return g
# primitives
_cpu_lapack_types = {onp.dtype(onp.float32), onp.dtype(onp.float64),
onp.dtype(onp.complex64), onp.dtype(onp.complex128)}
# Cholesky decomposition
def cholesky_jvp_rule(primals, tangents):
x, = primals
sigma_dot, = tangents
L = np.tril(cholesky_p.bind(x))
# Forward-mode rule from https://arxiv.org/pdf/1602.07527.pdf
def phi(X):
l = np.tril(X)
return l / (np._constant_like(X, 1) + np.eye(X.shape[-1], dtype=X.dtype))
tmp = triangular_solve(L, sigma_dot, left_side=False, transpose_a=True,
conjugate_a=True, lower=True)
L_dot = lax.batch_matmul(L, phi(triangular_solve(
L, tmp, left_side=True, transpose_a=False, lower=True)),
precision=lax.Precision.HIGHEST)
return L, L_dot
def cholesky_batching_rule(batched_args, batch_dims):
x, = batched_args
bd, = batch_dims
x = batching.moveaxis(x, bd, 0)
return cholesky(x), 0
cholesky_p = standard_unop(_float | _complex, 'cholesky')
ad.primitive_jvps[cholesky_p] = cholesky_jvp_rule
batching.primitive_batchers[cholesky_p] = cholesky_batching_rule
def _nan_like(c, operand):
shape = c.GetShape(operand)
dtype = shape.element_type()
if np.issubdtype(dtype, onp.complexfloating):
nan = c.Constant(onp.array(onp.nan * (1. + 1j), dtype=dtype))
else:
nan = c.Constant(onp.array(onp.nan, dtype=dtype))
return c.Broadcast(nan, shape.dimensions())
def cholesky_cpu_translation_rule(c, operand):
shape = c.GetShape(operand)
dtype = shape.element_type().type
if len(shape.dimensions()) == 2 and onp.dtype(dtype) in _cpu_lapack_types:
result, info = lapack.potrf(c, operand, lower=True)
return c.Select(c.Eq(info, c.ConstantS32Scalar(0)), result,
_nan_like(c, result))
else:
# Fall back to the HLO implementation for batched Cholesky decomposition or
# unsupported types.
# TODO(phawkins): support LAPACK primitives in batched mode.
return c.Cholesky(operand)
xla.backend_specific_translations['cpu'][cholesky_p] = cholesky_cpu_translation_rule
# Asymmetric eigendecomposition
def eig_impl(operand):
return xla.apply_primitive(eig_p, operand)
def eig_translation_rule(c, operand):
raise NotImplementedError(
"Nonsymmetric eigendecomposition is only implemented on the CPU backend")
def eig_abstract_eval(operand):
if isinstance(operand, ShapedArray):
if operand.ndim < 2 or operand.shape[-2] != operand.shape[-1]:
raise ValueError("Argument to nonsymmetric eigendecomposition must have "
"shape [..., n, n], got shape {}".format(operand.shape))
batch_dims = operand.shape[:-2]
n = operand.shape[-1]
dtype = onp.complex64 if dtypes.finfo(operand.dtype).bits == 32 else onp.complex128
dtype = dtypes.canonicalize_dtype(dtype)
vl = vr = ShapedArray(batch_dims + (n, n), dtype)
w = ShapedArray(batch_dims + (n,), dtype)
else:
raise NotImplementedError
return w, vl, vr
_cpu_geev = lapack.geev
def eig_cpu_translation_rule(c, operand):
shape = c.GetShape(operand)
batch_dims = shape.dimensions()[:-2]
w, vl, vr, info = _cpu_geev(c, operand)
ok = c.Eq(info, c.ConstantS32Scalar(0))
w = _broadcasting_select(c, c.Reshape(ok, None, batch_dims + (1,)), w,
_nan_like(c, w))
vl = _broadcasting_select(c, c.Reshape(ok, None, batch_dims + (1, 1)), vl,
_nan_like(c, vl))
vr = _broadcasting_select(c, c.Reshape(ok, None, batch_dims + (1, 1)), vr,
_nan_like(c, vr))
return c.Tuple(w, vl, vr)
def eig_batching_rule(batched_args, batch_dims):
x, = batched_args
bd, = batch_dims
x = batching.moveaxis(x, bd, 0)
return eig_p.bind(x), (0, 0, 0)
eig_p = Primitive('eig')
eig_p.multiple_results = True
eig_p.def_impl(eig_impl)
eig_p.def_abstract_eval(eig_abstract_eval)
xla.translations[eig_p] = eig_translation_rule
xla.backend_specific_translations['cpu'][eig_p] = eig_cpu_translation_rule
batching.primitive_batchers[eig_p] = eig_batching_rule
# Symmetric/Hermitian eigendecomposition
def eigh_impl(operand, lower):
v, w = xla.apply_primitive(eigh_p, operand, lower=lower)
return v, w
def eigh_translation_rule(c, operand, lower):
shape = c.GetShape(operand)
dims = shape.dimensions()
if dims[-1] == 0:
return c.Tuple(operand, c.Reshape(operand, None, dims[:-1]))
if not lower:
n = len(dims)
operand = c.Transpose(operand, list(range(n - 2)) + [n - 1, n - 2])
return c.Eigh(operand)
def eigh_abstract_eval(operand, lower):
if isinstance(operand, ShapedArray):
if operand.ndim < 2 or operand.shape[-2] != operand.shape[-1]:
raise ValueError(
"Argument to symmetric eigendecomposition must have shape [..., n, n],"
"got shape {}".format(operand.shape))
batch_dims = operand.shape[:-2]
n = operand.shape[-1]
v = ShapedArray(batch_dims + (n, n), operand.dtype)
w = ShapedArray(batch_dims + (n,), lax.lax._complex_basetype(operand.dtype))
else:
v, w = operand, operand
return v, w
def _eigh_cpu_gpu_translation_rule(syevd_impl, c, operand, lower):
shape = c.GetShape(operand)
batch_dims = shape.dimensions()[:-2]
v, w, info = syevd_impl(c, operand, lower=lower)
ok = c.Eq(info, c.ConstantS32Scalar(0))
v = _broadcasting_select(c, c.Reshape(ok, None, batch_dims + (1, 1)), v,
_nan_like(c, v))
w = _broadcasting_select(c, c.Reshape(ok, None, batch_dims + (1,)), w,
_nan_like(c, w))
return c.Tuple(v, w)
def eigh_jvp_rule(primals, tangents, lower):
# Derivative for eigh in the simplest case of distinct eigenvalues.
# This is classic nondegenerate perurbation theory, but also see
# https://people.maths.ox.ac.uk/gilesm/files/NA-08-01.pdf
# The general solution treating the case of degenerate eigenvalues is
# considerably more complicated. Ambitious readers may refer to the general
# methods below or refer to degenerate perturbation theory in physics.
# https://www.win.tue.nl/analysis/reports/rana06-33.pdf and
# https://people.orie.cornell.edu/aslewis/publications/99-clarke.pdf
a, = primals
a_dot, = tangents
v, w = eigh_p.bind(symmetrize(a), lower=lower)
# for complex numbers we need eigenvalues to be full dtype of v, a:
w = w.astype(a.dtype)
eye_n = np.eye(a.shape[-1], dtype=a.dtype)
# carefully build reciprocal delta-eigenvalue matrix, avoiding NaNs.
Fmat = np.reciprocal(eye_n + w[..., np.newaxis, :] - w[..., np.newaxis]) - eye_n
# eigh impl doesn't support batch dims, but future-proof the grad.
dot = partial(lax.dot if a.ndim == 2 else lax.batch_matmul,
precision=lax.Precision.HIGHEST)
vdag_adot_v = dot(dot(_H(v), a_dot), v)
dv = dot(v, np.multiply(Fmat, vdag_adot_v))
dw = np.diagonal(vdag_adot_v, axis1=-2, axis2=-1)
return (v, w), (dv, dw)
def eigh_batching_rule(batched_args, batch_dims, lower):
x, = batched_args
bd, = batch_dims
x = batching.moveaxis(x, bd, 0)
return eigh_p.bind(x, lower=lower), (0, 0)
eigh_p = Primitive('eigh')
eigh_p.multiple_results = True
eigh_p.def_impl(eigh_impl)
eigh_p.def_abstract_eval(eigh_abstract_eval)
xla.translations[eigh_p] = eigh_translation_rule
ad.primitive_jvps[eigh_p] = eigh_jvp_rule
batching.primitive_batchers[eigh_p] = eigh_batching_rule
_cpu_syevd = lapack.syevd
xla.backend_specific_translations['cpu'][eigh_p] = partial(
_eigh_cpu_gpu_translation_rule, _cpu_syevd)
xla.backend_specific_translations['gpu'][eigh_p] = partial(
_eigh_cpu_gpu_translation_rule, cusolver.syevd)
triangular_solve_dtype_rule = partial(
binop_dtype_rule, _input_dtype, (_float | _complex, _float | _complex),
'triangular_solve')
def triangular_solve_shape_rule(a, b, left_side=False, **unused_kwargs):
if a.ndim < 2:
msg = "triangular_solve requires a.ndim to be at least 2, got {}."
raise TypeError(msg.format(a.ndim))
if a.shape[-1] != a.shape[-2]:
msg = ("triangular_solve requires the last two dimensions of a to be equal "
"in size, got a.shape of {}.")
raise TypeError(msg.format(a.shape))
if a.shape[:-2] != b.shape[:-2]:
msg = ("triangular_solve requires both arguments to have the same number "
"of dimensions and equal batch dimensions, got {} and {}.")
raise TypeError(msg.format(a.shape, b.shape))
common_dim = -2 if left_side else -1
if a.shape[-1] != b.shape[common_dim]:
msg = "Incompatible shapes for arguments to triangular_solve: {} and {}."
raise TypeError(msg.format(a.shape, b.shape))
return b.shape
def triangular_solve_jvp_rule_a(
g_a, ans, a, b, left_side, lower, transpose_a, conjugate_a, unit_diagonal):
m, n = b.shape[-2:]
k = 1 if unit_diagonal else 0
g_a = np.tril(g_a, k=-k) if lower else np.triu(g_a, k=k)
g_a = lax.neg(g_a)
g_a = np.swapaxes(g_a, -1, -2) if transpose_a else g_a
g_a = np.conj(g_a) if conjugate_a else g_a
dot = partial(lax.dot if g_a.ndim == 2 else lax.batch_matmul,
precision=lax.Precision.HIGHEST)
def a_inverse(rhs):
return triangular_solve(a, rhs, left_side, lower, transpose_a, conjugate_a,
unit_diagonal)
# triangular_solve is about the same cost as matrix multplication (~n^2 FLOPs
# for matrix/vector inputs). Order these operations in whichever order is
# cheaper.
if left_side:
assert g_a.shape[-2:] == a.shape[-2:] == (m, m) and ans.shape[-2:] == (m, n)
if m > n:
return a_inverse(dot(g_a, ans)) # A^{-1} (∂A X)
else:
return dot(a_inverse(g_a), ans) # (A^{-1} ∂A) X
else:
assert g_a.shape[-2:] == a.shape[-2:] == (n, n) and ans.shape[-2:] == (m, n)
if m < n:
return a_inverse(dot(ans, g_a)) # (X ∂A) A^{-1}
else:
return dot(ans, a_inverse(g_a)) # X (∂A A^{-1})
def triangular_solve_transpose_rule(
cotangent, a, b, left_side, lower, transpose_a, conjugate_a,
unit_diagonal):
# Triangular solve is nonlinear in its first argument and linear in its second
# argument, analogous to `div` but swapped.
assert a is not ad.undefined_primal and b is ad.undefined_primal
if cotangent is ad_util.zero:
cotangent_b = ad_util.zero
else:
cotangent_b = triangular_solve(a, cotangent, left_side, lower,
not transpose_a, conjugate_a, unit_diagonal)
return [None, cotangent_b]
def triangular_solve_batching_rule(batched_args, batch_dims, left_side,
lower, transpose_a, conjugate_a,
unit_diagonal):
x, y = batched_args
bx, by = batch_dims
size = next(t.shape[i] for t, i in zip(batched_args, batch_dims)
if i is not None)
x = batching.bdim_at_front(x, bx, size)
y = batching.bdim_at_front(y, by, size)
return triangular_solve(x, y, left_side=left_side, lower=lower,
transpose_a=transpose_a, conjugate_a=conjugate_a,
unit_diagonal=unit_diagonal), 0
triangular_solve_p = standard_primitive(
triangular_solve_shape_rule, triangular_solve_dtype_rule,
'triangular_solve')
ad.defjvp2(triangular_solve_p,
triangular_solve_jvp_rule_a,
lambda g_b, _, a, b, **kws: triangular_solve(a, g_b, **kws))
ad.primitive_transposes[triangular_solve_p] = triangular_solve_transpose_rule
batching.primitive_batchers[triangular_solve_p] = triangular_solve_batching_rule
def _triangular_solve_cpu_translation_rule(
c, a, b, left_side, lower, transpose_a, conjugate_a, unit_diagonal):
shape = c.GetShape(a)
dtype = shape.element_type().type
if len(shape.dimensions()) == 2 and onp.dtype(dtype) in _cpu_lapack_types:
if conjugate_a and not transpose_a:
a = c.Conj(a)
conjugate_a = False
return lapack.jax_trsm(
c, c.Constant(onp.array(1, dtype=dtype)), a, b, left_side, lower,
transpose_a, conjugate_a, unit_diagonal)
else:
# Fall back to the HLO implementation for batched triangular_solve or
# unsupported types.
# TODO(phawkins): support BLAS primitives in batched mode.
return c.TriangularSolve(a, b, left_side, lower, transpose_a, conjugate_a,
unit_diagonal)
xla.backend_specific_translations['cpu'][triangular_solve_p] = \
_triangular_solve_cpu_translation_rule
def _triangular_solve_gpu_translation_rule(
c, a, b, left_side, lower, transpose_a, conjugate_a, unit_diagonal):
shape = c.GetShape(a)
dtype = shape.element_type().type
dims = shape.dimensions()
m, n = dims[-2:]
batch = prod(dims[:-2])
if batch > 1 and m <= 32 and n <= 32:
if conjugate_a and not transpose_a:
a = c.Conj(a)
conjugate_a = False
return cusolver.trsm(
c, a, b, left_side, lower, transpose_a, conjugate_a, unit_diagonal)
else:
# Use the XLA implementation for unbatched triangular_solve.
return c.TriangularSolve(a, b, left_side, lower, transpose_a, conjugate_a,
unit_diagonal)
xla.backend_specific_translations['gpu'][triangular_solve_p] = \
_triangular_solve_gpu_translation_rule
# LU decomposition
# Computes a pivoted LU decomposition such that
# PA = LU
# In the style of LAPACK, LU are stored in the same matrix.
def _lu_unblocked(a):
"""Unblocked LU decomposition, as a rolled loop."""
m, n = a.shape
def body(k, state):
pivot, perm, a = state
m_idx = np.arange(m)
n_idx = np.arange(n)
if np.issubdtype(a.dtype, np.complexfloating):
t = a[:, k]
magnitude = np.abs(np.real(t)) + np.abs(np.imag(t))
else:
magnitude = np.abs(a[:, k])
i = np.argmax(np.where(m_idx >= k, magnitude, -np.inf))
pivot = ops.index_update(pivot, ops.index[k], i)
a = ops.index_update(a, ops.index[[k, i],], a[[i, k],])
perm = ops.index_update(perm, ops.index[[i, k],], perm[[k, i],])
# a[k+1:, k] /= a[k, k], adapted for loop-invariant shapes
x = a[k, k]
a = ops.index_update(a, ops.index[:, k],
np.where(m_idx > k, a[:, k] / x, a[:, k]))
# a[k+1:, k+1:] -= np.outer(a[k+1:, k], a[k, k+1:])
a = a - np.where((m_idx[:, None] > k) & (n_idx > k),
np.outer(a[:, k], a[k, :]), np.array(0, dtype=a.dtype))
return pivot, perm, a
pivot = np.zeros((min(m, n),), dtype=np.int32)
perm = np.arange(m, dtype=np.int32)
if m == 0 and n == 0:
# If the array is empty, the loop body never executes but tracing it to a
# jaxpr fails because the indexing cannot succeed.
return (pivot, perm, a)
return lax.fori_loop(0, min(m, n), body, (pivot, perm, a))
def _lu_blocked(a, block_size=32):
"""Blocked LU decomposition, as an unrolled loop."""
m, n = a.shape
r = min(m, n)
pivot = np.zeros((r,), dtype=np.int32)
for k in range(0, r, block_size):
b = min(r - k, block_size)
block_pivot, perm, lu_block = _lu_unblocked(a[k:, k:k+b])
a = ops.index_update(a, ops.index[k:, k:k+b], lu_block)
a = ops.index_update(a, ops.index[k:, :k], a[perm + k, :k])
pivot = ops.index_update(pivot, ops.index[k:k+b], block_pivot + k)
if k + b < n:
a = ops.index_update(a, ops.index[k:, k+b:], a[perm + k, k+b:])
a = ops.index_update(
a, ops.index[k:k+b, k+b:],
triangular_solve(a[k:k+b, k:k+b], a[k:k+b, k+b:],
left_side=True, lower=True, unit_diagonal=True))
a = ops.index_add(
a, ops.index[k+b:, k+b:],
-lax.dot(a[k+b:, k:k+b], a[k:k+b, k+b:],
precision=lax.Precision.HIGHEST))
return pivot, a
def _lu_python(x):
"""Default LU decomposition in Python, where no better version exists."""
m, n = x.shape[-2:]
batch_dims = x.shape[:-2]
if len(batch_dims) > 0:
batch_size = onp.prod(batch_dims, dtype=onp.int64)
pivot, lu = api.vmap(_lu_blocked)(lax.reshape(x, (batch_size, m, n)))
pivot = lax.reshape(pivot, batch_dims + (min(m, n),))
lu = lax.reshape(lu, batch_dims + (m, n))
else:
pivot, lu = _lu_blocked(x)
return lu, pivot
def _lu_impl(operand):
lu, pivot = xla.apply_primitive(lu_p, operand)
return lu, pivot
def _lu_abstract_eval(operand):
if isinstance(operand, ShapedArray):
if operand.ndim < 2:
raise ValueError("Argument to LU decomposition must have ndims >= 2")
batch_dims = operand.shape[:-2]
m = operand.shape[-2]
n = operand.shape[-1]
pivot = ShapedArray(batch_dims + (min(m, n),), np.int32)
else:
pivot = operand
return operand, pivot
def _lu_jvp_rule(primals, tangents):
a, = primals
a_dot, = tangents
lu, pivots = lu_p.bind(a)
a_shape = np.shape(a)
m, n = a_shape[-2:]
dtype = lax.dtype(a)
k = min(m, n)
permutation = lu_pivots_to_permutation(pivots, m)
batch_dims = a_shape[:-2]
iotas = np.ix_(*(lax.iota(np.int32, b) for b in batch_dims + (1,)))
x = a_dot[iotas[:-1] + (permutation, slice(None))]
# Differentiation of Matrix Functionals Using Triangular Factorization
# F. R. De Hoog, R. S. Anderssen, and M. A. Lukas
#
# LU = A
# ==> L'U + LU' = A'
# ==> inv(L) . L' + U' . inv(U) = inv(L) A' inv(U)
# ==> L' = L . tril(inv(L) . A' . inv(U), -1)
# U' = triu(inv(L) . A' . inv(U)) . U
ndims = len(a_shape)
l_padding = [(0, 0, 0)] * ndims
l_padding[-1] = (0, m - k, 0)
zero = np._constant_like(lu, 0)
l = lax.pad(np.tril(lu[..., :, :k], -1), zero, l_padding)
l = l + np.eye(m, m, dtype=dtype)
u_eye = lax.pad(np.eye(n - k, n - k, dtype=dtype), zero,
((k, 0, 0), (k, 0, 0)))
u_padding = [(0, 0, 0)] * ndims
u_padding[-2] = (0, n - k, 0)
u = lax.pad(np.triu(lu[..., :k, :]), zero, u_padding) + u_eye
la = triangular_solve(l, x, left_side=True, transpose_a=False, lower=True,
unit_diagonal=True)
lau = triangular_solve(u, la, left_side=False, transpose_a=False,
lower=False)
l_dot = np.matmul(l, np.tril(lau, -1))
u_dot = np.matmul(np.triu(lau), u)
lu_dot = l_dot + u_dot
return (lu, pivots), (lu_dot, ad_util.zero)
def _lu_batching_rule(batched_args, batch_dims):
x, = batched_args
bd, = batch_dims
x = batching.moveaxis(x, bd, 0)
return lu_p.bind(x), (0, 0)
def _lu_cpu_gpu_translation_rule(getrf_impl, c, operand):
shape = c.GetShape(operand)
batch_dims = shape.dimensions()[:-2]
lu, pivot, info = getrf_impl(c, operand)
# Subtract 1 from the pivot to get 0-based indices.
pivot = c.Sub(pivot, c.ConstantS32Scalar(1))
ok = c.Ge(info, c.ConstantS32Scalar(0))
lu = _broadcasting_select(c, c.Reshape(ok, None, batch_dims + (1, 1)), lu,
_nan_like(c, lu))
return c.Tuple(lu, pivot)
lu_p = Primitive('lu')
lu_p.multiple_results = True
lu_p.def_impl(_lu_impl)
lu_p.def_abstract_eval(_lu_abstract_eval)
xla.translations[lu_p] = xla.lower_fun(_lu_python, instantiate=True)
ad.primitive_jvps[lu_p] = _lu_jvp_rule
batching.primitive_batchers[lu_p] = _lu_batching_rule
xla.backend_specific_translations['cpu'][lu_p] = partial(
_lu_cpu_gpu_translation_rule, lapack.getrf)
xla.backend_specific_translations['gpu'][lu_p] = partial(
_lu_cpu_gpu_translation_rule, cusolver.getrf)
# Define this outside lu_pivots_to_permutation to ensure fori_loop cache hits
def _lu_pivots_body_fn(i, permutation_and_swaps):
permutation, swaps = permutation_and_swaps
batch_dims = swaps.shape[:-1]
j = swaps[..., i]
iotas = np.ix_(*(lax.iota(np.int32, b) for b in batch_dims))
x = permutation[..., i]
y = permutation[iotas + (j,)]
permutation = ops.index_update(permutation, ops.index[..., i], y)
return ops.index_update(permutation, ops.index[iotas + (j,)], x), swaps
def lu_pivots_to_permutation(swaps, m):
"""Converts the pivots (row swaps) returned by LU to a permutation.
We build a permutation rather than applying `swaps` directly to the rows
of a matrix because lax loops aren't differentiable.
Args:
swaps: an array of shape (..., k) of row swaps to perform
m: the size of the output permutation. m should be >= k.
Returns:
An int32 array of shape (..., m).
"""
assert len(swaps.shape) >= 1
batch_dims = swaps.shape[:-1]
k = swaps.shape[-1]
permutation = lax.broadcasted_iota(np.int32, batch_dims + (m,),
len(batch_dims))
result, _ = lax.fori_loop(onp.array(0, onp.int32), onp.array(k, onp.int32),
_lu_pivots_body_fn, (permutation, swaps))
return result
# QR decomposition
def qr_impl(operand, full_matrices):
q, r = xla.apply_primitive(qr_p, operand, full_matrices=full_matrices)
return q, r
def qr_translation_rule(c, operand, full_matrices):
return c.QR(operand, full_matrices=full_matrices)
def qr_abstract_eval(operand, full_matrices):
if isinstance(operand, ShapedArray):
if operand.ndim < 2:
raise ValueError("Argument to QR decomposition must have ndims >= 2")
batch_dims = operand.shape[:-2]
m = operand.shape[-2]
n = operand.shape[-1]
k = m if full_matrices else min(m, n)
q = ShapedArray(batch_dims + (m, k), operand.dtype)
r = ShapedArray(batch_dims + (k, n), operand.dtype)
else:
q = operand
r = operand
return q, r
def qr_jvp_rule(primals, tangents, full_matrices):
# See j-towns.github.io/papers/qr-derivative.pdf for a terse derivation.
x, = primals
dx, = tangents
q, r = qr_p.bind(x, full_matrices=False)
if full_matrices or np.shape(x)[-2] < np.shape(x)[-1]:
raise NotImplementedError
dx_rinv = triangular_solve(r, dx) # Right side solve by default
qt_dx_rinv = np.matmul(_H(q), dx_rinv)
qt_dx_rinv_lower = np.tril(qt_dx_rinv, -1)
domega = qt_dx_rinv_lower - _H(qt_dx_rinv_lower) # This is skew-symmetric
dq = np.matmul(q, domega - qt_dx_rinv) + dx_rinv
dr = np.matmul(qt_dx_rinv - domega, r)
return (q, r), (dq, dr)
def qr_batching_rule(batched_args, batch_dims, full_matrices):
x, = batched_args
bd, = batch_dims
x = batching.moveaxis(x, bd, 0)
return qr_p.bind(x, full_matrices=full_matrices), (0, 0)
def _qr_cpu_gpu_translation_rule(geqrf_impl, orgqr_impl, c, operand,
full_matrices):
shape = c.GetShape(operand)
dims = shape.dimensions()
m, n = dims[-2:]
batch_dims = dims[:-2]
r, tau, info_geqrf = geqrf_impl(c, operand)
if m < n:
q = c.Slice(r, [0] * len(dims), list(batch_dims) + [m, m])
q, info_orgqr = orgqr_impl(c, q, tau)
elif not full_matrices:
q, info_orgqr = orgqr_impl(c, r, tau)
r = c.Slice(r, [0] * len(dims), list(batch_dims) + [n, n])
else:
padding_config = [(0, 0, 0)] * len(dims)
padding_config[-1] = (0, m - n, 0)
q = c.Pad(r, c.Constant(onp.array(0, dtype=shape.element_type())),
padding_config)
q, info_orgqr = orgqr_impl(c, q, tau)
ok = c.And(c.Eq(info_geqrf, c.ConstantS32Scalar(0)),
c.Eq(info_orgqr, c.ConstantS32Scalar(0)))
q = _broadcasting_select(c, c.Reshape(ok, None, batch_dims + (1, 1)), q,
_nan_like(c, q))
r = _broadcasting_select(c, c.Reshape(ok, None, batch_dims + (1, 1)), r,
_nan_like(c, r))
return c.Tuple(q, r)
qr_p = Primitive('qr')
qr_p.multiple_results = True
qr_p.def_impl(qr_impl)
qr_p.def_abstract_eval(qr_abstract_eval)
xla.translations[qr_p] = qr_translation_rule
ad.primitive_jvps[qr_p] = qr_jvp_rule
batching.primitive_batchers[qr_p] = qr_batching_rule
xla.backend_specific_translations['cpu'][qr_p] = partial(
_qr_cpu_gpu_translation_rule, lapack.geqrf, lapack.orgqr)
xla.backend_specific_translations['gpu'][qr_p] = partial(
_qr_cpu_gpu_translation_rule, cusolver.geqrf, cusolver.orgqr)
# Singular value decomposition
def svd_impl(operand, full_matrices, compute_uv):
s, u, vt = xla.apply_primitive(svd_p, operand, full_matrices=full_matrices,
compute_uv=compute_uv)
return s, u, vt
def svd_translation_rule(c, operand, full_matrices, compute_uv):
raise NotImplementedError(
"Singular value decomposition is only implemented on the CPU and GPU backends")
def svd_abstract_eval(operand, full_matrices, compute_uv):
if isinstance(operand, ShapedArray):
if operand.ndim < 2:
raise ValueError("Argument to singular value decomposition must have ndims >= 2")
batch_dims = operand.shape[:-2]
m = operand.shape[-2]
n = operand.shape[-1]
s = ShapedArray(batch_dims + (min(m, n),), lax.lax._complex_basetype(operand.dtype))
u = ShapedArray(batch_dims + (m, m if full_matrices else min(m, n)), operand.dtype)
vt = ShapedArray(batch_dims + (n if full_matrices else min(m, n), n), operand.dtype)
else:
raise NotImplementedError
return s, u, vt
def svd_jvp_rule(primals, tangents, full_matrices, compute_uv):
A, = primals
dA, = tangents
s, U, Vt = svd_p.bind(A, full_matrices=False, compute_uv=True)
if full_matrices:
# TODO: implement full matrices case, documented here: https://people.maths.ox.ac.uk/gilesm/files/NA-08-01.pdf
raise NotImplementedError(
"Singular value decomposition JVP not implemented for full matrices")
k = s.shape[-1]
Ut, V = _H(U), _H(Vt)
s_dim = s[..., None, :]
dS = np.matmul(np.matmul(Ut, dA), V)
ds = np.real(np.diagonal(dS, 0, -2, -1))
F = 1 / (np.square(s_dim) - np.square(_T(s_dim)) + np.eye(k)) - np.eye(k)
dSS = s_dim * dS
SdS = _T(s_dim) * dS
dU = np.matmul(U, F * (dSS + _T(dSS)))
dV = np.matmul(V, F * (SdS + _T(SdS)))
m, n = A.shape[-2], A.shape[-1]
if m > n:
dU = dU + np.matmul(np.eye(m) - np.matmul(U, Ut), np.matmul(dA, V)) / s_dim
if n > m:
dV = dV + np.matmul(np.eye(n) - np.matmul(V, Vt), np.matmul(_H(dA), U)) / s_dim
return (s, U, Vt), (ds, dU, _T(dV))
def _svd_cpu_gpu_translation_rule(gesvd_impl, c, operand, full_matrices, compute_uv):
shape = c.GetShape(operand)
batch_dims = shape.dimensions()[:-2]
s, u, vt, info = gesvd_impl(c, operand, full_matrices=full_matrices,
compute_uv=compute_uv)
ok = c.Eq(info, c.ConstantS32Scalar(0))
s = _broadcasting_select(c, c.Reshape(ok, None, batch_dims + (1,)), s,
_nan_like(c, s))
u = _broadcasting_select(c, c.Reshape(ok, None, batch_dims + (1, 1)), u,
_nan_like(c, u))
vt = _broadcasting_select(c, c.Reshape(ok, None, batch_dims + (1, 1)), vt,
_nan_like(c, vt))
return c.Tuple(s, u, vt)
def svd_batching_rule(batched_args, batch_dims, full_matrices, compute_uv):
x, = batched_args
bd, = batch_dims
x = batching.moveaxis(x, bd, 0)
outs = svd_p.bind(x, full_matrices=full_matrices, compute_uv=compute_uv)
return outs, (0, 0, 0)
svd_p = Primitive('svd')
svd_p.multiple_results = True
svd_p.def_impl(svd_impl)
svd_p.def_abstract_eval(svd_abstract_eval)
ad.primitive_jvps[svd_p] = svd_jvp_rule
batching.primitive_batchers[svd_p] = svd_batching_rule
xla.translations[svd_p] = svd_translation_rule
xla.backend_specific_translations['cpu'][svd_p] = partial(
_svd_cpu_gpu_translation_rule, lapack.gesdd)
xla.backend_specific_translations['gpu'][svd_p] = partial(
_svd_cpu_gpu_translation_rule, cusolver.gesvd)
|
jax-master
|
jax/lax_linalg.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
"""JAX pseudo-random number generators (PRNGs).
The JAX PRNG system is based on "Parallel random numbers: as easy as 1, 2, 3"
(Salmon et al. 2011). For details on the design and its motivation, see:
https://github.com/google/jax/blob/master/design_notes/prng.md
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from functools import partial
import itertools
import numpy as onp
from . import lax
from . import numpy as np
from . import tree_util
from . import dtypes
from .api import custom_transforms, defjvp, jit, vmap
from .numpy.lax_numpy import _constant_like, asarray, stack
from jax.lib import xla_bridge
from jax.lib import cuda_prng
from jax import core
from jax import abstract_arrays
from jax.numpy.linalg import cholesky
from jax.scipy.special import logit
from jax.interpreters import batching
from jax.interpreters import xla
def PRNGKey(seed):
"""Create a pseudo-random number generator (PRNG) key given an integer seed.
Args:
seed: a 64- or 32-bit integer used as the value of the key.
Returns:
A PRNG key, which is modeled as an array of shape (2,) and dtype uint32. The
key is constructed from a 64-bit seed by effectively bit-casting to a pair
of uint32 values (or from a 32-bit seed by first padding out with zeros).
"""
if onp.shape(seed):
raise TypeError("PRNGKey seed must be a scalar.")
convert = lambda k: lax.reshape(lax.convert_element_type(k, onp.uint32), [1])
if isinstance(seed, (int, onp.ndarray)):
# Special handling of raw integer values, which may have be 64bit even
# when jax_enable_x64=False and we don't want to drop the top 32 bits
k1 = convert(onp.bitwise_and(onp.right_shift(seed, 32), 0xFFFFFFFF))
else:
k1 = convert(lax.shift_right_logical(seed, lax._const(seed, 32)))
k2 = convert(np.bitwise_and(seed, 0xFFFFFFFF))
return lax.concatenate([k1, k2], 0)
def _is_prng_key(key):
try:
return key.shape == (2,) and key.dtype == onp.uint32
except AttributeError:
return False
### utilities
def _make_rotate_left(dtype):
if not np.issubdtype(dtype, onp.integer):
raise TypeError("_rotate_left only accepts integer dtypes.")
nbits = onp.array(np.iinfo(dtype).bits, dtype)
def _rotate_left(x, d):
if lax.dtype(d) != lax.dtype(x):
d = lax.convert_element_type(d, x.dtype)
return lax.shift_left(x, d) | lax.shift_right_logical(x, nbits - d)
return _rotate_left
def _bit_stats(bits):
"""This is a debugging function to compute the statistics of bit fields."""
return onp.array([list(map(int, onp.binary_repr(x, 64))) for x in bits]).mean(0)
### hash function and split
def _threefry2x32_abstract_eval(*args):
if any(a.dtype != np.uint32 for a in args):
raise TypeError("Arguments to threefry2x32 must have uint32 type, got {}"
.format(args))
if all(isinstance(arg, abstract_arrays.ShapedArray) for arg in args):
shape = lax._broadcasting_shape_rule(*args)
aval = abstract_arrays.ShapedArray(shape, np.dtype(np.uint32))
else:
aval = abstract_arrays.UnshapedArray(np.dtype(np.uint32))
return (aval,) * 2
def _threefry2x32_lowering(key1, key2, x1, x2, use_rolled_loops=True):
"""Apply the Threefry 2x32 hash.
Args:
keypair: a pair of 32bit unsigned integers used for the key.
count: an array of dtype uint32 used for the counts.
Returns:
An array of dtype uint32 with the same shape as `count`.
"""
x = [x1, x2]
rotate_left = _make_rotate_left(onp.uint32)
def apply_round(v, rot):
v = v[:]
v[0] = v[0] + v[1]
v[1] = rotate_left(v[1], rot)
v[1] = v[0] ^ v[1]
return v
rotations = [onp.array([13, 15, 26, 6], dtype=onp.uint32),
onp.array([17, 29, 16, 24], dtype=onp.uint32)]
ks = [key1, key2, key1 ^ key2 ^ onp.uint32(0x1BD11BDA)]
x[0] = x[0] + ks[0]
x[1] = x[1] + ks[1]
if use_rolled_loops:
def rotate_list(xs): return xs[1:] + xs[:1]
def step(i, state):
x, ks, rotations = state
for r in rotations[0]:
x = apply_round(x, r)
new_x = [x[0] + ks[0], x[1] + ks[1] + asarray(i + 1, dtype=onp.uint32)]
return new_x, rotate_list(ks), rotate_list(rotations)
x, _, _ = lax.fori_loop(0, 5, step, (x, rotate_list(ks), rotations))
else:
for r in rotations[0]:
x = apply_round(x, r)
x[0] = x[0] + ks[1]
x[1] = x[1] + ks[2] + onp.uint32(1)
for r in rotations[1]:
x = apply_round(x, r)
x[0] = x[0] + ks[2]
x[1] = x[1] + ks[0] + onp.uint32(2)
for r in rotations[0]:
x = apply_round(x, r)
x[0] = x[0] + ks[0]
x[1] = x[1] + ks[1] + onp.uint32(3)
for r in rotations[1]:
x = apply_round(x, r)
x[0] = x[0] + ks[1]
x[1] = x[1] + ks[2] + onp.uint32(4)
for r in rotations[0]:
x = apply_round(x, r)
x[0] = x[0] + ks[2]
x[1] = x[1] + ks[0] + onp.uint32(5)
return tuple(x)
def _threefry2x32_gpu_translation_rule(c, k1, k2, x1, x2):
shape = lax.broadcast_shapes(
c.GetShape(k1).dimensions(), c.GetShape(k2).dimensions(),
c.GetShape(x1).dimensions(), c.GetShape(x2).dimensions())
rank = len(shape)
def _broadcast(x):
ndims = c.GetShape(x).rank()
return c.BroadcastInDim(x, shape, tuple(range(rank - ndims, rank)))
return cuda_prng.threefry2x32(
c, (_broadcast(k1), _broadcast(k2)), (_broadcast(x1), _broadcast(x2)))
threefry2x32_p = core.Primitive("threefry2x32")
threefry2x32_p.multiple_results = True
threefry2x32_p.def_impl(partial(xla.apply_primitive, threefry2x32_p))
threefry2x32_p.def_abstract_eval(_threefry2x32_abstract_eval)
batching.defbroadcasting(threefry2x32_p)
xla.translations[threefry2x32_p] = xla.lower_fun(
partial(_threefry2x32_lowering, use_rolled_loops=False), instantiate=True)
xla.backend_specific_translations['cpu'][threefry2x32_p] = xla.lower_fun(
partial(_threefry2x32_lowering, use_rolled_loops=True), instantiate=True)
if cuda_prng:
xla.backend_specific_translations['gpu'][threefry2x32_p] = \
_threefry2x32_gpu_translation_rule
@jit
def threefry_2x32(keypair, count):
"""Apply the Threefry 2x32 hash.
Args:
keypair: a pair of 32bit unsigned integers used for the key.
count: an array of dtype uint32 used for the counts.
Returns:
An array of dtype uint32 with the same shape as `count`.
"""
key1, key2 = keypair
if not lax.dtype(key1) == lax.dtype(key2) == lax.dtype(count) == onp.uint32:
msg = "threefry_2x32 requires uint32 arguments, got {}"
raise TypeError(msg.format([lax.dtype(x) for x in [key1, key2, count]]))
odd_size = count.size % 2
if odd_size:
x = list(np.split(np.concatenate([count.ravel(), onp.uint32([0])]), 2))
else:
x = list(np.split(count.ravel(), 2))
x = threefry2x32_p.bind(key1, key2, x[0], x[1])
out = np.concatenate(x)
assert out.dtype == onp.uint32
return lax.reshape(out[:-1] if odd_size else out, count.shape)
def split(key, num=2):
"""Splits a PRNG key into `num` new keys by adding a leading axis.
Args:
key: a PRNGKey (an array with shape (2,) and dtype uint32).
num: optional, a positive integer indicating the number of keys to produce
(default 2).
Returns:
An array with shape (num, 2) and dtype uint32 representing `num` new keys.
"""
return _split(key, num)
@partial(jit, static_argnums=(1,))
def _split(key, num):
counts = lax.tie_in(key, lax.iota(onp.uint32, num * 2))
return lax.reshape(threefry_2x32(key, counts), (num, 2))
def fold_in(key, data):
"""Folds in data to a PRNG key to form a new PRNG key.
Args:
key: a PRNGKey (an array with shape (2,) and dtype uint32).
data: a 32bit integer representing data to be folded in to the key.
Returns:
A new PRNGKey that is a deterministic function of the inputs and is
statistically safe for producing a stream of new pseudo-random values.
"""
return _fold_in(key, data)
@jit
def _fold_in(key, data):
key2 = lax.tie_in(key, PRNGKey(data))
return threefry_2x32(key, key2)
def _random_bits(key, bit_width, shape):
"""Sample uniform random bits of given width and shape using PRNG key."""
if not _is_prng_key(key):
raise TypeError("_random_bits got invalid prng key.")
if bit_width not in (32, 64):
raise TypeError("requires 32- or 64-bit field width.")
max_count = (bit_width // 32) * onp.prod(shape)
if max_count >= np.iinfo(onp.uint32).max:
# TODO(mattjj): just split the key here
raise TypeError("requesting more random bits than a single call provides.")
counts = lax.tie_in(key, lax.iota(onp.uint32, max_count))
bits = threefry_2x32(key, counts)
if bit_width == 64:
bits = [lax.convert_element_type(x, onp.uint64) for x in np.split(bits, 2)]
bits = lax.shift_left(bits[0], onp.uint64(32)) | bits[1]
return lax.reshape(bits, shape)
### random samplers
def _check_shape(name, shape, *param_shapes):
try:
shape = tuple(map(int, shape))
except TypeError:
msg = "{} requires a concrete tuple of integers as shape argument, got {}."
raise ValueError(msg.format(name, shape))
if param_shapes:
shape_ = lax.broadcast_shapes(shape, *param_shapes)
if shape != shape_:
msg = ("{} parameter shapes must be broadcast-compatible with shape "
"argument, and the result of broadcasting the shapes must equal "
"the shape argument, but got result {} for shape argument {}.")
raise ValueError(msg.format(name, shape_, shape))
def uniform(key, shape=(), dtype=onp.float64, minval=0., maxval=1.):
"""Sample uniform random values in [minval, maxval) with given shape/dtype.
Args:
key: a PRNGKey used as the random key.
shape: optional, a tuple of nonnegative integers representing the result
shape. Default ().
dtype: optional, a float dtype for the returned values (default float64 if
jax_enable_x64 is true, otherwise float32).
minval: optional, a minimum (inclusive) value for the range (default 0).
maxval: optional, a maximum (exclusive) value for the range (default 1).
Returns:
A random array with the specified shape and dtype.
"""
dtype = dtypes.canonicalize_dtype(dtype)
return _uniform(key, shape, dtype, minval, maxval)
@partial(jit, static_argnums=(1, 2))
def _uniform(key, shape, dtype, minval, maxval):
_check_shape("uniform", shape)
if not np.issubdtype(dtype, onp.floating):
raise TypeError("uniform only accepts floating point dtypes.")
minval = lax.convert_element_type(minval, dtype)
maxval = lax.convert_element_type(maxval, dtype)
finfo = np.finfo(dtype)
nbits, nmant = finfo.bits, finfo.nmant
if nbits not in (32, 64):
raise TypeError("uniform only accepts 32- or 64-bit dtypes.")
bits = _random_bits(key, nbits, shape)
# The strategy here is to randomize only the mantissa bits with an exponent of
# 1 (after applying the bias), then shift and scale to the desired range. The
# bit-level transformation we use relies on Numpy and XLA having bit-for-bit
# equivalent float representations, which might not be true on all platforms.
float_bits = lax.bitwise_or(
lax.shift_right_logical(bits, onp.array(nbits - nmant, lax.dtype(bits))),
onp.array(1., dtype).view(onp.uint32 if nbits == 32 else onp.uint64))
floats = lax.bitcast_convert_type(float_bits, dtype) - onp.array(1., dtype)
return lax.max(
minval,
lax.reshape(floats * (maxval - minval) + minval, shape))
def randint(key, shape, minval, maxval, dtype=onp.int64):
"""Sample uniform random values in [minval, maxval) with given shape/dtype.
Args:
key: a PRNGKey used as the random key.
shape: a tuple of nonnegative integers representing the shape.
minval: int or array of ints broadcast-compatible with ``shape``, a minimum
(inclusive) value for the range.
maxval: int or array of ints broadcast-compatible with ``shape``, a maximum
(exclusive) value for the range.
dtype: optional, an int dtype for the returned values (default int64 if
jax_enable_x64 is true, otherwise int32).
Returns:
A random array with the specified shape and dtype.
"""
dtype = dtypes.canonicalize_dtype(dtype)
return _randint(key, shape, minval, maxval, dtype)
@partial(jit, static_argnums=(1, 4))
def _randint(key, shape, minval, maxval, dtype):
_check_shape("randint", shape, onp.shape(minval), onp.shape(maxval))
if not np.issubdtype(dtype, onp.integer):
raise TypeError("randint only accepts integer dtypes.")
minval = lax.convert_element_type(minval, dtype)
maxval = lax.convert_element_type(maxval, dtype)
nbits = np.iinfo(dtype).bits
if nbits not in (32, 64):
raise TypeError("randint only accepts 32- or 64-bit dtypes.")
# if we don't have minval < maxval, just always return minval
# https://github.com/google/jax/issues/222
maxval = lax.max(lax.add(minval, onp.array(1, dtype)), maxval)
# This algorithm is biased whenever (maxval - minval) is not a power of 2.
# We generate double the number of random bits required by the dtype so as to
# reduce that bias.
k1, k2 = split(key)
rbits = lambda key: _random_bits(key, nbits, shape)
higher_bits, lower_bits = rbits(k1), rbits(k2)
unsigned_dtype = onp.uint32 if nbits == 32 else onp.uint64
span = lax.convert_element_type(maxval - minval, unsigned_dtype)
# To compute a remainder operation on an integer that might have twice as many
# bits as we can represent in the native unsigned dtype, we compute a
# multiplier equal to 2**nbits % span (using that nbits is 32 or 64).
multiplier = lax.rem(onp.array(2**16, unsigned_dtype), span)
multiplier = lax.rem(lax.mul(multiplier, multiplier), span)
if nbits == 64:
multiplier = lax.rem(lax.mul(multiplier, multiplier), span)
random_offset = lax.add(lax.mul(lax.rem(higher_bits, span), multiplier),
lax.rem(lower_bits, span))
random_offset = lax.rem(random_offset, span)
return lax.add(minval, lax.convert_element_type(random_offset, dtype))
def shuffle(key, x, axis=0):
"""Shuffle the elements of an array uniformly at random along an axis.
Args:
key: a PRNGKey used as the random key.
x: the array to be shuffled.
axis: optional, an int axis along which to shuffle (default 0).
Returns:
A shuffled version of x.
"""
return _shuffle(key, x, axis)
@partial(jit, static_argnums=(2,))
def _shuffle(key, x, axis):
# On parallel architectures, Fisher-Yates is more expensive than doing
# multiple sorts. This algorithm is based on one developed and analyzed by
# tjablin@. We sort according to randomly-generated 32bit keys, but those keys
# may have collisions. If we repeat the process, using fresh 32bit keys for
# each sort, then whenever all pairs of elements have been assigned distinct
# keys at some iteration (or equivalently when the strings formed by
# concatenating the successive keys for each element are all distinct) then we
# are guaranteed to have a perfect sample (assuming that either the sort is
# stable or that any bias is not value-dependent). Since checking uniqueness
# at runtime may be expensive, we use a heuristic static stop criterion
# developed by tjablin@. See tensorflow/compiler/tf2xla/random_ops.cc for more
# info, and for the original implementation of this algorithm. See also
# Section 2 of http://people.csail.mit.edu/costis/6896sp11/lec5s.pdf for
# another analysis (where the keys are generated one bit at a time).
exponent = 3 # see tjablin@'s analysis for explanation of this parameter
uint32max = np.iinfo(onp.uint32).max
num_rounds = int(onp.ceil(exponent * onp.log(x.size) / onp.log(uint32max)))
for _ in range(num_rounds):
key, subkey = split(key)
sort_keys = _random_bits(subkey, 32, x.shape)
_, x = lax.sort_key_val(sort_keys, x, axis)
return x
def normal(key, shape=(), dtype=onp.float64):
"""Sample standard normal random values with given shape and float dtype.
Args:
key: a PRNGKey used as the random key.
shape: optional, a tuple of nonnegative integers representing the result
shape. Default ().
dtype: optional, a float dtype for the returned values (default float64 if
jax_enable_x64 is true, otherwise float32).
Returns:
A random array with the specified shape and dtype.
"""
dtype = dtypes.canonicalize_dtype(dtype)
return _normal(key, shape, dtype)
@partial(jit, static_argnums=(1, 2))
def _normal(key, shape, dtype):
_check_shape("normal", shape)
lo = onp.nextafter(onp.array(-1., dtype), 0., dtype=dtype)
hi = onp.array(1., dtype)
u = uniform(key, shape, dtype, lo, hi)
return onp.array(onp.sqrt(2), dtype) * lax.erf_inv(u)
def multivariate_normal(key, mean, cov, shape=None, dtype=onp.float64):
"""Sample multivariate normal random values with given mean and covariance.
Args:
key: a PRNGKey used as the random key.
mean: a mean vector of shape ``(..., n)``.
cov: a positive definite covariance matrix of shape ``(..., n, n)``. The
batch shape ``...`` must be broadcast-compatible with that of ``mean``.
shape: optional, a tuple of nonnegative integers specifying the result
batch shape; that is, the prefix of the result shape excluding the last
axis. Must be broadcast-compatible with ``mean.shape[:-1]`` and
``cov.shape[:-2]``. The default (None) produces a result batch shape by
broadcasting together the batch shapes of ``mean`` and ``cov``.
dtype: optional, a float dtype for the returned values (default float64 if
jax_enable_x64 is true, otherwise float32).
Returns:
A random array with the specified dtype and shape given by
``shape + mean.shape[-1:]`` if ``shape`` is not None, or else
``broadcast_shapes(mean.shape[:-1], cov.shape[:-2]) + mean.shape[-1:]``.
"""
dtype = dtypes.canonicalize_dtype(dtype)
return _multivariate_normal(key, mean, cov, shape, dtype)
@partial(jit, static_argnums=(3, 4))
def _multivariate_normal(key, mean, cov, shape, dtype):
if not onp.ndim(mean) >= 1:
msg = "multivariate_normal requires mean.ndim >= 1, got mean.ndim == {}"
raise ValueError(msg.format(onp.ndim(mean)))
if not onp.ndim(cov) >= 2:
msg = "multivariate_normal requires cov.ndim >= 2, got cov.ndim == {}"
raise ValueError(msg.format(onp.ndim(cov)))
n = mean.shape[-1]
if onp.shape(cov)[-2:] != (n, n):
msg = ("multivariate_normal requires cov.shape == (..., n, n) for n={n}, "
"but got cov.shape == {shape}.")
raise ValueError(msg.format(n=n, shape=onp.shape(cov)))
if shape is None:
shape = lax.broadcast_shapes(mean.shape[:-1], cov.shape[:-2])
else:
_check_shape("normal", shape, mean.shape[:-1], mean.shape[:-2])
chol_factor = cholesky(cov)
normal_samples = normal(key, shape + mean.shape[-1:], dtype)
return mean + np.tensordot(normal_samples, chol_factor, [-1, 1])
def truncated_normal(key, lower, upper, shape=None, dtype=onp.float64):
"""Sample truncated standard normal random values with given shape and dtype.
Args:
key: a PRNGKey used as the random key.
lower: a float or array of floats representing the lower bound for
truncation. Must be broadcast-compatible with ``upper``.
upper: a float or array of floats representing the upper bound for
truncation. Must be broadcast-compatible with ``lower``.
shape: optional, a tuple of nonnegative integers specifying the result
shape. Must be broadcast-compatible with ``lower`` and ``upper``. The
default (None) produces a result shape by broadcasting ``lower`` and
``upper``.
dtype: optional, a float dtype for the returned values (default float64 if
jax_enable_x64 is true, otherwise float32).
Returns:
A random array with the specified dtype and shape given by ``shape`` if
``shape`` is not None, or else by broadcasting ``lower`` and ``upper``.
"""
dtype = dtypes.canonicalize_dtype(dtype)
return _truncated_normal(key, lower, upper, shape, dtype)
@partial(jit, static_argnums=(3, 4))
def _truncated_normal(key, lower, upper, shape, dtype):
if shape is None:
shape = lax.broadcast_shapes(onp.shape(lower), onp.shape(upper))
else:
_check_shape("truncated_normal", shape, onp.shape(lower), onp.shape(upper))
sqrt2 = onp.array(onp.sqrt(2), dtype)
a = lax.erf(lax.convert_element_type(lower, dtype) / sqrt2)
b = lax.erf(lax.convert_element_type(upper, dtype) / sqrt2)
if not np.issubdtype(dtype, onp.floating):
raise TypeError("truncated_normal only accepts floating point dtypes.")
u = uniform(key, shape, dtype, minval=np.finfo(dtype).tiny)
return sqrt2 * lax.erf_inv(a + u * (b - a))
def bernoulli(key, p=onp.float32(0.5), shape=None):
"""Sample Bernoulli random values with given shape and mean.
Args:
key: a PRNGKey used as the random key.
p: optional, a float or array of floats for the mean of the random
variables. Must be broadcast-compatible with ``shape``. Default 0.5.
shape: optional, a tuple of nonnegative integers representing the result
shape. Must be broadcast-compatible with ``p.shape``. The default (None)
produces a result shape equal to ``p.shape``.
Returns:
A random array with boolean dtype and shape given by ``shape`` if ``shape``
is not None, or else ``p.shape``.
"""
dtype = dtypes.canonicalize_dtype(lax.dtype(p))
if not np.issubdtype(dtype, onp.floating):
msg = "bernoulli probability `p` must have a floating dtype, got {}."
raise TypeError(msg.format(dtype))
p = lax.convert_element_type(p, dtype)
return _bernoulli(key, p, shape)
@partial(jit, static_argnums=(2,))
def _bernoulli(key, p, shape):
if shape is None:
shape = onp.shape(p)
else:
_check_shape("bernoulli", shape, onp.shape(p))
return uniform(key, shape, lax.dtype(p)) < p
def beta(key, a, b, shape=None, dtype=onp.float64):
"""Sample Bernoulli random values with given shape and mean.
Args:
key: a PRNGKey used as the random key.
a: a float or array of floats broadcast-compatible with ``shape``
representing the first parameter "alpha".
b: a float or array of floats broadcast-compatible with ``shape``
representing the second parameter "beta".
shape: optional, a tuple of nonnegative integers specifying the result
shape. Must be broadcast-compatible with ``a`` and ``b``. The default
(None) produces a result shape by broadcasting ``a`` and ``b``.
dtype: optional, a float dtype for the returned values (default float64 if
jax_enable_x64 is true, otherwise float32).
Returns:
A random array with the specified dtype and shape given by ``shape`` if
``shape`` is not None, or else by broadcasting ``a`` and ``b``.
"""
dtype = dtypes.canonicalize_dtype(dtype)
return _beta(key, a, b, shape, dtype)
@partial(jit, static_argnums=(3, 4))
def _beta(key, a, b, shape, dtype):
if shape is None:
shape = lax.broadcast_shapes(onp.shape(a), onp.shape(b))
else:
_check_shape("beta", shape, onp.shape(a), onp.shape(b))
a = lax.convert_element_type(a, dtype)
b = lax.convert_element_type(b, dtype)
key_a, key_b = split(key)
gamma_a = gamma(key_a, a, shape, dtype)
gamma_b = gamma(key_b, b, shape, dtype)
return gamma_a / (gamma_a + gamma_b)
def cauchy(key, shape=(), dtype=onp.float64):
"""Sample Cauchy random values with given shape and float dtype.
Args:
key: a PRNGKey used as the random key.
shape: optional, a tuple of nonnegative integers representing the result
shape. Default ().
dtype: optional, a float dtype for the returned values (default float64 if
jax_enable_x64 is true, otherwise float32).
Returns:
A random array with the specified shape and dtype.
"""
dtype = dtypes.canonicalize_dtype(dtype)
return _cauchy(key, shape, dtype)
@partial(jit, static_argnums=(1, 2))
def _cauchy(key, shape, dtype):
_check_shape("cauchy", shape)
u = uniform(key, shape, dtype, minval=np.finfo(dtype).eps, maxval=1.)
pi = _constant_like(u, onp.pi)
return lax.tan(lax.mul(pi, lax.sub(u, _constant_like(u, 0.5))))
def dirichlet(key, alpha, shape=None, dtype=onp.float64):
"""Sample Cauchy random values with given shape and float dtype.
Args:
key: a PRNGKey used as the random key.
alpha: an array of shape ``(..., n)`` used as the concentration
parameter of the random variables.
shape: optional, a tuple of nonnegative integers specifying the result
batch shape; that is, the prefix of the result shape excluding the last
element of value ``n``. Must be broadcast-compatible with
``alpha.shape[:-1]``. The default (None) produces a result shape equal to
``alpha.shape``.
dtype: optional, a float dtype for the returned values (default float64 if
jax_enable_x64 is true, otherwise float32).
Returns:
A random array with the specified dtype and shape given by
``shape + (alpha.shape[-1],)`` if ``shape`` is not None, or else
``alpha.shape``.
"""
dtype = dtypes.canonicalize_dtype(dtype)
return _dirichlet(key, alpha, shape, dtype)
@partial(jit, static_argnums=(2, 3))
def _dirichlet(key, alpha, shape, dtype):
if not onp.ndim(alpha) >= 1:
msg = "dirichlet requires alpha.ndim >= 1, got alpha.ndim == {}"
raise ValueError(msg.format(onp.ndim(alpha)))
if shape is None:
shape = onp.shape(alpha)[:-1]
else:
_check_shape("dirichlet", shape, onp.shape(alpha)[:-1])
alpha = lax.convert_element_type(alpha, dtype)
gamma_samples = gamma(key, alpha, shape + onp.shape(alpha)[-1:], dtype)
return gamma_samples / np.sum(gamma_samples, axis=-1, keepdims=True)
def exponential(key, shape=(), dtype=onp.float64):
"""Sample Exponential random values with given shape and float dtype.
Args:
key: a PRNGKey used as the random key.
shape: optional, a tuple of nonnegative integers representing the result
shape. Default ().
dtype: optional, a float dtype for the returned values (default float64 if
jax_enable_x64 is true, otherwise float32).
Returns:
A random array with the specified shape and dtype.
"""
dtype = dtypes.canonicalize_dtype(dtype)
return _exponential(key, shape, dtype)
@partial(jit, static_argnums=(1, 2))
def _exponential(key, shape, dtype):
_check_shape("exponential", shape)
u = uniform(key, shape, dtype)
# taking 1 - u to move the domain of log to (0, 1] instead of [0, 1)
return lax.neg(lax.log1p(lax.neg(u)))
def _gamma_one(key, alpha):
# Ref: A simple method for generating gamma variables, George Marsaglia and Wai Wan Tsang
# The algorithm can also be founded in:
# https://en.wikipedia.org/wiki/Gamma_distribution#Generating_gamma-distributed_random_variables
zero = _constant_like(alpha, 0)
one = _constant_like(alpha, 1)
minus_one = _constant_like(alpha, -1)
one_over_two = _constant_like(alpha, 0.5)
one_over_three = _constant_like(alpha, 1. / 3.)
squeeze_const = _constant_like(alpha, 0.0331)
dtype = lax.dtype(alpha)
key, subkey = split(key)
# for alpha < 1, we boost alpha to alpha + 1 and get a sample according to
# Gamma(alpha) ~ Gamma(alpha+1) * Uniform()^(1 / alpha)
boost = lax.select(lax.ge(alpha, one),
one,
lax.pow(uniform(subkey, (), dtype=dtype), lax.div(one, alpha)))
alpha = lax.select(lax.ge(alpha, one), alpha, lax.add(alpha, one))
d = lax.sub(alpha, one_over_three)
c = lax.div(one_over_three, lax.pow(d, one_over_two))
def _cond_fn(kXVU):
_, X, V, U = kXVU
# TODO: use lax.cond when its batching rule is supported
# The reason is to avoid evaluating second condition which involves log+log
# if the first condition is satisfied
cond = lax.bitwise_and(lax.ge(U, lax.sub(one, lax.mul(squeeze_const, lax.mul(X, X)))),
lax.ge(lax.log(U), lax.add(lax.mul(X, one_over_two),
lax.mul(d, lax.add(lax.sub(one, V),
lax.log(V))))))
return cond
def _body_fn(kXVU):
def _next_kxv(kxv):
key = kxv[0]
key, subkey = split(key)
x = normal(subkey, (), dtype=dtype)
v = lax.add(one, lax.mul(x, c))
return key, x, v
key = kXVU[0]
key, x_key, U_key = split(key, 3)
_, x, v = lax.while_loop(lambda kxv: lax.le(kxv[2], zero), _next_kxv, (x_key, zero, minus_one))
X = lax.mul(x, x)
V = lax.mul(lax.mul(v, v), v)
U = uniform(U_key, (), dtype=dtype)
return key, X, V, U
# initial state is chosen such that _cond_fn will return True
_, _, V, _ = lax.while_loop(_cond_fn, _body_fn, (key, zero, one, _constant_like(alpha, 2)))
z = lax.mul(lax.mul(d, V), boost)
return lax.select(lax.eq(z, zero), np.finfo(z.dtype).tiny, z)
_bivariate_coef = [[0.16009398, -0.094634816, 0.025146379, -0.0030648348,
1, 0.3266811, 0.10406087, 0.0014179033],
[0.53487893, 0.12980707, 0.06573594, -0.0015649787,
0.16639465, 0.020070098, -0.0035938937, -0.00058392601],
[0.040121005, -0.0065914079, -0.002628604, -0.0013441777,
0.017050642, -0.0021309345, 0.00085092385, -1.5248239e-07]]
def _gamma_grad_one(z, alpha):
# Ref 1: Pathwise Derivatives Beyond the Reparameterization Trick, Martin & Fritz
# Ref 2: Case 4 follows https://github.com/fritzo/notebooks/blob/master/gamma-reparameterized.ipynb
# TODO: use lax.cond instead of lax.while_loop when its batching rule is available
# See https://github.com/google/jax/issues/490
def _case1(zagf):
z, alpha, _, flag = zagf
# dz = - dCDF(z; a) / pdf(z; a)
# pdf = z^(a-1) * e^(-z) / Gamma(a)
# CDF(z; a) = IncompleteGamma(a, z) / Gamma(a)
# dCDF(z; a) = (dIncompleteGamma - IncompleteGamma * Digamma(a)) / Gamma(a)
# =: unnormalized_dCDF / Gamma(a)
# IncompleteGamma ~ z^a [ 1/a - z/(a+1) + z^2/2!(a+2) - z^3/3!(a+3) + z^4/4!(a+4) - z^5/5!(a+5) ]
# =: z^a * term1
# dIncompleteGamma ~ z^a * log(z) * term1 - z^a [1/a^2 - z/(a+1)^2 + z^2/2!(a+2)^2
# - z^3/3!(a+3)^2 + z^4/4!(a+4)^2 - z^5/5!(a+5)^2 ]
# =: z^a * log(z) * term1 - z^a * term2
# unnormalized_dCDF = z^a { [log(z) - Digamma(a)] * term1 - term2 }
zi = 1.0
update = zi / alpha
term1 = update
term2 = update / alpha
for i in range(1, 6):
zi = -zi * z / i
update = zi / (alpha + i)
term1 = term1 + update
term2 = term2 + update / (alpha + i)
unnormalized_cdf_dot = np.power(z, alpha) * ((np.log(z) - lax.digamma(alpha)) * term1 - term2)
unnormalized_pdf = np.power(z, alpha - 1) * np.exp(-z)
grad = -unnormalized_cdf_dot / unnormalized_pdf
return z, alpha, grad, ~flag
def _cond2(zagf):
z, alpha, _, flag = zagf
return (~flag) & (alpha > 8.0) & ((z < 0.9 * alpha) | (z > 1.1 * alpha))
def _case2(zagf):
z, alpha, _, flag = zagf
# Formula 58 of [1]
sqrt_8a = np.sqrt(8 * alpha)
z_minus_a = z - alpha
log_z_div_a = np.log(z / alpha)
sign = np.where(z < alpha, 1.0, -1.0)
term1 = 4 * (z + alpha) / (sqrt_8a * z_minus_a * z_minus_a)
term2 = log_z_div_a * (sqrt_8a / z_minus_a + sign * np.power(z_minus_a - alpha * log_z_div_a, -1.5))
term3 = z * (1.0 + 1.0 / (12 * alpha) + 1.0 / (288 * alpha * alpha)) / sqrt_8a
grad = (term1 + term2) * term3
return z, alpha, grad, ~flag
def _cond3(zagf):
z, alpha, _, flag = zagf
return (~flag) & (alpha > 8.0) & (z >= 0.9 * alpha) & (z <= 1.1 * alpha)
def _case3(zagf):
z, alpha, _, flag = zagf
# Formula 59 of [1]
z_div_a = np.divide(z, alpha)
aa = alpha * alpha
term1 = 1440 * alpha + 6 * z_div_a * (53 - 120 * z) - 65 * z_div_a * z_div_a + 3600 * z + 107
term2 = 1244160 * alpha * aa
term3 = 1 + 24 * alpha + 288 * aa
grad = term1 * term3 / term2
return z, alpha, grad, ~flag
def _case4(zagf):
z, alpha, _, flag = zagf
# Ref [2]
u = np.log(z / alpha)
v = np.log(alpha)
c = []
for i in range(8):
c.append(_bivariate_coef[0][i] + u * (_bivariate_coef[1][i] + u * _bivariate_coef[2][i]))
p = c[0] + v * (c[1] + v * (c[2] + v * c[3]))
q = c[4] + v * (c[5] + v * (c[6] + v * c[7]))
grad = np.exp(p / np.maximum(q, 0.01))
return z, alpha, grad, ~flag
_, _, grad, flag = lax.while_loop(lambda zagf: (~zagf[3]) & (zagf[0] < 0.8),
_case1,
(z, alpha, lax._const(alpha, 0.0), False))
_, _, grad, flag = lax.while_loop(_cond2, _case2, (z, alpha, grad, flag))
_, _, grad, flag = lax.while_loop(_cond3, _case3, (z, alpha, grad, flag))
_, _, grad, flag = lax.while_loop(lambda zagf: ~zagf[3], _case4, (z, alpha, grad, flag))
return grad
def _gamma_grad(sample, a):
samples = np.reshape(sample, -1)
alphas = np.reshape(a, -1)
grads = vmap(_gamma_grad_one)(samples, alphas)
return grads.reshape(onp.shape(a))
@custom_transforms
def _gamma_impl(key, a):
alphas = np.reshape(a, -1)
keys = split(key, onp.size(alphas))
samples = vmap(_gamma_one)(keys, alphas)
return np.reshape(samples, onp.shape(a))
defjvp(_gamma_impl, None,
lambda tangent, ans, key, a, **kwargs: tangent * _gamma_grad(ans, a))
def gamma(key, a, shape=None, dtype=onp.float64):
"""Sample Gamma random values with given shape and float dtype.
Args:
key: a PRNGKey used as the random key.
a: a float or array of floats broadcast-compatible with ``shape``
representing the parameter of the distribution.
shape: optional, a tuple of nonnegative integers specifying the result
shape. Must be broadcast-compatible with ``a``. The default (None)
produces a result shape equal to ``a.shape``.
dtype: optional, a float dtype for the returned values (default float64 if
jax_enable_x64 is true, otherwise float32).
Returns:
A random array with the specified dtype and with shape given by ``shape`` if
``shape`` is not None, or else by ``a.shape``.
"""
dtype = dtypes.canonicalize_dtype(dtype)
return _gamma(key, a, shape, dtype)
@partial(jit, static_argnums=(2, 3))
def _gamma(key, a, shape, dtype):
if shape is None:
shape = onp.shape(a)
else:
_check_shape("gamma", shape, onp.shape(a))
a = lax.convert_element_type(a, dtype)
if onp.shape(a) != shape:
a = np.broadcast_to(a, shape)
return _gamma_impl(key, a)
def gumbel(key, shape=(), dtype=onp.float64):
"""Sample Gumbel random values with given shape and float dtype.
Args:
key: a PRNGKey used as the random key.
shape: optional, a tuple of nonnegative integers representing the result
shape. Default ().
dtype: optional, a float dtype for the returned values (default float64 if
jax_enable_x64 is true, otherwise float32).
Returns:
A random array with the specified shape and dtype.
"""
dtype = dtypes.canonicalize_dtype(dtype)
return _gumbel(key, shape, dtype)
@partial(jit, static_argnums=(1, 2))
def _gumbel(key, shape, dtype):
_check_shape("gumbel", shape)
return -np.log(-np.log(
uniform(key, shape, dtype, minval=np.finfo(dtype).eps, maxval=1.)))
def laplace(key, shape=(), dtype=onp.float64):
"""Sample Laplace random values with given shape and float dtype.
Args:
key: a PRNGKey used as the random key.
shape: optional, a tuple of nonnegative integers representing the result
shape. Default ().
dtype: optional, a float dtype for the returned values (default float64 if
jax_enable_x64 is true, otherwise float32).
Returns:
A random array with the specified shape and dtype.
"""
dtype = dtypes.canonicalize_dtype(dtype)
return _laplace(key, shape, dtype)
@partial(jit, static_argnums=(1, 2))
def _laplace(key, shape, dtype):
_check_shape("laplace", shape)
u = uniform(
key, shape, dtype, minval=-1. + np.finfo(dtype).epsneg, maxval=1.)
return lax.mul(lax.sign(u), lax.log1p(lax.neg(lax.abs(u))))
def logistic(key, shape=(), dtype=onp.float64):
"""Sample logistic random values with given shape and float dtype.
Args:
key: a PRNGKey used as the random key.
shape: optional, a tuple of nonnegative integers representing the result
shape. Default ().
dtype: optional, a float dtype for the returned values (default float64 if
jax_enable_x64 is true, otherwise float32).
Returns:
A random array with the specified shape and dtype.
"""
dtype = dtypes.canonicalize_dtype(dtype)
return _logistic(key, shape, dtype)
@partial(jit, static_argnums=(1, 2))
def _logistic(key, shape, dtype):
_check_shape("logistic", shape)
return logit(uniform(key, shape, dtype))
def pareto(key, b, shape=None, dtype=onp.float64):
"""Sample Pareto random values with given shape and float dtype.
Args:
key: a PRNGKey used as the random key.
a: a float or array of floats broadcast-compatible with ``shape``
representing the parameter of the distribution.
shape: optional, a tuple of nonnegative integers specifying the result
shape. Must be broadcast-compatible with ``b``. The default (None)
produces a result shape equal to ``b.shape``.
dtype: optional, a float dtype for the returned values (default float64 if
jax_enable_x64 is true, otherwise float32).
Returns:
A random array with the specified dtype and with shape given by ``shape`` if
``shape`` is not None, or else by ``b.shape``.
"""
dtype = dtypes.canonicalize_dtype(dtype)
return _pareto(key, b, shape, dtype)
@partial(jit, static_argnums=(2, 3))
def _pareto(key, b, shape, dtype):
if shape is None:
shape = onp.shape(b)
else:
_check_shape("pareto", shape)
b = lax.convert_element_type(b, dtype)
e = exponential(key, shape, dtype)
return lax.exp(e / b)
def t(key, df, shape=(), dtype=onp.float64):
"""Sample Student's t random values with given shape and float dtype.
Args:
key: a PRNGKey used as the random key.
df: a float or array of floats broadcast-compatible with ``shape``
representing the parameter of the distribution.
shape: optional, a tuple of nonnegative integers specifying the result
shape. Must be broadcast-compatible with ``df``. The default (None)
produces a result shape equal to ``df.shape``.
dtype: optional, a float dtype for the returned values (default float64 if
jax_enable_x64 is true, otherwise float32).
Returns:
A random array with the specified dtype and with shape given by ``shape`` if
``shape`` is not None, or else by ``df.shape``.
"""
dtype = dtypes.canonicalize_dtype(dtype)
return _t(key, df, shape, dtype)
@partial(jit, static_argnums=(2, 3))
def _t(key, df, shape, dtype):
if shape is None:
shape = onp.shape(df)
else:
_check_shape("t", shape, onp.shape(df))
df = lax.convert_element_type(df, dtype)
key_n, key_g = split(key)
n = normal(key_n, shape, dtype)
two = _constant_like(n, 2)
half_df = lax.div(df, two)
g = gamma(key_n, half_df, shape, dtype)
return n * np.sqrt(half_df / g)
|
jax-master
|
jax/random.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from six.moves import reduce
class PrettyPrint(object):
"""Crude Hughes-inspired pretty printer."""
def __init__(self, lines):
self.lines = lines
def indent(self, indent):
return PrettyPrint([(indent + orig_indent, s)
for orig_indent, s in self.lines])
def __add__(self, rhs):
return PrettyPrint(self.lines + rhs.lines)
def __rshift__(self, rhs):
if not rhs.lines:
return self
indent, s = self.lines[-1]
indented_block = rhs.indent(indent + len(s))
common_line = s + ' ' * rhs.lines[0][0] + rhs.lines[0][1]
return PrettyPrint(self.lines[:-1]
+ [(indent, common_line)]
+ indented_block.lines[1:])
def __str__(self):
return '\n'.join(' ' * indent + s for indent, s in self.lines) + '\n'
def pp(s):
return PrettyPrint([(0, line) for line in str(s).splitlines()])
def hcat(ps):
return reduce(lambda x, y: x >> y, ps)
def vcat(ps):
if not ps:
return pp('')
else:
return reduce(lambda x, y: x + y, ps)
def pp_kv_pairs(kv_pairs):
if kv_pairs:
kv_pairs = vcat([pp('{}='.format(k)) >> pp(v) for k, v in kv_pairs])
return pp('[ ') >> kv_pairs >> pp(' ]')
else:
return pp('')
def print_list(xs):
return ' '.join(map(str, xs))
|
jax-master
|
jax/pprint_util.py
|
# coding=utf-8
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
"""
JAX user-facing transformations and utilities.
The transformations here mostly wrap internal transformations, providing
convenience flags to control behavior and handling Python containers of
arguments and outputs. The Python containers handled are pytrees (see
tree_util.py), which include nested tuples/lists/dicts, where the leaves are
arrays.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import itertools as it
import operator as op
import os
import threading
from warnings import warn
import numpy as onp
from contextlib import contextmanager
from distutils.util import strtobool
import six
from six.moves import reduce
from . import core
from . import linear_util as lu
from . import ad_util
from . import dtypes
from .core import eval_jaxpr
from .api_util import (wraps, flatten_fun, apply_flat_fun, flatten_fun_nokwargs,
flatten_fun_nokwargs2)
from .tree_util import (tree_map, tree_flatten, tree_unflatten, tree_structure,
tree_transpose, tree_leaves, tree_multimap,
_replace_nones)
from .util import (unzip2, unzip3, curry, partial, safe_map, safe_zip,
WrapHashably, Hashable, prod, split_list)
from .lib import xla_bridge as xb
from .lib.xla_bridge import (device_count, local_device_count, devices, local_devices,
host_id, host_ids, host_count)
from .abstract_arrays import ConcreteArray, ShapedArray, raise_to_shaped
from .interpreters import partial_eval as pe
from .interpreters import xla
from .interpreters import pxla
from .interpreters import ad
from .interpreters import batching
from .interpreters import parallel
from .interpreters import masking
from .interpreters.masking import shapecheck
from .config import flags, config
map = safe_map
zip = safe_zip
FLAGS = flags.FLAGS
flags.DEFINE_bool("jax_disable_jit",
strtobool(os.getenv("JAX_DISABLE_JIT", "False")),
"Disable JIT compilation and just call original Python.")
def _check_callable(fun):
if not callable(fun):
raise TypeError("Expected a callable value, got {}".format(fun))
class _ThreadLocalState(threading.local):
def __init__(self):
self.jit_is_disabled = False
_thread_local_state = _ThreadLocalState()
def jit(fun, static_argnums=(), device=None, backend=None):
"""Sets up `fun` for just-in-time compilation with XLA.
Args:
fun: Function to be jitted. Should be a pure function, as side-effects may
only be executed once. Its arguments and return value should be arrays,
scalars, or (nested) standard Python containers (tuple/list/dict) thereof.
Positional arguments indicated by `static_argnums` can be anything at all,
provided they are hashable and have an equality operation defined. Static
arguments are included as part of a compilation cache key, which is why
hash and equality operators must be defined.
static_argnums: A tuple of ints specifying which positional arguments to
treat as static (compile-time constant). Operations that only depend on
static arguments will be constant-folded. Calling the jitted function with
different values for these constants will trigger recompilation. If the
jitted function is called with fewer positional arguments than indicated
by `static_argnums` then an error is raised. Defaults to ().
device: This is an experimental feature and the API is likely to change.
Optional, the Device the jitted function will run on. (Available devices
can be retrieved via ``jax.devices()``.) The default is inherited from
XLA's DeviceAssignment logic and is usually to use ``jax.devices()[0]``.
backend: This is an experimental feature and the API is likely to change.
Optional, a string representing the xla backend. 'cpu','gpu', or 'tpu'.
Returns:
A wrapped version of `fun`, set up for just-in-time compilation.
In the following example, `selu` can be compiled into a single fused kernel by
XLA:
>>> @jax.jit
>>> def selu(x, alpha=1.67, lmbda=1.05):
>>> return lmbda * jax.numpy.where(x > 0, x, alpha * jax.numpy.exp(x) - alpha)
>>>
>>> key = jax.random.PRNGKey(0)
>>> x = jax.random.normal(key, (10,))
>>> print(selu(x))
[-0.54485154 0.27744263 -0.29255125 -0.91421586 -0.62452525 -0.2474813
-0.8574326 -0.7823267 0.7682731 0.59566754]
"""
_check_callable(fun)
if isinstance(static_argnums, int):
static_argnums = (static_argnums,)
@wraps(fun)
def f_jitted(*args, **kwargs):
if _thread_local_state.jit_is_disabled or config.read('jax_disable_jit'):
return fun(*args, **kwargs)
if static_argnums and max(static_argnums) >= len(args):
msg = ("Jitted function has static_argnums={} but was called with only {}"
" positional arguments.")
raise TypeError(msg.format(static_argnums, len(args)))
f = lu.wrap_init(fun)
if static_argnums:
dyn_argnums = [i for i in range(len(args)) if i not in static_argnums]
f, dyn_args = _argnums_partial(f, dyn_argnums, args)
else:
dyn_args = args
args_flat, in_tree = tree_flatten((dyn_args, kwargs))
_check_args(args_flat)
flat_fun, out_tree = flatten_fun(f, in_tree)
out = xla.xla_call(flat_fun, *args_flat, device=device, backend=backend)
return tree_unflatten(out_tree(), out)
jitted_name = "jit({}, static_argnums={})"
f_jitted.__name__ = jitted_name.format(f_jitted.__name__, static_argnums)
return f_jitted
@contextmanager
def disable_jit():
"""Context manager that disables `jit` behavior under its dynamic context.
For debugging purposes, it is useful to have a mechanism that disables `jit`
everywhere in a dynamic context.
Values that have a data dependence on the arguments to a jitted function are
traced and abstracted. For example, an abstract value may be a ShapedArray
instance, representing the set of all possible arrays with a given shape and
dtype, but not representing one concrete array with specific values. You might
notice those if you use a benign side-effecting operation in a jitted
function, like a print:
>>> @jax.jit
>>> def f(x):
... y = x * 2
... print("Value of y is", y)
... return y + 3
...
>>> print(f(jax.numpy.array([1, 2, 3])))
Value of y is Traced<ShapedArray(int32[3]):JaxprTrace(level=-1/1)>
[5 7 9]
Here `y` has been abstracted by `jit` to a `ShapedArray`, which represents an
array with a fixed shape and type but an arbitrary value. It's also traced. If
we want to see a concrete value while debugging, and avoid the tracer too, we
can use the `disable_jit` context manager:
>>> with jax.disable_jit():
>>> print(f(np.array([1, 2, 3])))
>>>
Value of y is [2 4 6]
[5 7 9]
"""
try:
prev_val = _thread_local_state.jit_is_disabled
_thread_local_state.jit_is_disabled = True
yield
finally:
_thread_local_state.jit_is_disabled = prev_val
def xla_computation(fun, static_argnums=(), axis_env=None, backend=None,
tuple_args=False, instantiate_const_outputs=True):
"""Creates a function that produces its XLA computation given example args.
Args:
fun: Function from which to form XLA computations.
static_argnums: See the ``jax.jit`` docstring.
axis_env: Optional, a list of pairs where the first element is an axis name
and the second element is a positive integer representing the size of the
mapped axis with that name. This parameter is useful when lowering
functions that involve parallel communication collectives, and it
specifies the axis name/size environment that would be set up by
applications of ``jax.pmap``. See the examples below.
backend: This is an experimental feature and the API is likely to change.
Optional, a string representing the xla backend. 'cpu','gpu', or 'tpu'.
tuple_args: Optional bool, defaults to False. If True, the resulting XLA
computation will have a single tuple argument that is unpacked into the
specified function arguments.
instantiate_const_outputs: Optional bool, defaults to True. If False, then
``xla_computation`` does not instantiate constant-valued outputs in the
XLA computation, and so the result is closer to the computation that
``jax.jit`` produces and may be more useful for studying ``jit`` behavior.
If True, then constant-valued outputs are instantiated in the XLA
computation, which may be more useful for staging computations out of JAX
entirely.
Returns:
A wrapped version of ``fun`` that when applied to example arguments returns a
built XLA Computation (see xla_client.py), from which representations of the
unoptimized XLA HLO computation can be extracted using methods like
``GetHloText``, ``GetSerializedProto``, and ``GetHloDotGraph``.
For example:
>>> def f(x): return jax.numpy.sin(jax.numpy.cos(x))
>>> c = jax.xla_computation(f)(3.)
>>> print(c.GetHloText())
HloModule jaxpr_computation__4.5
ENTRY jaxpr_computation__4.5 {
tuple.1 = () tuple()
parameter.2 = f32[] parameter(0)
cosine.3 = f32[] cosine(parameter.2)
ROOT sine.4 = f32[] sine(cosine.3)
}
Here's an example that involves a parallel collective and axis name:
>>> def f(x): return x - jax.lax.psum(x, 'i')
>>> c = jax.xla_computation(f, axis_env=[('i', 4)])(2)
>>> print(c.GetHloText())
HloModule jaxpr_computation.9
primitive_computation.3 {
parameter.4 = s32[] parameter(0)
parameter.5 = s32[] parameter(1)
ROOT add.6 = s32[] add(parameter.4, parameter.5)
}
ENTRY jaxpr_computation.9 {
tuple.1 = () tuple()
parameter.2 = s32[] parameter(0)
all-reduce.7 = s32[] all-reduce(parameter.2), replica_groups={{0,1,2,3}}, to_apply=primitive_computation.3
ROOT subtract.8 = s32[] subtract(parameter.2, all-reduce.7)
}
Notice the ``replica_groups`` that were generated. Here's an example that
generates more interesting ``replica_groups``:
>>> def g(x):
... rowsum = lax.psum(x, 'i')
... colsum = lax.psum(x, 'j')
... allsum = lax.psum(x, ('i', 'j'))
... return rowsum, colsum, allsum
...
>>> axis_env = [('i', 4), ('j', 2)]
>>> c = xla_computation(g, axis_env=axis_env)(5.)
>>> print(c.GetHloText())
HloModule jaxpr_computation__1.19
[removed uninteresting text here]
ENTRY jaxpr_computation__1.19 {
tuple.1 = () tuple()
parameter.2 = f32[] parameter(0)
all-reduce.7 = f32[] all-reduce(parameter.2), replica_groups={{0,2,4,6},{1,3,5,7}}, to_apply=primitive_computation__1.3
all-reduce.12 = f32[] all-reduce(parameter.2), replica_groups={{0,1},{2,3},{4,5},{6,7}}, to_apply=primitive_computation__1.8
all-reduce.17 = f32[] all-reduce(parameter.2), replica_groups={{0,1,2,3,4,5,6,7}}, to_apply=primitive_computation__1.13
ROOT tuple.18 = (f32[], f32[], f32[]) tuple(all-reduce.7, all-reduce.12, all-reduce.17)
}
"""
_check_callable(fun)
fun_name = getattr(fun, '__name__', 'unknown')
def make_axis_env(nreps):
if axis_env is None:
return xla.AxisEnv(nreps)
else:
nreps = nreps * prod(size for name, size in axis_env)
names, sizes = zip(*axis_env)
return xla.AxisEnv(nreps, names, sizes)
@wraps(fun)
def computation_maker(*args, **kwargs):
wrapped = lu.wrap_init(fun)
jax_args, in_tree = tree_flatten((args, kwargs))
jaxtree_fun, out_tree = flatten_fun(wrapped, in_tree)
avals = map(xla.abstractify, jax_args)
pvals = [pe.PartialVal((aval, core.unit)) for aval in avals]
jaxpr, _, consts = pe.trace_to_jaxpr(jaxtree_fun, pvals,
instantiate=instantiate_const_outputs)
axis_env_ = make_axis_env(xla.jaxpr_replicas(jaxpr))
c = xb.make_computation_builder('xla_computation_{}'.format(fun_name))
xla_consts = map(c.Constant, consts)
xla_args = xla._xla_callable_args(c, avals, tuple_args)
outs = xla.jaxpr_subcomp(c, jaxpr, backend, axis_env_, xla_consts, (),
*xla_args)
return c.Build(c.Tuple(*outs))
return computation_maker
def grad(fun, argnums=0, has_aux=False, holomorphic=False):
"""Creates a function which evaluates the gradient of `fun`.
Args:
fun: Function to be differentiated. Its arguments at positions specified by
`argnums` should be arrays, scalars, or standard Python containers. It
should return a scalar (which includes arrays with shape `()` but not
arrays with shape `(1,)` etc.)
argnums: Optional, integer or tuple of integers. Specifies which positional
argument(s) to differentiate with respect to (default 0).
has_aux: Optional, bool. Indicates whether `fun` returns a pair where the
first element is considered the output of the mathematical function to be
differentiated and the second element is auxiliary data. Default False.
holomorphic: Optional, bool. Indicates whether `fun` is promised to be
holomorphic. Default False.
Returns:
A function with the same arguments as `fun`, that evaluates the gradient of
`fun`. If `argnums` is an integer then the gradient has the same shape and
type as the positional argument indicated by that integer. If argnums is a
tuple of integers, the gradient is a tuple of values with the same shapes
and types as the corresponding arguments. If `has_aux` is True then a pair
of (gradient, auxiliary_data) is returned.
For example:
>>> grad_tanh = jax.grad(jax.numpy.tanh)
>>> print(grad_tanh(0.2))
0.961043
"""
value_and_grad_f = value_and_grad(fun, argnums, has_aux=has_aux,
holomorphic=holomorphic)
docstr = ("Gradient of {fun} with respect to positional argument(s) "
"{argnums}. Takes the same arguments as {fun} but returns the "
"gradient, which has the same shape as the arguments at "
"positions {argnums}.")
@wraps(fun, docstr=docstr, argnums=argnums)
def grad_f(*args, **kwargs):
_, g = value_and_grad_f(*args, **kwargs)
return g
@wraps(fun, docstr=docstr, argnums=argnums)
def grad_f_aux(*args, **kwargs):
(_, aux), g = value_and_grad_f(*args, **kwargs)
return g, aux
return grad_f_aux if has_aux else grad_f
def value_and_grad(fun, argnums=0, has_aux=False, holomorphic=False):
"""Creates a function which evaluates both `fun` and the gradient of `fun`.
Args:
fun: Function to be differentiated. Its arguments at positions specified by
`argnums` should be arrays, scalars, or standard Python containers. It
should return a scalar (which includes arrays with shape `()` but not
arrays with shape `(1,)` etc.)
argnums: Optional, integer or tuple of integers. Specifies which positional
argument(s) to differentiate with respect to (default 0).
has_aux: Optional, bool. Indicates whether `fun` returns a pair where the
first element is considered the output of the mathematical function to be
differentiated and the second element is auxiliary data. Default False.
holomorphic: Optional, bool. Indicates whether `fun` is promised to be
holomorphic. Default False.
Returns:
A function with the same arguments as `fun` that evaluates both `fun` and
the gradient of `fun` and returns them as a pair (a two-element tuple). If
`argnums` is an integer then the gradient has the same shape and type as the
positional argument indicated by that integer. If argnums is a tuple of
integers, the gradient is a tuple of values with the same shapes and types
as the corresponding arguments.
"""
docstr = ("Value and gradient of {fun} with respect to positional "
"argument(s) {argnums}. Takes the same arguments as {fun} but "
"returns a two-element tuple where the first element is the value "
"of {fun} and the second element is the gradient, which has the "
"same shape as the arguments at positions {argnums}.")
_check_callable(fun)
@wraps(fun, docstr=docstr, argnums=argnums)
def value_and_grad_f(*args, **kwargs):
max_argnum = argnums if type(argnums) is int else max(argnums)
if max_argnum >= len(args):
msg = ("differentiating with respect to argnums={} requires at least "
"{} positional arguments to be passed by the caller, but got only "
"{} positional arguments.")
raise TypeError(msg.format(argnums, max_argnum + 1, len(args)))
f = lu.wrap_init(fun, kwargs)
f_partial, dyn_args = _argnums_partial(f, argnums, args)
if not has_aux:
ans, vjp_py = vjp(f_partial, *dyn_args)
else:
ans, vjp_py, aux = vjp(f_partial, *dyn_args, has_aux=True)
_check_scalar(ans)
dtype = dtypes.result_type(ans)
if not (holomorphic or dtypes.issubdtype(dtype, onp.floating)):
msg = ("Gradient only defined for real-output functions (with dtype that "
"is a subdtype of np.floating), but got dtype {}. For holomorphic "
"differentiation, pass holomorphic=True.")
raise TypeError(msg.format(dtype))
g = vjp_py(onp.ones((), dtype=dtype))
g = g[0] if isinstance(argnums, int) else g
if not has_aux:
return ans, g
else:
return (ans, aux), g
return value_and_grad_f
def _check_scalar(x):
msg = "Gradient only defined for scalar-output functions. Output {}.".format
try:
aval = core.get_aval(x)
except TypeError:
raise TypeError(msg("was {}".format(x)))
else:
if isinstance(aval, ShapedArray):
if aval.shape != ():
raise TypeError(msg("had shape: {}".format(aval.shape)))
else:
raise TypeError(msg("had abstract value {}".format(aval)))
def jacfwd(fun, argnums=0, holomorphic=False):
"""Jacobian of `fun` evaluated column-by-column using forward-mode AD.
Args:
fun: Function whose Jacobian is to be computed.
argnums: Optional, integer or tuple of integers. Specifies which positional
argument(s) to differentiate with respect to (default `0`).
holomorphic: Optional, bool. Indicates whether `fun` is promised to be
holomorphic. Default False.
Returns:
A function with the same arguments as `fun`, that evaluates the Jacobian of
`fun` using forward-mode automatic differentiation.
>>> def f(x):
... return jax.numpy.asarray(
... [x[0], 5*x[2], 4*x[1]**2 - 2*x[2], x[2] * jax.numpy.sin(x[0])])
...
>>> print(jax.jacfwd(f)(np.array([1., 2., 3.])))
[[ 1. , 0. , 0. ],
[ 0. , 0. , 5. ],
[ 0. , 16. , -2. ],
[ 1.6209068 , 0. , 0.84147096]]
"""
def jacfun(*args, **kwargs):
f = lu.wrap_init(fun, kwargs)
f_partial, dyn_args = _argnums_partial(f, argnums, args)
holomorphic or tree_map(_check_real_input_jacfwd, dyn_args)
pushfwd = partial(jvp, f_partial, dyn_args)
y, jac = vmap(pushfwd, out_axes=(None, batching.last))(_std_basis(dyn_args))
example_args = dyn_args[0] if isinstance(argnums, int) else dyn_args
return tree_map(partial(_unravel_array_into_pytree, example_args, -1), jac)
return jacfun
def _check_real_input_jacfwd(x):
aval = core.get_aval(x)
if not dtypes.issubdtype(aval.dtype, onp.floating):
msg = ("jacfwd only defined for functions with input dtypes that are "
"sub-dtypes of `np.floating` (i.e. that model real values), but got "
"{}. For holomorphic differentiation, pass holomorphic=True.")
raise TypeError(msg.format(aval.dtype.name))
def jacrev(fun, argnums=0, holomorphic=False):
"""Jacobian of `fun` evaluated row-by-row using reverse-mode AD.
Args:
fun: Function whose Jacobian is to be computed.
argnums: Optional, integer or tuple of integers. Specifies which positional
argument(s) to differentiate with respect to (default `0`).
holomorphic: Optional, bool. Indicates whether `fun` is promised to be
holomorphic. Default False.
Returns:
A function with the same arguments as `fun`, that evaluates the Jacobian of
`fun` using reverse-mode automatic differentiation.
>>> def f(x):
... return jax.numpy.asarray(
... [x[0], 5*x[2], 4*x[1]**2 - 2*x[2], x[2] * jax.numpy.sin(x[0])])
...
>>> print(jax.jacrev(f)(np.array([1., 2., 3.])))
[[ 1. , 0. , 0. ],
[ 0. , 0. , 5. ],
[ 0. , 16. , -2. ],
[ 1.6209068 , 0. , 0.84147096]]
"""
def jacfun(*args, **kwargs):
f = lu.wrap_init(fun, kwargs)
f_partial, dyn_args = _argnums_partial(f, argnums, args)
y, pullback = vjp(f_partial, *dyn_args)
holomorphic or tree_map(_check_real_output_jacrev, y)
jac = vmap(pullback)(_std_basis(y))
jac = jac[0] if isinstance(argnums, int) else jac
example_args = dyn_args[0] if isinstance(argnums, int) else dyn_args
jac = tree_map(partial(_unravel_array_into_pytree, y, 0), jac)
return tree_transpose(tree_structure(example_args), tree_structure(y), jac)
return jacfun
jacobian = jacrev
def _check_real_output_jacrev(x):
aval = core.get_aval(x)
if not dtypes.issubdtype(aval.dtype, onp.floating):
msg = ("jacrev only defined for functions with output dtypes that are "
"sub-dtypes of `np.floating` (i.e. that model real values), but got "
"{}. For holomorphic differentiation, pass holomorphic=True.")
raise TypeError(msg.format(aval.dtype.name))
def hessian(fun, argnums=0, holomorphic=False):
"""Hessian of `fun`.
Args:
fun: Function whose Hessian is to be computed.
argnums: Optional, integer or tuple of integers. Specifies which positional
argument(s) to differentiate with respect to (default `0`).
holomorphic: Optional, bool. Indicates whether `fun` is promised to be
holomorphic. Default False.
Returns:
A function with the same arguments as `fun`, that evaluates the Hessian of
`fun`.
>>> g = lambda(x): x[0]**3 - 2*x[0]*x[1] - x[1]**6
>>> print(jax.hessian(g)(jax.numpy.array([1., 2.])))
[[ 6., -2.],
[ -2., -480.]]
"""
return jacfwd(jacrev(fun, argnums, holomorphic), argnums, holomorphic)
def _std_basis(pytree):
leaves, _ = tree_flatten(pytree)
ndim = sum(map(onp.size, leaves))
# TODO(mattjj): use a symbolic identity matrix here
dtype = dtypes.result_type(*leaves)
flat_basis = onp.eye(ndim, dtype=dtype)
return _unravel_array_into_pytree(pytree, 1, flat_basis)
def _unravel_array_into_pytree(pytree, axis, arr):
leaves, treedef = tree_flatten(pytree)
axis = axis % arr.ndim
shapes = [arr.shape[:axis] + onp.shape(l) + arr.shape[axis+1:] for l in leaves]
parts = _split(arr, onp.cumsum(map(onp.size, leaves[:-1])), axis)
reshaped_parts = [onp.reshape(x, shape) for x, shape in zip(parts, shapes)]
return tree_unflatten(treedef, reshaped_parts)
def _split(x, indices, axis):
if isinstance(x, onp.ndarray):
return onp.split(x, indices, axis)
else:
return x.split(indices, axis)
def _dtype(x):
return dtypes.canonicalize_dtype(dtypes.result_type(x))
def vmap(fun, in_axes=0, out_axes=0):
"""Vectorizing map. Creates a function which maps `fun` over argument axes.
Args:
fun: Function to be mapped over additional axes.
in_axes: A nonnegative integer, None, or (nested) standard Python container
(tuple/list/dict) thereof specifying which input array axes to map over.
If each positional argument to ``fun`` is an array, then ``in_axes`` can
be a nonnegative integer, a None, or a tuple of integers and Nones with
length equal to the number of positional arguments to ``fun``. An integer
or None indicates which array axis to map over for all arguments (with
None indicating not to map any axis), and a tuple indicates which axis to
map for each corresponding positional argument. If the positional
arguments to ``fun`` are container types, the corresponding element of
``in_axes`` can itself be a matching container, so that distinct array
axes can be mapped for different container elements. ``in_axes`` must be a
container tree prefix of the positional argument tuple passed to ``fun``.
out_axes: A nonnegative integer, None, or (nested) standard Python container
(tuple/list/dict) thereof indicating where the mapped axis should appear
in the output.
Returns:
Batched/vectorized version of ``fun`` with arguments that correspond to
those of ``fun``, but with extra array axes at positions indicated by
``in_axes``, and a return value that corresponds to that of ``fun``, but
with extra array axes at positions indicated by ``out_axes``.
For example, we can implement a matrix-matrix product using a vector dot
product:
>>> vv = lambda x, y: np.vdot(x, y) # ([a], [a]) -> []
>>> mv = vmap(vv, (0, None), 0) # ([b,a], [a]) -> [b] (b is the mapped axis)
>>> mm = vmap(mv, (None, 1), 1) # ([b,a], [a,c]) -> [b,c] (c is the mapped axis)
Here we use ``[a,b]`` to indicate an array with shape (a,b). Here are some
variants:
>>> mv1 = vmap(vv, (0, 0), 0) # ([b,a], [b,a]) -> [b] (b is the mapped axis)
>>> mv2 = vmap(vv, (0, 1), 0) # ([b,a], [a,b]) -> [b] (b is the mapped axis)
>>> mm2 = vmap(mv2, (1, 1), 0) # ([b,c,a], [a,c,b]) -> [c,b] (c is the mapped axis)
Here's an example of using container types in ``in_axes`` to specify which
axes of the container elements to map over:
>>> A, B, C, D = 2, 3, 4, 5
>>> x = np.ones((A, B))
>>> y = np.ones((B, C))
>>> z = np.ones((C, D))
>>> def foo(tree_arg):
... x, (y, z) = tree_arg
... return np.dot(x, np.dot(y, z))
>>> tree = (x, (y, z))
>>> print(foo(tree))
[[12. 12. 12. 12. 12.]
[12. 12. 12. 12. 12.]]
>>> from jax import vmap
>>> K = 6 # batch size
>>> x = np.ones((K, A, B)) # batch axis in different locations
>>> y = np.ones((B, K, C))
>>> z = np.ones((C, D, K))
>>> tree = (x, (y, z))
>>> vfoo = vmap(foo, in_axes=((0, (1, 2)),))
>>> print(vfoo(tree)).shape
(6, 2, 5)
"""
docstr = ("Vectorized version of {fun}. Takes similar arguments as {fun} "
"but with additional array axes over which {fun} is mapped.")
_check_callable(fun)
if (not isinstance(in_axes, (list, tuple, type(None), int))
or not isinstance(out_axes, (list, tuple, type(None), int))):
msg = ("vmap arguments in_axes and out_axes must each be an integer, None, "
"or a (nested) tuple of those types, got {} and {} respectively.")
raise TypeError(msg.format(type(in_axes), type(out_axes)))
def _check_axis_sizes(tree, vals, dims):
mapped_axis_sizes = {x.shape[d] for x, d in zip(vals, dims) if d is not None}
try:
sizes, = mapped_axis_sizes
except ValueError:
msg = "vmap got inconsistent sizes for array axes to be mapped:\n{}"
# we switch the error message based on whether args is a tuple of arrays,
# in which case we can produce an error message based on argument indices,
# or if it has nested containers.
# TODO(mattjj,phawkins): add a way to inspect pytree kind more directly
if tree == tree_flatten((core.unit,) * tree.num_leaves)[1]:
lines1 = ["arg {} has shape {} and axis {} is to be mapped"
.format(i, x.shape, d) for i, (x, d) in enumerate(zip(vals, dims))]
sizes = collections.defaultdict(list)
for i, (x, d) in enumerate(zip(vals, dims)):
if d is not None:
sizes[x.shape[d]].append(i)
lines2 = ["{} {} {} {} to be mapped of size {}".format(
"args" if len(idxs) > 1 else "arg",
", ".join(map(str, idxs)),
"have" if len(idxs) > 1 else "has",
"axes" if len(idxs) > 1 else "an axis",
size)
for size, idxs in sizes.items()]
raise ValueError(msg.format("\n".join(lines1 + ["so"] + lines2)))
else:
sizes = [x.shape[d] if d is not None else None for x, d in zip(vals, dims)]
sizes = tree_unflatten(tree, sizes)
raise ValueError(msg.format("the tree of axis sizes is:\n{}".format(sizes)))
@wraps(fun, docstr=docstr)
def batched_fun(*args):
args_flat, in_tree = tree_flatten(args)
f = lu.wrap_init(fun)
flat_fun, out_tree = flatten_fun_nokwargs(f, in_tree)
in_axes_flat = _flatten_axes(in_tree, in_axes)
_check_axis_sizes(in_tree, args_flat, in_axes_flat)
out_flat = batching.batch(flat_fun, args_flat, in_axes_flat,
lambda: _flatten_axes(out_tree(), out_axes))
return tree_unflatten(out_tree(), out_flat)
return batched_fun
def _flatten_axes(treedef, axis_tree):
# given an axis spec tree axis_tree (a pytree with integers and Nones at the
# leaves, i.e. the Nones are to be considered leaves) that is a tree prefix of
# the given treedef, build a complete axis spec tree with the same structure
# and return the flattened result
# TODO(mattjj,phawkins): improve this implementation
proxy = object()
dummy = tree_unflatten(treedef, [object()] * treedef.num_leaves)
axes = []
add_leaves = lambda i, x: axes.extend([i] * len(tree_flatten(x)[0]))
try:
tree_multimap(add_leaves, _replace_nones(proxy, axis_tree), dummy)
except ValueError:
msg = ("axes specification must be a tree prefix of the corresponding "
"value, got specification {} for value {}.")
raise ValueError(msg.format(axis_tree, treedef))
axes = [None if a is proxy else a for a in axes]
assert len(axes) == treedef.num_leaves
return axes
def pmap(fun, axis_name=None, devices=None, backend=None):
"""Parallel map with support for collectives.
The purpose of ``pmap`` is to express single-program multiple-data (SPMD)
programs and execute them in parallel on XLA devices, such as multiple GPUs or
multiple TPU cores. Semantically it is comparable to ``vmap`` because both
transformations map a function over array axes, but where ``vmap`` vectorizes
functions by pushing the mapped axis down into primitive operations, ``pmap``
instead replicates the function and executes each replica on its own XLA
device in parallel.
Another key difference with ``vmap`` is that while ``vmap`` can only express
pure maps, ``pmap`` enables the use of parallel SPMD collective operations,
like all-reduce sum.
The mapped axis size must be less than or equal to the number of local XLA
devices available, as returned by ``jax.local_device_count()`` (unless
``devices`` is specified, see below). For nested ``pmap`` calls, the product
of the mapped axis sizes must be less than or equal to the number of XLA
devices.
**Multi-host platforms:** On multi-host platforms such as TPU pods, ``pmap``
is designed to be used in SPMD Python programs, where every host is running
the same Python code such that all hosts run the same pmapped function in the
same order. Each host should still call the pmapped function with mapped axis
size equal to the number of *local* devices (unless ``devices`` is specified,
see below), and an array of the same leading axis size will be returned as
usual. However, any collective operations in ``fun`` will be computed over
*all* participating devices, including those on other hosts, via
device-to-device communication. Conceptually, this can be thought of as
running a pmap over a single array sharded across hosts, where each host
"sees" only its local shard of the input and output. The SPMD model requires
that the same multi-host pmaps must be run in the same order on all devices,
but they can be interspersed with arbitrary operations running on a single
host.
Args:
fun: Function to be mapped over argument axes. Its arguments and return
value should be arrays, scalars, or (nested) standard Python containers
(tuple/list/dict) thereof.
axis_name: Optional, a hashable Python object used to identify the mapped
axis so that parallel collectives can be applied.
devices: This is an experimental feature and the API is likely to change.
Optional, a sequence of Devices to map over. (Available devices can be
retrieved via jax.devices()). If specified, the size of the mapped axis
must be equal to the number of local devices in the sequence. Nested
``pmap`` s with ``devices`` specified in either the inner or outer ``pmap``
are not yet supported.
backend: This is an experimental feature and the API is likely to change.
Optional, a string representing the xla backend. 'cpu', 'gpu', or 'tpu'.
Returns:
A parallelized version of ``fun`` with arguments that correspond to those of
``fun`` but each with an additional leading array axis (with equal sizes)
and with output that has an additional leading array axis (with the same
size).
For example, assuming 8 XLA devices are available, ``pmap`` can be used as a
map along a leading array axes:
>>> out = pmap(lambda x: x ** 2)(np.arange(8))
>>> print(out)
[0, 1, 4, 9, 16, 25, 36, 49]
>>> x = np.arange(3 * 2 * 2.).reshape((3, 2, 2))
>>> y = np.arange(3 * 2 * 2.).reshape((3, 2, 2)) ** 2
>>> out = pmap(np.dot)(x, y)
>>> print(out)
[[[ 4. 9.]
[ 12. 29.]]
[[ 244. 345.]
[ 348. 493.]]
[[ 1412. 1737.]
[ 1740. 2141.]]]
In addition to expressing pure maps, ``pmap`` can also be used to express
parallel single-program multiple-data (SPMD) programs that communicate via
collective operations. For example:
>>> f = lambda x: x / jax.lax.psum(x, axis_name='i')
>>> out = pmap(f, axis_name='i')(np.arange(4.))
>>> print(out)
[ 0. 0.16666667 0.33333334 0.5 ]
>>> print(out.sum())
1.0
In this example, ``axis_name`` is a string, but it can be any Python object
with ``__hash__`` and ``__eq__`` defined.
The argument ``axis_name`` to ``pmap`` names the mapped axis so that
collective operations, like ``jax.lax.psum``, can refer to it. Axis names are
important particularly in the case of nested ``pmap`` functions, where
collectives can operate over distinct axes:
>>> from functools import partial
>>> @partial(pmap, axis_name='rows')
>>> @partial(pmap, axis_name='cols')
>>> def normalize(x):
>>> row_normed = x / jax.lax.psum(x, 'rows')
>>> col_normed = x / jax.lax.psum(x, 'cols')
>>> doubly_normed = x / jax.lax.psum(x, ('rows', 'cols'))
>>> return row_normed, col_normed, doubly_normed
>>>
>>> x = np.arange(8.).reshape((4, 2))
>>> row_normed, col_normed, doubly_normed = normalize(x)
>>> print(row_normed.sum(0))
[ 1. 1.]
>>> print(col_normed.sum(1))
[ 1. 1. 1. 1.]
>>> print(doubly_normed.sum((0, 1)))
1.0
On multi-host platforms, collective operations operate over all devices,
including those those on other hosts. For example, assuming the following code
runs on two hosts with 4 XLA devices each:
>>> f = lambda x: x + jax.lax.psum(x, axis_name='i')
>>> data = np.arange(4) if jax.host_id() == 0 else np.arange(4,8)
>>> out = pmap(f, axis_name='i')(data)
>>> print(out)
[28 29 30 31] # on host 0
[32 33 34 35] # on host 1
Each host passes in a different length-4 array, corresponding to its 4 local
devices, and the psum operates over all 8 values. Conceptually, the two
length-4 arrays can be thought of as sharded length-16 array (in this example
equivalent to np.arange(8)) that is mapped over, with the length-8 mapped axis
given name 'i'. The pmap call on each host then returns the corresponding
length-4 output shard.
The ``devices`` argument can be used to specify exactly which devices are used
to run the parallel computation. For example, again assuming a single host
with 8 devices, the following code defines two parallel computations, one
which runs on the first six devices and one on the remaining two:
>>> from functools import partial
>>> @partial(pmap, axis_name='i', devices=jax.devices()[:6])
>>> def f1(x):
>>> return x / jax.lax.psum(x, axis_name='i')
>>>
>>> @partial(pmap, axis_name='i', devices=jax.devices()[-2:])
>>> def f2(x):
>>> return jax.lax.psum(x ** 2, axis_name='i')
>>>
>>> print(f1(np.arange(6.)))
[0. 0.06666667 0.13333333 0.2 0.26666667 0.33333333]
>>> print(f2(np.array([2., 3.])))
[ 13. 13.]
"""
_check_callable(fun)
axis_name = _TempAxisName(fun) if axis_name is None else axis_name
@wraps(fun)
def f_pmapped(*args, **kwargs):
f = lu.wrap_init(fun)
args, in_tree = tree_flatten((args, kwargs))
axis_size = _pmap_axis_size(args)
_check_args(args)
flat_fun, out_tree = flatten_fun(f, in_tree)
out = pxla.xla_pmap(flat_fun, *args, axis_name=axis_name, axis_size=axis_size,
devices=tuple(devices) if devices is not None else devices,
backend=backend)
return tree_unflatten(out_tree(), out)
namestr = "pmap({}, axis_name={})".format
f_pmapped.__name__ = namestr(f_pmapped.__name__, axis_name)
return f_pmapped
def _pmap_axis_size(xs):
for x in xs:
try:
return x.shape[0]
except AttributeError:
pass
else:
msg = "pmap got value with no leading axis to map over: {}."
raise ValueError(msg.format([x for x in xs if not hasattr(x, 'shape')]))
class _TempAxisName(object):
def __init__(self, obj):
self.obj = obj
def __repr__(self):
return '<axis {}>'.format(hex(id(self.obj)))
def __hash__(self):
return hash(self.obj)
def __eq__(self, other):
return self.obj is other.obj
def soft_pmap(fun, axis_name=None, backend=None):
warn("soft_pmap is an experimental feature and probably has bugs!")
_check_callable(fun)
axis_name = _TempAxisName(fun) if axis_name is None else axis_name
@wraps(fun)
def f_pmapped(*args, **kwargs):
f = lu.wrap_init(fun)
args_flat, in_tree = tree_flatten((args, kwargs))
axis_size = _pmap_axis_size(args_flat)
_check_args(args_flat)
flat_fun, out_tree = flatten_fun(f, in_tree)
chunk_size, leftover = divmod(axis_size, pxla.unmapped_device_count(backend))
if chunk_size == 0 and leftover:
return pmap(fun, axis_name, backend)(*args) # can map directly onto hardware
elif leftover:
msg = ("soft_pmap mapped axis size must be divisble by the number of "
"XLA devices (or be less than or equal to that number), but got "
"an axis size of {} with {} devices.")
raise ValueError(msg.format(axis_size, pxla.pxla.unmapped_device_count()))
num_chunks = axis_size // chunk_size
reshaped_args = [_reshape_split(num_chunks, x) for x in args_flat]
soft_mapped_fun = pxla.split_axis(flat_fun, axis_name, chunk_size)
reshaped_outs = pxla.xla_pmap(soft_mapped_fun, *reshaped_args,
axis_name=axis_name, axis_size=num_chunks,
devices=None, backend=backend)
outs = [_reshape_merge(out) for out in reshaped_outs]
return tree_unflatten(out_tree(), outs)
namestr = "soft_pmap({}, axis_name={})".format
f_pmapped.__name__ = namestr(f_pmapped.__name__, axis_name)
return f_pmapped
def _reshape_split(num_chunks, x):
aval = core.get_aval(x)
if aval is core.abstract_unit:
return x
else:
return x.reshape((num_chunks, x.shape[0] // num_chunks) + x.shape[1:])
def _reshape_merge(x):
aval = core.get_aval(x)
if aval is core.abstract_unit:
return x
else:
return x.reshape((-1,) + x.shape[2:])
def _papply(fun):
# This function is for testing purposes.
axis_name = _TempAxisName(fun)
def papply_fun(*args, **kwargs):
f = lu.wrap_init(fun)
args_flat, in_tree = tree_flatten((args, kwargs))
flat_fun, out_tree = flatten_fun(f, in_tree)
axis_size = _pmap_axis_size(args_flat)
out_flat = parallel.papply(flat_fun, axis_name, args_flat, axis_size)
return tree_unflatten(out_tree(), out_flat)
return papply_fun, axis_name
def _parallelize(fun):
axis_name = _TempAxisName(fun)
def pfun(*args):
f = lu.wrap_init(fun)
args_flat, in_tree = tree_flatten(args)
f, out_tree = flatten_fun_nokwargs(f, in_tree)
axis_size = _pmap_axis_size(args_flat)
chunk_size, leftover = divmod(axis_size, pxla.unmapped_device_count())
if chunk_size == 0 and leftover:
return pmap(fun, axis_name)(*args) # can map directly onto hardware
elif leftover:
raise ValueError
num_chunks = axis_size // chunk_size
reshaped_args = [_reshape_split(num_chunks, x) for x in args_flat]
f, out_axes = parallel.papply_transform(f, axis_name, axis_size)
f = pxla.split_axis(f, axis_name, chunk_size)
outs = pxla.xla_pmap(f, *reshaped_args, axis_name=axis_name,
axis_size=num_chunks, devices=None)
outs = map(_reshape_merge, outs)
outs = [batching.matchaxis(axis_size, 0, dst, x)
for dst, x in zip(out_axes(), outs)]
return tree_unflatten(out_tree(), outs)
return pfun
def mask(fun, in_shapes, out_shape):
in_specs, in_shapes_tree = tree_flatten(in_shapes)
out_specs, out_shapes_tree = tree_flatten(out_shape)
in_specs = map(masking.parse_spec, in_specs)
out_specs = map(masking.parse_spec, out_specs)
unique_ids = collections.defaultdict(object)
in_specs = map(partial(_remap_ids, unique_ids), in_specs)
out_specs = map(partial(_remap_ids, unique_ids), out_specs)
def wrapped_fun(args, logical_env):
args_flat, in_tree = tree_flatten(args)
if in_tree != in_shapes_tree: raise TypeError("pytree mismatch")
logical_env = {unique_ids[name] : val for name, val in logical_env.items()}
in_shapes = map(masking.finalize_spec, in_specs, map(onp.shape, args_flat))
padded_env = _bind_shapes(in_shapes, [x.shape for x in args_flat])
f = lu.wrap_init(fun)
flat_fun, out_tree = flatten_fun_nokwargs(f, in_tree)
outs, out_shapes_ = masking.mask_fun(
flat_fun, logical_env, padded_env, args_flat, in_shapes)
if not out_tree() == out_shapes_tree: raise TypeError("pytree mismatch")
out_shapes = map(masking.finalize_spec, out_specs, map(onp.shape, outs))
if not out_shapes == list(out_shapes_):
raise masking.ShapeError
if not all(onp.shape(out) == masking.eval_shape_expr(padded_env, expr)
for out, expr in zip(outs, out_shapes)):
raise masking.ShapeError
return tree_unflatten(out_tree(), outs)
return wrapped_fun
def _remap_ids(names, shape_spec):
ShapeSpec, Poly, Mon = masking.ShapeSpec, masking.Poly, masking.Mon
mdim = masking.monomorphic_dim
return ShapeSpec(Poly({Mon({names[id] : deg for id, deg in mon.items()})
: coeff for mon, coeff in poly.items()})
if poly is not mdim else mdim for poly in shape_spec)
def _bind_shapes(shape_exprs, shapes):
env = {}
for shape_expr, shape in zip(shape_exprs, shapes):
for poly, d in zip(shape_expr, shape):
if masking.is_constant(poly):
continue
else:
(binder,), = poly # TODO generalize to handle striding
if env.setdefault(binder, d) != d: raise masking.ShapeError
return env
@curry
def shapecheck(in_shapes, out_shape, fun):
in_shapes, in_tree = tree_flatten(in_shapes)
in_shapes = map(masking.parse_spec, in_shapes)
out_shapes, out_tree = tree_flatten(out_shape)
out_shapes = map(masking.parse_spec, out_shapes)
flat_fun, out_tree_ = flatten_fun_nokwargs(lu.wrap_init(fun), in_tree)
out_shapes_ = masking.shapecheck(flat_fun, in_shapes)
if out_tree != out_tree_(): raise TypeError("pytree mismatch")
if not all(map(_shape_spec_consistent, out_shapes, out_shapes_)):
raise masking.ShapeError
return fun
def _shape_spec_consistent(spec, expr):
return all(a == b for a, b in zip(spec, expr) if a is not masking.monomorphic_dim)
def jvp(fun, primals, tangents):
"""Computes a (forward-mode) Jacobian-vector product of `fun`.
Args:
fun: Function to be differentiated. Its arguments should be arrays, scalars,
or standard Python containers of arrays or scalars. It should return an
array, scalar, or standard Python container of arrays or scalars.
primals: The primal values at which the Jacobian of `fun` should be
evaluated. Should be either a tuple or a list of arguments,
and its length should equal to the number of positional parameters of `fun`.
tangents: The tangent vector for which the Jacobian-vector product should be
evaluated. Should be either a tuple or a list of tangents, with the same
tree structure and array shapes as `primals`.
Returns:
A `(primals_out, tangents_out)` pair, where `primals_out` is
`fun(*primals)`, and `tangents_out` is the Jacobian-vector product of
`function` evaluated at `primals` with `tangents`. The `tangents_out` value
has the same Python tree structure and shapes as `primals_out`.
For example:
>>> y, v = jax.jvp(jax.numpy.sin, (0.1,), (0.2,))
>>> print(y)
0.09983342
>>> print(v)
0.19900084
"""
if not isinstance(fun, lu.WrappedFun):
fun = lu.wrap_init(fun)
if (not isinstance(primals, (tuple, list)) or
not isinstance(tangents, (tuple, list))):
msg = ("primal and tangent arguments to jax.jvp must be tuples or lists; "
"found {} and {}.")
raise TypeError(msg.format(type(primals).__name__, type(tangents).__name__))
ps_flat, tree_def = tree_flatten(primals)
ts_flat, tree_def_2 = tree_flatten(tangents)
if tree_def != tree_def_2:
msg = ("primal and tangent arguments to jax.jvp must have the same tree "
"structure; primals have tree structure {} whereas tangents have "
"tree structure {}")
raise TypeError(msg.format(tree_def, tree_def_2))
for p, t in safe_zip(ps_flat, ts_flat):
if _dtype(p) != _dtype(t):
msg = ("primal and tangent arguments to jax.jvp must have equal types; "
"type mismatch primal {} vs tangent {}")
raise TypeError(msg.format(_dtype(p), _dtype(t)))
flat_fun, out_tree = flatten_fun_nokwargs(fun, tree_def)
out_primals, out_tangents = ad.jvp(flat_fun).call_wrapped(ps_flat, ts_flat)
return (tree_unflatten(out_tree(), out_primals),
tree_unflatten(out_tree(), out_tangents))
def linearize(fun, *primals):
"""Produce a linear approximation to `fun` using `jvp` and partial evaluation.
Args:
fun: Function to be differentiated. Its arguments should be arrays, scalars,
or standard Python containers of arrays or scalars. It should return an
array, scalar, or standard python container of arrays or scalars.
primals: The primal values at which the Jacobian of `fun` should be
evaluated. Should be a tuple of arrays, scalar, or standard Python
container thereof. The length of the tuple is equal to the number of
positional parameters of `fun`.
Returns:
A pair where the first element is the value of `f(*primals)` and the second
element is a function that evaluates the (forward-mode) Jacobian-vector
product of `fun` evaluated at `primals` without re-doing the linearization
work.
In terms of values computed, `linearize` behaves much like a curried `jvp`,
where these two code blocks compute the same values::
y, out_tangent = jax.jvp(f, (x,), (in_tangent,))
y, f_jvp = jax.linearize(f, x)
out_tangent = f_jvp(in_tangent)
However, the difference is that `linearize` uses partial evaluation so that
the function `f` is not re-linearized on calls to `f_jvp`. In general that
means the memory usage scales with the size of the computation, much like in
reverse-mode. (Indeed, `linearize` has a similar signature to `vjp`!)
This function is mainly useful if you want to apply `f_jvp` multiple times,
i.e. to evaluate a pushforward for many different input tangent vectors at the
same linearization point. Moreover if all the input tangent vectors are known
at once, it can be more efficient to vectorize using `vmap`, as in::
pushfwd = partial(jvp, f, (x,))
y, out_tangents = vmap(pushfwd, out_axes=(None, 0))((in_tangents,))
By using `vmap` and `jvp` together like this we avoid the stored-linearization
memory cost that scales with the depth of the computation, which is incurred
by both `linearize` and `vjp`.
Here's a more complete example of using `linearize`:
>>> def f(x): return 3. * np.sin(x) + np.cos(x / 2.)
...
>>> jax.jvp(f, (2.,), (3.,))
(array(3.2681944, dtype=float32), array(-5.007528, dtype=float32))
>>> y, f_jvp = jax.linearize(f, 2.)
>>> print(y)
3.2681944
>>> print(f_jvp(3.))
-5.007528
>>> print(f_jvp(4.))
-6.676704
"""
f = lu.wrap_init(fun)
primals_flat, in_tree = tree_flatten((primals, {}))
jaxtree_fun, out_tree = flatten_fun(f, in_tree)
out_primals, out_pvals, jaxpr, consts = ad.linearize(jaxtree_fun, *primals_flat)
out_tree = out_tree()
out_primal_py = tree_unflatten(out_tree, out_primals)
primal_avals = list(map(core.get_aval, primals_flat))
lifted_jvp = partial(lift_linearized, jaxpr, primal_avals, consts,
(in_tree, out_tree), out_pvals)
return out_primal_py, lifted_jvp
def lift_linearized(jaxpr, primal_avals, consts, io_tree, out_pvals, *py_args):
def fun(*tangents):
tangent_avals = list(map(core.get_aval, tangents))
for primal_aval, tangent_aval in zip(primal_avals, tangent_avals):
try:
core.lattice_join(primal_aval, tangent_aval)
except TypeError:
msg = ("linearized function called on tangent values inconsistent with "
"the original primal values.")
raise ValueError(msg)
dummy = (core.unit,) * len(tangents)
out = eval_jaxpr(jaxpr, consts, (), *(dummy + tangents))
tangents_out = out[len(out)//2:]
return tuple(map(pe.merge_pvals, tangents_out, out_pvals))
return apply_flat_fun(fun, io_tree, *py_args)
def _check_inexact_input_vjp(x):
aval = core.get_aval(x)
if not dtypes.issubdtype(aval.dtype, onp.inexact):
msg = ("Primal inputs to reverse-mode differentiation must be of float "
"or complex type, got type {}")
raise TypeError(msg.format(aval.dtype.name))
def _vjp_pullback_wrapper(fun, cotangent_dtypes, io_tree, py_args):
in_tree_expected, out_tree = io_tree
args, in_tree = tree_flatten(py_args)
if in_tree != in_tree_expected:
msg = ("Tree structure of cotangent input {}, does not match structure of "
"primal output {}")
raise TypeError(msg.format(in_tree_expected, in_tree))
for a, dtype in safe_zip(args, cotangent_dtypes):
if _dtype(a) != dtype:
msg = ("Type of cotangent input to vjp pullback function ({}) does not "
"match type of corresponding primal output ({})")
raise TypeError(msg.format(_dtype(a), dtype))
ans = fun(*args)
return tree_unflatten(out_tree, ans)
def vjp(fun, *primals, **kwargs):
"""Compute a (reverse-mode) vector-Jacobian product of `fun`.
`grad` is implemented as a special case of `vjp`.
Args:
fun: Function to be differentiated. Its arguments should be arrays, scalars,
or standard Python containers of arrays or scalars. It should return an
array, scalar, or standard Python container of arrays or scalars.
primals: A sequence of primal values at which the Jacobian of `fun`
should be evaluated. The length of `primals` should be equal to the number
of positional parameters to `fun`. Each primal value should be a tuple of
arrays, scalar, or standard Python containers thereof.
has_aux: Optional, bool. Indicates whether `fun` returns a pair where the
first element is considered the output of the mathematical function to be
differentiated and the second element is auxiliary data. Default False.
Returns:
A `(primals_out, vjpfun)` pair, where `primals_out` is `fun(*primals)`.
`vjpfun` is a function from a cotangent vector with the same shape as
`primals_out` to a tuple of cotangent vectors with the same shape as
`primals`, representing the vector-Jacobian product of `fun` evaluated at
`primals`.
>>> def f(x, y):
... return jax.numpy.sin(x), jax.numpy.cos(y)
...
>>> primals, f_vjp = jax.vjp(f, 0.5, 1.0)
>>> xbar, ybar = f_vjp((-0.7, 0.3))
>>> print(xbar)
-0.61430776
>>> print(ybar)
-0.2524413
"""
has_aux = kwargs.pop('has_aux', False)
assert not kwargs
if not isinstance(fun, lu.WrappedFun):
fun = lu.wrap_init(fun)
primals_flat, in_tree = tree_flatten(primals)
_check_args(primals_flat)
tree_map(_check_inexact_input_vjp, primals)
if not has_aux:
flat_fun, out_tree = flatten_fun_nokwargs(fun, in_tree)
out_primal, out_vjp = ad.vjp(flat_fun, primals_flat)
out_tree = out_tree()
else:
flat_fun, out_aux_trees = flatten_fun_nokwargs2(fun, in_tree)
out_primal, out_vjp, aux = ad.vjp(flat_fun, primals_flat, has_aux=True)
out_tree, aux_tree = out_aux_trees()
out_primal_py = tree_unflatten(out_tree, out_primal)
vjp_py = partial(_vjp_pullback_wrapper, out_vjp,
[_dtype(x) for x in out_primal], (out_tree, in_tree))
if not has_aux:
return out_primal_py, vjp_py
else:
return out_primal_py, vjp_py, tree_unflatten(aux_tree, aux)
def make_jaxpr(fun):
"""Creates a function that produces its jaxpr given example args.
Args:
fun: The function whose `jaxpr` is to be computed. Its positional arguments
and return value should be arrays, scalars, or standard Python containers
(tuple/list/dict) thereof.
Returns:
A wrapped version of `fun` that when applied to example arguments returns a
TypedJaxpr representation of `fun` on those arguments.
A `jaxpr` is JAX's intermediate representation for program traces. The `jaxpr`
language is based on the simply-typed first-order lambda calculus with
let-bindings. `make_jaxpr` adapts a function to return its `jaxpr`, which we
can inspect to understand what JAX is doing internally.
The `jaxpr` returned is a trace of `fun` abstracted to `ShapedArray` level.
Other levels of abstraction exist internally.
We do not describe the semantics of the `jaxpr` language in detail here, but
instead give a few examples.
>>> def f(x): return jax.numpy.sin(jax.numpy.cos(x))
>>> print(f(3.0))
-0.83602184
>>> jax.make_jaxpr(f)(3.0)
{ lambda ; ; a.
let b = cos a
c = sin b
in [c] }
>>> jax.make_jaxpr(jax.grad(f))(3.0)
{ lambda ; ; a.
let b = cos a
c = cos b
d = mul 1.0 c
e = neg d
f = sin a
g = mul e f
in [g] }
"""
_check_callable(fun)
def pv_like(x):
aval = xla.abstractify(x)
return pe.PartialVal((aval, core.unit))
@wraps(fun)
def jaxpr_maker(*args, **kwargs):
wrapped = lu.wrap_init(fun)
jax_args, in_tree = tree_flatten((args, kwargs))
jaxtree_fun, out_tree = flatten_fun(wrapped, in_tree)
in_pvals = map(pv_like, jax_args)
jaxpr, out_pvals, consts = pe.trace_to_jaxpr(
jaxtree_fun, in_pvals, instantiate=True, stage_out_calls=True)
out_avals = map(raise_to_shaped, unzip2(out_pvals)[0])
in_avals = tuple(raise_to_shaped(in_aval) for in_aval, _ in in_pvals)
typed_jaxpr = core.TypedJaxpr(jaxpr, consts, in_avals, out_avals)
return typed_jaxpr
jaxpr_maker.__name__ = "make_jaxpr({})".format(jaxpr_maker.__name__)
return jaxpr_maker
def device_put(x, device=None):
return tree_map(lambda y: xla.device_put_p.bind(y, device=device), x)
# TODO(mattjj): consider revising
def _device_get(x):
if isinstance(x, core.Tracer):
return x
return x.copy()
def device_get(x):
for y in tree_leaves(x):
try:
y.copy_to_host_async()
except AttributeError:
pass
return tree_map(_device_get, x)
def _argnums_partial(f, dyn_argnums, args):
if isinstance(dyn_argnums, int):
dyn_argnums = (dyn_argnums,)
else:
dyn_argnums = tuple(dyn_argnums)
fixed_args = tuple([core.unit if i in dyn_argnums else _wrap_hashably(arg)
for i, arg in enumerate(args)])
dyn_args = tuple(args[i] for i in dyn_argnums)
return _argnums_partial_(f, dyn_argnums, fixed_args), dyn_args
def _wrap_hashably(arg):
try:
hash(arg)
except TypeError:
return WrapHashably(arg) # e.g. ndarrays, DeviceArrays
else:
return Hashable(arg)
@lu.transformation
def _argnums_partial_(dyn_argnums, fixed_args, *dyn_args, **kwargs):
args = [None if arg is core.unit else arg.val for arg in fixed_args]
for i, arg in zip(dyn_argnums, dyn_args):
args[i] = arg
ans = yield args, kwargs
yield ans
def _check_args(args):
for arg in args:
if not (isinstance(arg, core.Tracer) or _valid_jaxtype(arg)):
raise TypeError("Argument '{}' of type {} is not a valid JAX type"
.format(arg, type(arg)))
def _valid_jaxtype(arg):
try:
xla.abstractify(arg) # faster than core.get_aval
except TypeError:
return False
else:
return True
class CustomTransformsFunction(object):
def __init__(self, fun, prim):
self.fun = fun
self.prim = prim
wraps(fun)(self)
def __repr__(self):
return '<jax.custom_transforms function {fun}>'.format(fun=self.__name__)
def __call__(self, *args):
# TODO(mattjj): instead of tracing to a jaxpr, use process_call
args_flat, in_tree = tree_flatten(args)
flat_fun, out_tree = flatten_fun_nokwargs(lu.wrap_init(self.fun), in_tree)
in_pvals = [pe.PartialVal((raise_to_shaped(core.get_aval(x)), core.unit))
for x in args_flat]
jaxpr, _, consts = pe.trace_to_jaxpr(flat_fun, in_pvals, instantiate=True)
outs = self.prim.bind(*it.chain(consts, args_flat), jaxpr=jaxpr,
in_tree=in_tree, out_tree=out_tree(),
num_consts=len(consts))
return tree_unflatten(out_tree(), outs)
def custom_transforms(fun):
"""Wraps a function so that its transformation behavior can be controlled.
A primary use case of ``custom_transforms`` is defining custom VJP rules (aka
custom gradients) for a Python function, while still supporting other
transformations like ``jax.jit`` and ``jax.vmap``. Custom differentiation
rules can be supplied using the ``jax.defjvp`` and ``jax.defvjp`` functions.
The ``custom_transforms`` decorator wraps ``fun`` so that its transformation
behavior can be overridden, but not all transformation rules need to be
specified manually. The default behavior is retained for any non-overridden
rules.
The function ``fun`` must satisfy the same constraints required for jit
compilation. In particular the shapes of arrays in the computation of ``fun``
may depend on the shapes of ``fun``'s arguments, but not their values.
Value dependent Python control flow is also not yet supported.
Args:
fun: a Python callable. Must be functionally pure. Its arguments and return
value should be arrays, scalars, or (nested) standard Python containers
(tuple/list/dict) thereof.
Returns:
A Python callable with the same input/output and transformation behavior as
``fun``, but for which custom transformation rules can be supplied, e.g.
using ``jax.defvjp``.
For example:
>>> @jax.custom_transforms
... def f(x):
... return np.sin(x ** 2)
...
>>> print(f(3.))
0.4121185
>>> print(jax.grad(f)(3.))
-5.4667816
>>> jax.defvjp(f, lambda g, x: g * x)
>>> print(jax.grad(f)(3.))
3.0
"""
name = getattr(fun, '__name__', '<unnamed custom_transforms primitive>')
fun_p = core.Primitive(name)
fun_p.multiple_results = True
def fun_impl(*args, **params):
consts, args = split_list(args, [params['num_consts']])
return core.eval_jaxpr(params['jaxpr'], consts, (), *args)
fun_p.def_impl(fun_impl)
def fun_jvp(primals, tangents, **params):
return ad.jvp(lu.wrap_init(fun_impl, params)).call_wrapped(primals, tangents)
ad.primitive_jvps[fun_p] = fun_jvp
def fun_batch(args, dims, **params):
return batching.batch_fun(lu.wrap_init(fun_impl, params), args, dims)
batching.primitive_batchers[fun_p] = fun_batch
def fun_abstract_eval(*avals, **params):
return pe.abstract_eval_fun(fun_impl, *avals, **params)
fun_p.def_abstract_eval(fun_abstract_eval)
def fun_translation(c, *xla_args, **params):
return xla.lower_fun(fun_impl, True)(c, *xla_args, **params)
xla.translations[fun_p] = fun_translation
return CustomTransformsFunction(fun, fun_p)
def _check_custom_transforms_type(name, fun):
if type(fun) is not CustomTransformsFunction:
msg = ("{} requires a custom_transforms function as its first argument, "
"but got type {}.")
raise TypeError(msg.format(name, type(fun)))
def defjvp_all(fun, custom_jvp):
"""Define a custom JVP rule for a ``custom_transforms`` function.
If ``fun`` represents a function with signature ``a -> b``, then
``custom_jvp`` represents a function with signature ``(a, T a) -> (b, T b)``,
where we use ``T x`` to represent a tangent type for the type ``x``.
In more detail, ``custom_jvp`` must take two arguments, both tuples of length
equal to the number of positional arguments to ``fun``. The first argument to
``custom_jvp`` represents the input primal values, and the second represents
the input tangent values. ``custom_jvp`` must return a pair where the first
element represents the output primal value and the second element represents
the output tangent value.
Defining a custom JVP rule also affects the default VJP rule, which is derived
from the JVP rule automatically via transposition.
Args:
fun: a custom_transforms function.
custom_jvp: a Python callable specifying the JVP rule, taking two tuples as
arguments specifying the input primal values and tangent values,
respectively. The tuple elements can be arrays, scalars, or (nested)
standard Python containers (tuple/list/dict) thereof. The output must be a
pair representing the primal output and tangent output, which can be
arrays, scalars, or (nested) standard Python containers. Must be
functionally pure.
Returns:
None. A side-effect is that ``fun`` is associated with the JVP rule
specified by ``custom_jvp``.
For example:
>>> @jax.custom_transforms
... def f(x):
... return np.sin(x ** 2)
...
>>> print(f(3.))
0.4121185
>>> out_primal, out_tangent = jax.jvp(f, (3.,), (2.,))
>>> print(out_primal)
0.4121185
>>> print(out_tangent)
-10.933563
>>> jax.defjvp_all(f, lambda ps, ts: (np.sin(ps[0] ** 2), 8. * ts[0]))
>>> out_primal, out_tangent = jax.jvp(f, (3.,), (2.,))
>>> print(out_primal)
0.4121185
>>> print(out_tangent)
16.0
"""
_check_custom_transforms_type("defjvp_all", fun)
def custom_transforms_jvp(primals, tangents, **params):
num_consts, in_tree = params['num_consts'], params['in_tree']
_, args_flat = split_list(primals, [num_consts])
consts_dot, args_dot_flat = split_list(tangents, [num_consts])
if not all(t is ad_util.zero for t in consts_dot):
msg = ("Detected differentiation with respect to closed-over values with "
"custom JVP rule, which isn't supported.")
raise ValueError(msg)
args = tree_unflatten(in_tree, args_flat)
args_dot = tree_unflatten(in_tree, args_dot_flat)
out, out_dot = custom_jvp(args, args_dot)
out_flat, out_tree = tree_flatten(out)
out_dot_flat, out_tree2 = tree_flatten(out_dot)
if out_tree != out_tree2:
msg = ("Custom JVP rule returned different tree structures for primals "
"and tangents, but they must be equal: {} and {}.")
raise TypeError(msg.format(out_tree, out_tree2))
return out_flat, out_dot_flat
ad.primitive_jvps[fun.prim] = custom_transforms_jvp
def defjvp(fun, *jvprules):
"""Definine JVP rules for each argument separately.
This function is a convenience wrapper around ``jax.defjvp_all`` for
separately defining JVP rules for each of the function's arguments. This
convenience wrapper does not provide a mechanism for depending on anything
other than the function arguments and its primal output value, though
depending on intermediate results is possible using ``jax.defjvp_all``.
The signature of each component JVP rule is ``lambda g, ans, *primals: ...``
where ``g`` represents the tangent of the corresponding positional argument,
``ans`` represents the output primal, and ``*primals`` represents all the
primal positional arguments.
Defining a custom JVP rule also affects the default VJP rule, which is derived
from the JVP rule automatically via transposition.
Args:
fun: a custom_transforms function.
*jvprules: a sequence of functions or Nones specifying the JVP rule for each
corresponding positional argument. When an element is None, it indicates
that the Jacobian from the corresponding input to the output is zero.
Returns:
None. A side-effect is that ``fun`` is associated with the JVP rule
specified by ``*jvprules``.
For example:
>>> @jax.custom_transforms
... def f(x):
... return np.sin(x ** 2)
...
>>> print(f(3.))
0.4121185
>>> out_primal, out_tangent = jax.jvp(f, (3.,), (2.,))
>>> print(out_primal)
0.4121185
>>> print(out_tangent)
-10.933563
>>> jax.defjvp(f, lambda g, ans, x: 8. * g + ans)
>>> out_primal, out_tangent = jax.jvp(f, (3.,), (2.,))
>>> print(out_primal)
0.4121185
>>> print(out_tangent)
16.412119
"""
_check_custom_transforms_type("defjvp", fun)
def custom_jvp(primals, tangents):
ans = fun(*primals)
tangents_out = [rule(t, ans, *primals) for rule, t in zip(jvprules, tangents)
if rule is not None and t is not ad_util.zero]
return ans, reduce(ad.add_tangents, tangents_out, ad_util.zero)
defjvp_all(fun, custom_jvp)
def defvjp_all(fun, custom_vjp):
"""Define a custom VJP rule for a ``custom_transforms`` function.
If ``fun`` represents a function with signature ``a -> b``, then
``custom_vjp`` represents a function with signature ``a -> (b, CT b -> CT a)``
where we use ``CT x`` to represent a cotangent type for the type ``x``. That
is, ``custom_vjp`` should take the same arguments as ``fun`` and return a pair
where the first element represents the primal value of ``fun`` applied to the
arguments, and the second element is a VJP function that maps from output
cotangents to input cotangents, returning a tuple with length equal to the
number of positional arguments supplied to ``fun``.
The VJP function returned as the second element of the output of
``custom_vjp`` can close over intermediate values computed when evaluating the
primal value of ``fun``. That is, use lexical closure to share work between
the forward pass and the backward pass of reverse-mode automatic
differentiation.
See also ``jax.custom_gradient``.
Args:
fun: a custom_transforms function.
custom_vjp: a Python callable specifying the VJP rule, taking the same
arguments as ``fun`` and returning a pair where the first elment is the
value of ``fun`` applied to the arguments and the second element is a
Python callable representing the VJP map from output cotangents to input
cotangents. The returned VJP function must accept a value with the same
shape as the value of ``fun`` applied to the arguments and must return a
tuple with length equal to the number of positional arguments to ``fun``.
Arguments can be arrays, scalars, or (nested) standard Python containers
(tuple/list/dict) thereof. Must be functionally pure.
Returns:
None. A side-effect is that ``fun`` is associated with the VJP rule
specified by ``custom_vjp``.
For example:
>>> @jax.custom_transforms
... def f(x):
... return np.sin(x ** 2)
...
>>> print(f(3.))
0.4121185
>>> print(jax.grad(f)(3.))
-5.4667816
>>> jax.defvjp_all(f, lambda x: (np.sin(x ** 2), lambda g: (g * x,)))
>>> print(f(3.))
0.4121185
>>> print(jax.grad(f)(3.))
3.0
An example with a function on two arguments, so that the VJP function must
return a tuple of length two:
>>> @jax.custom_transforms
... def f(x, y):
... return x * y
...
>>> jax.defvjp_all(f, lambda x, y: (x * y, lambda g: (y, x)))
>>> print(f(3., 4.))
12.0
>>> print(jax.grad(f, argnums=(0, 1))(3., 4.))
(4.0, 3.0)
"""
_check_custom_transforms_type("defvjp_all", fun)
def custom_transforms_vjp(*consts_and_args, **params):
num_consts, in_tree = params['num_consts'], params['in_tree']
consts, args_flat = split_list(consts_and_args, [num_consts])
args = tree_unflatten(params['in_tree'], args_flat)
out, vjp = custom_vjp(*args)
out_flat, out_tree = tree_flatten(out)
if out_tree != params['out_tree']:
msg = (
"First output of `custom_vjp`: {} doesn't match the structure of "
"the output of `fun`: {}\n"
"{}\n"
"vs\n"
"{}\n".format(custom_vjp, fun, out_tree, params['out_tree'])
)
raise TypeError(msg)
def vjp_flat(*cts_flat):
cts = tree_unflatten(out_tree, cts_flat)
args_cts_flat, in_tree2 = tree_flatten(vjp(cts))
if in_tree != in_tree2:
msg = (
"Output of the `vjp`: {} doesn't match the structure of args of "
"`fun`: {}\n"
"{}\n"
"vs\n"
"{}\n".format(vjp, fun, in_tree2, in_tree)
)
raise TypeError(msg)
return [core.unit] * num_consts + list(args_cts_flat)
return out_flat, vjp_flat
ad.defvjp_all(fun.prim, custom_transforms_vjp)
def defvjp(fun, *vjprules):
"""Define VJP rules for each argument separately.
This function is a convenience wrapper around ``jax.defvjp_all`` for
separately defining VJP rules for each of the function's arguments. This
convenience wrapper does not provide a mechanism for depending on anything
other than the function arguments and its primal output value, though
depending on intermediate results is possible using ``jax.defvjp_all``.
The signature of each component VJP rule is ``lambda g, ans, *primals: ...``
where ``g`` represents the output cotangent, ``ans`` represents the output
primal, and ``*primals`` represents all the primal positional arguments.
Args:
fun: a custom_transforms function.
*vjprules: a sequence of functions or Nones specifying the VJP rule for each
corresponding positional argument. When an element is None, it indicates
that the Jacobian from the corresponding input to the output is zero.
Returns:
None. A side-effect is that ``fun`` is associated with the VJP rule
specified by ``*vjprules``.
For example:
>>> @jax.custom_transforms
... def f(x, y):
... return np.sin(x ** 2 + y)
...
>>> print(f(3., 4.))
0.42016703
>>> print(jax.grad(f)(3., 4.))
5.4446807
>>> print(jax.grad(f, 1)(3., 4.))
0.9074468
>>> jax.defvjp(f, None, lambda g, ans, x, y: g + x + y + ans)
>>> print(jax.grad(f)(3., 4.))
0.0
>>> print(jax.grad(f, 1)(3., 4.))
8.420167
"""
_check_custom_transforms_type("defvjp", fun)
def custom_vjp(*primals):
ans = fun(*primals)
# TODO(mattjj): avoid instantiating zeros?
def vjpfun(ct):
return tuple(vjp(ct, ans, *primals) if vjp else ad_util.zeros_like_jaxval(x)
for x, vjp in zip(primals, vjprules))
return ans, vjpfun
defvjp_all(fun, custom_vjp)
def custom_gradient(fun):
"""Convenience function for defining custom VJP rules (aka custom gradients).
While the canonical way to define custom VJP rules is via ``jax.defvjp_all``
and its convenience wrappers, the ``custom_gradient`` convenience wrapper
follows TensorFlow's ``tf.custom_gradient`` API. The difference here is that
``custom_gradient`` can be used as a decorator on one function that returns
both the primal value (representing the output of the mathematical function to
be differentiated) and the VJP (gradient) function.
See https://www.tensorflow.org/api_docs/python/tf/custom_gradient.
If the mathematical function to be differentiated has type signature
``a -> b``, then the Python callable ``fun`` should have signature
``a -> (b, CT b -> CT a)`` where we use ``CT x`` to denote a cotangent type
for ``x``. See the example below. That is, ``fun`` should return a pair where
the first element represents the value of the mathematical function to be
differentiated and the second element is a function that represents the custom
VJP rule.
The custom VJP function returned as the second element of the output of ``fun``
can close over intermediate values computed when evaluating the function to be
differentiated. That is, use lexical closure to share work between the forward
pass and the backward pass of reverse-mode automatic differentiation.
Args:
fun: a Python callable specifying both the mathematical function to be
differentiated and its reverse-mode differentiation rule. It should return
a pair consisting of an output value and a Python callable that represents
the custom gradient function.
Returns:
A Python callable with signature ``a -> b``, i.e. that returns the output
value specified by the first element of ``fun``'s output pair. A side effect
is that under-the-hood ``jax.defvjp_all`` is called to set up the returned
Python callable with the custom VJP rule specified by the second element
of ``fun``'s output pair.
For example:
>>> @jax.custom_gradient
... def f(x):
... return x ** 2, lambda g: (g * x,)
...
>>> print(f(3.))
9.0
>>> print(jax.grad(f)(3.))
3.0
An example with a function on two arguments, so that the VJP function must
return a tuple of length two:
>>> @jax.custom_gradient
... def f(x, y):
... return x * y, lambda g: (y, x)
...
>>> print(f(3., 4.))
12.0
>>> print(jax.grad(f, argnums=(0, 1))(3., 4.))
(4.0, 3.0)
"""
def primal_fun(*args, **kwargs):
ans, _ = fun(*args, **kwargs)
return ans
primal_fun = custom_transforms(primal_fun)
defvjp_all(primal_fun, fun)
return primal_fun
def jarrett(fun):
new_fun = custom_transforms(fun)
def elementwise_jvp(primals, tangents):
pushfwd = partial(jvp, fun, primals)
y, jacs = vmap(pushfwd, out_axes=(None, 0))(_elementwise_std_basis(tangents))
flat_tangents, _ = tree_flatten(tangents)
out_tangent = sum([t * jac for t, jac in zip(flat_tangents, jacs)])
return y, out_tangent
defjvp_all(new_fun, elementwise_jvp)
return new_fun
def _elementwise_std_basis(pytree):
leaves, _ = tree_flatten(pytree)
arity = len(leaves)
dims = map(onp.size, leaves)
# TODO(mattjj): use symbolic constants
dtype = dtypes.result_type(*leaves)
if not dtypes.issubdtype(dtype, onp.floating):
msg = ("Jacobian only defined for functions with floating input and output "
"dtypes (i.e. dtypes that model real numbers), got {}.")
raise TypeError(msg.format(dtype)) # TODO(mattjj, dougalm): handle complex
basis_array = onp.stack([onp.concatenate(
[onp.ones(dims[j], dtype) if i == j else onp.zeros(dims[j], dtype)
for j in range(arity)]) for i in range(arity)])
return _unravel_array_into_pytree(pytree, 1, basis_array)
# This function mostly exists for making slides about JAX.
def _make_graphviz(fun):
"""Adapts `fun` to return a graphviz dot string of its program representation.
Args:
fun: The function whose `jaxpr` is to be rendered into graphviz dot. Its
positional arguments and return value should be arrays, scalars, or
standard Python containers (tuple/list/dict) thereof.
Returns:
A wrapped version of `fun`, set up to return a graphviz dot string.
See make_jaxpr for a related function.
"""
# TODO(mattjj): handle eqn.restructure
# TODO(mattjj): handle subjaxprs
def pv_like(x):
aval = xla.abstractify(x)
return pe.PartialVal((aval, core.unit))
id_names = ("id{}".format(i) for i in it.count())
def jaxpr_to_graphviz(jaxpr, consts):
fragment = []
fragment.extend(map(invar_node, jaxpr.invars, jaxpr.invars))
fragment.extend(map(freevar_node, jaxpr.freevars, jaxpr.freevars))
fragment.extend(map(constant_node, jaxpr.constvars, consts))
for eqn in jaxpr.eqns:
if eqn.destructure:
id_name = next(id_names)
fragment.append(function_node(id_name, eqn.primitive.name))
fragment.extend(edge(invar, id_name) for invar in eqn.invars)
fragment.extend(edge(id_name, outvar) for outvar in eqn.outvars)
else:
fragment.append(function_node(eqn.outvars[0], eqn.primitive.name))
fragment.extend(edge(invar, eqn.outvars[0]) for invar in eqn.invars)
fragment.append(outvar_node(jaxpr.outvar, "out"))
return graph(''.join(fragment))
edge = '{} -> {} [color=gray30];\n'.format
function_node = '{} [label="{}", shape=box, color=lightskyblue, style=filled];\n'.format
invar_node = '{} [rank=2, label="{}", color=mediumspringgreen, style=filled];\n'.format
outvar_node = '{} [label="{}", fillcolor=indianred1, style="filled,dashed", color=black];\n'.format
constant_node = '{} [rank=2, label="{}", color=goldenrod1, style=filled];\n'.format
freevar_node = '{} [rank=2, label="{}", color=palegreen, style=filled];\n'.format
graph = 'digraph G {{{}}}'.format
@wraps(fun)
def graphviz_maker(*args, **kwargs):
wrapped = lu.wrap_init(fun, kwargs)
jax_args, in_trees = unzip2(map(pytree_to_jaxtupletree, args))
jaxtree_fun, out_tree = pytree_fun_to_jaxtupletree_fun(wrapped, in_trees)
pvals = map(pv_like, jax_args)
jaxpr, _, consts = pe.trace_to_jaxpr(jaxtree_fun, pvals)
return jaxpr_to_graphviz(jaxpr, consts)
graphviz_maker.__name__ = "make_graphviz({})".format(graphviz_maker.__name__)
return graphviz_maker
class ShapeDtypeStruct(object):
__slots__ = ["shape", "dtype"]
def __init__(self, shape, dtype):
self.shape = shape
self.dtype = dtype
def eval_shape(fun, *args, **kwargs):
"""Compute the shape/dtype of ``fun(*args, **kwargs)`` without any FLOPs.
This utility function is useful for performing shape inference. Its
input/output behavior is defined by::
def eval_shape(fun, *args, **kwargs):
out = fun(*args, **kwargs)
return jax.tree_util.tree_map(shape_dtype_struct, out)
def shape_dtype_struct(x):
return ShapeDtypeStruct(x.shape, x.dtype)
class ShapeDtypeStruct(object):
__slots__ = ["shape", "dtype"]
def __init__(self, shape, dtype):
self.shape = shape
self.dtype = dtype
In particular, the output is a pytree of objects that have ``shape`` and
``dtype`` attributes, but nothing else about them is guaranteed by the API.
But instead of applying ``fun`` directly, which might be expensive, it uses
JAX's abstract interpretation machinery to evaluate the shapes without doing
any FLOPs.
Using ``eval_shape`` can also catch shape errors, and will raise same shape
errors as evaluating ``fun(*args, **kwargs)``.
Args:
*args: a positional argument tuple of arrays, scalars, or (nested) standard
Python containers (tuples, lists, dicts, namedtuples, i.e. pytrees) of
those types. Since only the ``shape`` and ``dtype`` attributes are
accessed, only values that duck-type arrays are required, rather than real
ndarrays. The duck-typed objects cannot be namedtuples because those are
treated as standard Python containers. See the example below.
**kwargs: a keyword argument dict of arrays, scalars, or (nested) standard
Python containers (pytrees) of those types. As in ``args``, array values
need only be duck-typed to have ``shape`` and ``dtype`` attributes.
For example:
>>> f = lambda A, x: np.tanh(np.dot(A, x))
>>> class MyArgArray(object):
... def __init__(self, shape, dtype):
... self.shape = shape
... self.dtype = dtype
...
>>> A = MyArgArray((2000, 3000), np.float32)
>>> x = MyArgArray((3000, 1000), np.float32)
>>> out = jax.eval_shape(f, A, x) # no FLOPs performed
>>> print(out.shape)
(2000, 1000)
>>> print(out.dtype)
dtype('float32')
"""
def abstractify(x):
return ShapedArray(onp.shape(x), dtypes.result_type(x))
args_flat, in_tree = tree_flatten((args, kwargs))
fun, out_tree = flatten_fun(lu.wrap_init(fun), in_tree)
out = pe.abstract_eval_fun(fun.call_wrapped, *map(abstractify, args_flat))
out = [ShapeDtypeStruct(x.shape, x.dtype) for x in out]
return tree_unflatten(out_tree(), out)
def checkpoint(fun, concrete=False):
@wraps(fun)
def fun_remat(*args, **kwargs):
args_flat, in_tree = tree_flatten((args, kwargs))
flat_fun, out_tree = flatten_fun(lu.wrap_init(fun), in_tree)
out_flat = pe.remat_call(flat_fun, *args_flat, concrete=concrete)
return tree_unflatten(out_tree(), out_flat)
return fun_remat
remat = checkpoint
|
jax-master
|
jax/api.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
"""Utilities for working with tree-like container data structures.
This module provides a small set of utility functions for working with tree-like
data structures, such as nested tuples, lists, and dicts. We call these
structures pytrees. They are trees in that they are defined recursively (any
non-pytree is a pytree, i.e. a leaf, and any pytree of pytrees is a pytree) and
can be operated on recursively (object identity equivalence is not preserved by
mapping operations, and the structures cannot contain reference cycles).
The set of Python types that are considered pytree nodes (e.g. that can be
mapped over, rather than treated as leaves) is extensible. There is a single
module-level registry of types, and class hierarchy is ignored. By registering a
new pytree node type, that type in effect becomes transparent to the utility
functions in this file.
The primary purpose of this module is to enable the interoperability between
user defined data structures and JAX transformations (e.g. `jit`). This is not
meant to be a general purpose tree-like data structure handling library.
See the `JAX pytrees notebook <https://jax.readthedocs.io/en/latest/notebooks/JAX_pytrees.html>`_
for examples.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
import collections
from six.moves import reduce
from .lib import pytree
from .util import partial, safe_zip, unzip2
def tree_flatten(tree):
"""Flattens a pytree.
Args:
tree: a pytree to flatten.
Returns:
a pair with a list of leaves and the corresponding treedef.
"""
return pytree.flatten(tree)
def tree_unflatten(treedef, leaves):
"""Reconstructs a pytree from the treedef and the leaves.
The inverse of `tree_flatten`.
Args:
treedef: the treedef to reconstruct
leaves: the list of leaves to use for reconstruction. The list must
match the leaves of the treedef.
Returns:
The reconstructed pytree, containing the `leaves` placed in the
structure described by `treedef`.
"""
return treedef.unflatten(leaves)
def tree_leaves(tree):
"""Gets the leaves of a pytree."""
return pytree.flatten(tree)[0]
def tree_structure(tree):
"""Gets the treedef for a pytree."""
return pytree.flatten(tree)[1]
def treedef_tuple(treedefs):
"""Makes a tuple treedef from a list of child treedefs."""
return pytree.tuple(list(treedefs))
def treedef_children(treedef):
return treedef.children()
def treedef_is_leaf(treedef):
return treedef.num_nodes == 1
def register_pytree_node(nodetype, flatten_func, unflatten_func):
"""Extends the set of types that are considered internal nodes in pytrees.
See `example usage <https://jax.readthedocs.io/en/latest/notebooks/JAX_pytrees.html#Pytrees-are-extensible>`_.
Args:
nodetype: a Python type to treat as an internal pytree node.
flatten_func: a function to be used during flattening, taking a value
of type `nodetype` and returning a pair, with (1) an iterable for
the children to be flattened recursively, and (2) some auxiliary data
to be stored in the treedef and to be passed to the `unflatten_func`.
unflatten_func: a function taking two arguments: the auxiliary data that
was returned by `flatten_func` and stored in the treedef, and the
unflattened children. The function should return an instance of
`nodetype`.
"""
pytree.register_node(nodetype, flatten_func, unflatten_func)
_registry[nodetype] = _RegistryEntry(flatten_func, unflatten_func)
def tree_map(f, tree):
"""Maps a function over a pytree to produce a new pytree.
Args:
f: function to be applied at each leaf.
tree: a pytree to be mapped over.
Returns:
A new pytree with the same structure as `tree` but with the value at each
leaf given by `f(x)` where `x` is the value at the corresponding leaf in
`tree`.
"""
leaves, treedef = pytree.flatten(tree)
return treedef.unflatten(map(f, leaves))
def tree_multimap(f, tree, *rest):
"""Maps a multi-input function over pytree args to produce a new pytree.
Args:
f: function that takes `1 + len(rest)` arguments, to be applied at the
corresponding leaves of the pytrees.
tree: a pytree to be mapped over, with each leaf providing the first
positional argument to `f`.
*rest: a tuple of pytrees, each of which has the same structure as tree or
or has tree as a prefix.
Returns:
A new pytree with the same structure as `tree` but with the value at each
leaf given by `f(x, *xs)` where `x` is the value at the corresponding leaf
in `tree` and `xs` is the tuple of values at corresponding nodes in
`rest`.
"""
leaves, treedef = pytree.flatten(tree)
all_leaves = [leaves] + [treedef.flatten_up_to(r) for r in rest]
return treedef.unflatten(f(*xs) for xs in zip(*all_leaves))
# TODO(mattjj,phawkins): consider removing this function
def _process_pytree(process_node, tree):
leaves, treedef = pytree.flatten(tree)
return treedef.walk(process_node, None, leaves), treedef
def build_tree(treedef, xs):
return treedef.from_iterable_tree(xs)
def tree_transpose(outer_treedef, inner_treedef, pytree_to_transpose):
flat, treedef = tree_flatten(pytree_to_transpose)
expected_treedef = outer_treedef.compose(inner_treedef)
if treedef != expected_treedef:
raise TypeError("Mismatch\n{}\n != \n{}".format(treedef, expected_treedef))
inner_size = inner_treedef.num_leaves
outer_size = outer_treedef.num_leaves
flat = iter(flat)
lol = [[next(flat) for _ in range(inner_size)] for __ in range(outer_size)]
transposed_lol = zip(*lol)
subtrees = map(partial(tree_unflatten, outer_treedef), transposed_lol)
return tree_unflatten(inner_treedef, subtrees)
# TODO(mattjj): remove the Python-side registry when the C++-side registry is
# sufficiently queryable that we can express _replace_nones. That may mean once
# we have a flatten_one function.
_RegistryEntry = collections.namedtuple("RegistryEntry", ["to_iter", "from_iter"])
_registry = {
tuple: _RegistryEntry(lambda xs: (xs, None), lambda _, xs: tuple(xs)),
list: _RegistryEntry(lambda xs: (xs, None), lambda _, xs: list(xs)),
dict: _RegistryEntry(lambda xs: unzip2(sorted(xs.items()))[::-1],
lambda keys, xs: dict(zip(keys, xs))),
type(None): _RegistryEntry(lambda z: ((), None), lambda _, xs: None),
}
def _replace_nones(sentinel, tree):
if tree is None:
return sentinel
else:
handler = _registry.get(type(tree))
if handler:
children, metadata = handler.to_iter(tree)
proc_children = [_replace_nones(sentinel, child) for child in children]
return handler.from_iter(metadata, proc_children)
elif isinstance(tree, tuple) and hasattr(tree, '_fields'):
# handle namedtuple as a special case, based on heuristic
children = iter(tree)
proc_children = [_replace_nones(sentinel, child) for child in children]
return type(tree)(*proc_children)
else:
return tree
def tree_reduce(f, tree):
return reduce(f, tree_leaves(tree))
def tree_all(tree):
return all(tree_leaves(tree))
register_pytree_node(
collections.OrderedDict,
lambda x: (list(x.values()), list(x.keys())),
lambda keys, values: collections.OrderedDict(safe_zip(keys, values)))
register_pytree_node(
collections.defaultdict,
lambda x: (tuple(x.values()), (x.default_factory, tuple(x.keys()))),
lambda s, values: collections.defaultdict(s[0], safe_zip(s[1], values)))
class Partial(functools.partial):
"""A version of functools.partial that works in pytrees.
Use it for partial function evaluation in a way that is compatible with JAX's
transformations, e.g., ``Partial(func, *args, **kwargs)``.
(You need to explicitly opt-in to this behavior because we didn't want to give
functools.partial different semantics than normal function closures.)
"""
register_pytree_node(
Partial,
lambda partial_: ((partial_.args, partial_.keywords), partial_.func),
lambda func, xs: Partial(func, *xs[0], **xs[1]),
)
|
jax-master
|
jax/tree_util.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .tree_util import (build_tree, tree_flatten, tree_unflatten,
treedef_is_leaf)
from . import linear_util as lu
from .util import safe_map, unzip2, partial, curry
map = safe_map
@curry
def wraps(wrapped, fun, namestr="{fun}", docstr="{doc}", **kwargs):
try:
fun.__name__ = namestr.format(fun=get_name(wrapped))
fun.__module__ = get_module(wrapped)
fun.__doc__ = docstr.format(fun=get_name(wrapped), doc=get_doc(wrapped), **kwargs)
fun.__wrapped__ = wrapped
finally:
return fun
def get_name(fun): return getattr(fun, "__name__", "<unnamed function>")
def get_module(fun): return getattr(fun, "__module__", "<unknown module>")
def get_doc(fun): return getattr(fun, "__doc__", "")
@lu.transformation_with_aux
def flatten_fun(in_tree, *args_flat):
py_args, py_kwargs = tree_unflatten(in_tree, args_flat)
ans = yield py_args, py_kwargs
yield tree_flatten(ans)
def apply_flat_fun(fun, io_tree, *py_args):
in_tree_expected, out_tree = io_tree
args, in_tree = tree_flatten((py_args, {}))
if in_tree != in_tree_expected:
raise TypeError("Expected {}, got {}".format(in_tree_expected, in_tree))
ans = fun(*args)
return tree_unflatten(out_tree, ans)
@lu.transformation_with_aux
def flatten_fun_nokwargs(in_tree, *args_flat):
py_args = tree_unflatten(in_tree, args_flat)
ans = yield py_args, {}
yield tree_flatten(ans)
def apply_flat_fun_nokwargs(fun, io_tree, py_args):
in_tree_expected, out_tree = io_tree
args, in_tree = tree_flatten(py_args)
if in_tree != in_tree_expected:
raise TypeError("Expected {}, got {}".format(in_tree_expected, in_tree))
ans = fun(*args)
return tree_unflatten(out_tree, ans)
@lu.transformation_with_aux
def flatten_fun_nokwargs2(in_tree, *args_flat):
py_args = tree_unflatten(in_tree, args_flat)
ans, aux = yield py_args, {}
ans_flat, ans_tree = tree_flatten(ans)
aux_flat, aux_tree = tree_flatten(aux)
yield (ans_flat, aux_flat), (ans_tree, aux_tree)
|
jax-master
|
jax/api_util.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from collections import namedtuple
import itertools as it
import numpy as onp
import six
from six.moves import reduce
from .. import core
from .. import dtypes
from ..core import Trace, Tracer, new_master
from ..abstract_arrays import ShapedArray, make_shaped_array, array_types, raise_to_shaped
from ..ad_util import add_jaxvals, add_jaxvals_p, zeros_like_jaxval, zeros_like_p
from .. import linear_util as lu
from ..util import unzip2, partial, safe_map
from . import xla
from . import partial_eval as pe
map = safe_map
def batch(fun, in_vals, in_dims, out_dim_dests):
size, = {x.shape[d] for x, d in zip(in_vals, in_dims) if d is not not_mapped}
out_vals, out_dims = batch_fun(fun, in_vals, in_dims)
return map(partial(matchaxis, size), out_dims, out_dim_dests(), out_vals)
def batch_fun(fun, in_vals, in_dims):
with new_master(BatchTrace) as master:
fun, out_dims = batch_subtrace(fun, master, in_dims)
out_vals = fun.call_wrapped(*in_vals)
del master
return out_vals, out_dims()
@lu.transformation_with_aux
def batch_subtrace(master, in_dims, *in_vals):
trace = BatchTrace(master, core.cur_sublevel())
in_tracers = [BatchTracer(trace, val, dim) if dim is not None else val
for val, dim in zip(in_vals, in_dims)]
outs = yield in_tracers, {}
out_tracers = map(trace.full_raise, outs)
out_vals, out_dims = unzip2((t.val, t.batch_dim) for t in out_tracers)
yield out_vals, out_dims
### tracer
# TODO(mattjj): use a special sentinel type rather than None
NotMapped = type(None)
not_mapped = None
class BatchTracer(Tracer):
__slots__ = ['val', 'batch_dim']
def __init__(self, trace, val, batch_dim):
assert core.skip_checks or type(batch_dim) in (int, NotMapped)
self.trace = trace
self.val = val
self.batch_dim = batch_dim
@property
def aval(self):
aval = raise_to_shaped(core.get_aval(self.val))
if self.batch_dim is not_mapped:
return aval
else:
if aval is core.abstract_unit:
return aval
elif type(aval) is ShapedArray:
assert 0 <= self.batch_dim < aval.ndim
new_shape = tuple(onp.delete(aval.shape, self.batch_dim))
return ShapedArray(new_shape, aval.dtype)
else:
raise TypeError(aval)
def full_lower(self):
if self.batch_dim is not_mapped:
return core.full_lower(self.val)
else:
return self
class BatchTrace(Trace):
def pure(self, val):
return BatchTracer(self, val, not_mapped)
def lift(self, val):
return BatchTracer(self, val, not_mapped)
def sublift(self, val):
return BatchTracer(self, val.val, val.batch_dim)
def process_primitive(self, primitive, tracers, params):
vals_in, dims_in = unzip2((t.val, t.batch_dim) for t in tracers)
if all(bdim is not_mapped for bdim in dims_in):
return primitive.bind(*vals_in, **params)
else:
# TODO(mattjj,phawkins): if no rule implemented, could vmap-via-map here
batched_primitive = get_primitive_batcher(primitive)
val_out, dim_out = batched_primitive(vals_in, dims_in, **params)
if primitive.multiple_results:
return map(partial(BatchTracer, self), val_out, dim_out)
else:
return BatchTracer(self, val_out, dim_out)
def process_call(self, call_primitive, f, tracers, params):
assert call_primitive.multiple_results
if call_primitive in pe.map_primitives:
return self.process_map(call_primitive, f, tracers, params)
vals, dims = unzip2((t.val, t.batch_dim) for t in tracers)
if all(bdim is not_mapped for bdim in dims):
return call_primitive.bind(f, *vals, **params)
else:
f, dims_out = batch_subtrace(f, self.master, dims)
vals_out = call_primitive.bind(f, *vals, **params)
return [BatchTracer(self, v, d) for v, d in zip(vals_out, dims_out())]
def process_map(self, map_primitive, f, tracers, params):
vals, dims = unzip2((t.val, t.batch_dim) for t in tracers)
if all(dim is not_mapped for dim in dims):
return map_primitive.bind(f, *vals, **params)
else:
size, = {x.shape[d] for x, d in zip(vals, dims) if d is not not_mapped}
is_batched = tuple(d is not not_mapped for d in dims)
vals = [moveaxis(x, d, 1) if d is not not_mapped and d != 1 else x
for x, d in zip(vals, dims)]
dims = tuple(not_mapped if d is not_mapped else 0 for d in dims)
f, dims_out = batch_subtrace(f, self.master, dims)
vals_out = map_primitive.bind(f, *vals, **params)
dims_out = tuple(d + 1 if d is not not_mapped else d for d in dims_out())
return [BatchTracer(self, v, d) for v, d in zip(vals_out, dims_out)]
def post_process_call(self, call_primitive, out_tracers, params):
vals, dims = unzip2((t.val, t.batch_dim) for t in out_tracers)
master = self.master
def todo(x):
trace = BatchTrace(master, core.cur_sublevel())
return map(partial(BatchTracer, trace), x, dims)
return vals, todo
### primitives
primitive_batchers = {}
def get_primitive_batcher(p):
try:
return primitive_batchers[p]
except KeyError:
msg = "Batching rule for '{}' not implemented"
raise NotImplementedError(msg.format(p))
def defvectorized(prim):
primitive_batchers[prim] = partial(vectorized_batcher, prim)
def vectorized_batcher(prim, batched_args, batch_dims, **params):
assert all(batch_dims[0] == bd for bd in batch_dims[1:]), batch_dims
return prim.bind(*batched_args, **params), batch_dims[0]
def defbroadcasting(prim):
primitive_batchers[prim] = partial(broadcast_batcher, prim)
def broadcast_batcher(prim, args, dims, **params):
shapes = {(x.shape, d) for x, d in zip(args, dims) if onp.ndim(x)}
if len(shapes) == 1:
# if there's only agreeing batch dims and scalars, just call the primitive
d = next(d for d in dims if d is not not_mapped)
out = prim.bind(*args, **params)
return (out, (d,) * len(out)) if prim.multiple_results else (out, d)
else:
size, = {shape[d] for shape, d in shapes if d is not not_mapped}
args = [bdim_at_front(x, d, size) for x, d in zip(args, dims)]
ndim = max(onp.ndim(x) for x in args) # special-case scalar broadcasting
args = [_handle_scalar_broadcasting(ndim, x, d) for x, d in zip(args, dims)]
out = prim.bind(*args, **params)
return (out, (0,) * len(out)) if prim.multiple_results else (out, 0)
def _handle_scalar_broadcasting(nd, x, d):
if d is not_mapped or nd == onp.ndim(x):
return x
else:
return x.reshape(x.shape + (1,) * (nd - onp.ndim(x)))
def defreducer(prim):
primitive_batchers[prim] = partial(reducer_batcher, prim)
def reducer_batcher(prim, batched_args, batch_dims, axes, **params):
operand, = batched_args
bdim, = batch_dims
axes = tuple(onp.where(onp.less(axes, bdim), axes, onp.add(axes, 1)))
bdim_out = int(list(onp.delete(onp.arange(operand.ndim), axes)).index(bdim))
if 'input_shape' in params:
params = dict(params, input_shape=operand.shape)
return prim.bind(operand, axes=axes, **params), bdim_out
# sets up primitive batchers for ad_util and xla primitives
def add_batched(batched_args, batch_dims):
bdx, bdy = batch_dims
x, y = batched_args
if bdx == bdy or core.get_aval(x) == core.abstract_unit:
return add_jaxvals(x, y), bdx
elif bdx is not_mapped:
x = broadcast(x, y.shape[bdy], bdy)
return add_jaxvals(x, y), bdy
elif bdy is not_mapped:
y = broadcast(y, x.shape[bdx], bdx)
return add_jaxvals(x, y), bdx
else:
x = moveaxis(x, bdx, bdy)
return add_jaxvals(x, y), bdy
primitive_batchers[add_jaxvals_p] = add_batched
def zeros_like_batched(batched_args, batch_dims):
val, = batched_args
bdim, = batch_dims
return zeros_like_jaxval(val), bdim
primitive_batchers[zeros_like_p] = zeros_like_batched
defvectorized(xla.device_put_p)
### util
# These utilities depend on primitives for things like broadcasting, reshaping,
# and transposition on arrays. To avoid a circular import from depending on
# lax.py, these functions use method dispatch on their arguments, which could be
# DeviceArrays, numpy.ndarrays, or traced versions of those. This strategy
# almost works, except for broadcast, for which raw numpy.ndarrays don't have a
# method. To handle that case, the `broadcast` function uses a try/except.
class _Last(object): pass
last = _Last()
def broadcast(x, sz, axis):
if core.get_aval(x) is core.abstract_unit:
return core.unit
if axis is last:
axis = onp.ndim(x)
shape = list(onp.shape(x))
shape.insert(axis, sz)
if isinstance(x, onp.ndarray) or onp.isscalar(x):
return onp.broadcast_to(dtypes.coerce_to_array(x), shape)
else:
broadcast_dims = tuple(onp.delete(onp.arange(len(shape)), axis))
return x.broadcast_in_dim(shape, broadcast_dims)
def moveaxis(x, src, dst):
if core.get_aval(x) is core.abstract_unit:
return core.unit
if src == dst:
return x
src, dst = src % x.ndim, dst % x.ndim
perm = [i for i in range(onp.ndim(x)) if i != src]
perm.insert(dst, src)
return x.transpose(perm)
def matchaxis(sz, src, dst, x):
if core.get_aval(x) is core.abstract_unit:
return core.unit
if src == dst:
return x
elif type(src) == type(dst) == int:
return moveaxis(x, src, dst)
elif type(src) == int and dst is last:
return moveaxis(x, src, -1)
elif src is not_mapped and dst is not not_mapped:
return broadcast(x, sz, dst)
else:
raise ValueError((src, dst))
def bdim_at_front(x, bdim, size):
if core.get_aval(x) is core.abstract_unit:
return core.unit
if bdim is not_mapped:
return broadcast(x, size, 0)
else:
return moveaxis(x, bdim, 0)
def _promote_aval_rank(sz, aval):
if aval is core.abstract_unit:
return core.abstract_unit
else:
return ShapedArray((sz,) + aval.shape, aval.dtype)
def batch_jaxpr(jaxpr, size, batched, instantiate):
f = lu.wrap_init(core.jaxpr_as_fun(jaxpr))
f, batched_out = batched_traceable(f, size, batched, instantiate)
avals_in = [_promote_aval_rank(size, a) if b else a
for a, b in zip(jaxpr.in_avals, batched)]
in_pvals = [pe.PartialVal((aval, core.unit)) for aval in avals_in]
jaxpr_out, pvals_out, consts_out = pe.trace_to_jaxpr(f, in_pvals, instantiate=True)
avals_out, _ = unzip2(pvals_out)
jaxpr_out = core.TypedJaxpr(jaxpr_out, consts_out, avals_in, avals_out)
return jaxpr_out, batched_out()
@lu.transformation_with_aux
def batched_traceable(size, batched, instantiate, *vals):
in_dims = [0 if b else None for b in batched]
with new_master(BatchTrace) as master:
trace = BatchTrace(master, core.cur_sublevel())
ans = yield map(partial(BatchTracer, trace), vals, in_dims), {}
out_tracers = map(trace.full_raise, ans)
out_vals, out_dims = unzip2((t.val, t.batch_dim) for t in out_tracers)
del master, out_tracers
if type(instantiate) is bool:
instantiate = [instantiate] * len(out_vals)
out_vals = [moveaxis(x, d, 0) if d is not not_mapped and d != 0
else broadcast(x, size, 0) if d is not_mapped and inst else x
for x, d, inst in zip(out_vals, out_dims, instantiate)]
out_batched = [d is not not_mapped or inst
for d, inst in zip(out_dims, instantiate)]
yield out_vals, out_batched
|
jax-master
|
jax/interpreters/batching.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
|
jax-master
|
jax/interpreters/__init__.py
|
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import print_function
from contextlib import contextmanager
from collections import defaultdict, Counter, namedtuple
from functools import partial, wraps
import itertools as it
import operator as op
import string
import numpy as onp
import six
from .. import core
from ..core import Trace, Tracer
from ..util import unzip2, safe_map, safe_zip, curry
from ..abstract_arrays import ShapedArray
from .. import linear_util as lu
from . import partial_eval as pe
map = safe_map
zip = safe_zip
reduce = six.moves.reduce
def prod(xs):
xs = list(xs)
return reduce(op.mul, xs) if xs else 1
### main transformation functions
ShapeEnvs = namedtuple("ShapeEnvs", ["logical", "padded"])
shape_envs = ShapeEnvs({}, {}) # TODO(mattjj): make this a stack for efficiency
@contextmanager
def extend_shape_envs(logical_env, padded_env):
global shape_envs
new_logical = dict(it.chain(shape_envs.logical.items(), logical_env.items()))
new_padded = dict(it.chain(shape_envs.padded.items(), padded_env.items()))
shape_envs, prev = ShapeEnvs(new_logical, new_padded), shape_envs
yield
shape_envs = prev
def shape_as_value(expr):
if type(expr) is ShapeExpr:
return eval_shape_expr(shape_envs.logical, expr)
elif type(expr) is tuple and any(type(d) is Poly for d in expr):
return tuple(eval_dim_expr(shape_envs.logical, d) if type(d) is Poly else d
for d in expr)
else:
return expr
def padded_shape_as_value(expr):
if type(expr) is ShapeExpr:
return eval_shape_expr(shape_envs.padded, expr)
elif type(expr) is tuple and any(type(d) is Poly for d in expr):
return tuple(eval_dim_expr(shape_envs.padded, d) if type(d) is Poly else d
for d in expr)
else:
return expr
def mask_fun(fun, logical_env, padded_env, in_vals, shape_exprs):
with core.new_master(MaskTrace) as master:
fun, out_shapes = mask_subtrace(fun, master)
with extend_shape_envs(logical_env, padded_env):
out_vals = fun.call_wrapped(in_vals, shape_exprs)
del master
return out_vals, out_shapes()
@lu.transformation_with_aux
def mask_subtrace(master, in_vals, shape_exprs):
trace = MaskTrace(master, core.cur_sublevel())
in_tracers = [MaskTracer(trace, x, s).full_lower()
for x, s in zip(in_vals, shape_exprs)]
outs = yield in_tracers, {}
out_tracers = map(trace.full_raise, outs)
out_vals, out_shapes = unzip2((t.val, t.shape_expr) for t in out_tracers)
yield out_vals, out_shapes
### shape expressions
# Shape expressions model tuples of formal polynomials with integer
# coefficients. Here are the internal data structures we use to represent them.
#
# type ShapeExpr = [Poly]
# type Poly = Map Mon Int
# type Mon = Map Str Int
class ShapeExpr(tuple): # type ShapeExpr = [Poly]
def __str__(self):
return 'ShapeExpr({})'.format(', '.join(map(str, self)))
def __getitem__(self, idx):
if type(idx) is int:
return super(ShapeExpr, self).__getitem__(idx)
else:
return ShapeExpr(super(ShapeExpr, self).__getitem__(idx))
class Poly(Counter): # type Poly = Map Mon Int -- monomials to coeffs
def __mul__(p1, p2):
new_poly = Poly()
for (mon1, coeff1), (mon2, coeff2) in it.product(p1.items(), p2.items()):
mon = Mon(mon1 + mon2) # add monomials' id degrees
coeff = coeff1 * coeff2 # multiply integer coeffs
new_poly[mon] = new_poly.get(mon, 0) + coeff # accumulate coeffs
return new_poly
def __add__(p1, p2):
return Poly(Counter.__add__(p1, p2))
def __hash__(self):
return hash(tuple(self.items()))
def __str__(self):
return ' + '.join('{} {}'.format(v, k) if v != 1 else str(k)
for k, v in sorted(self.items())).strip()
class Mon(Counter): # type Mon = Map Id Int -- ids to degrees
def __hash__(self):
return hash(tuple(self.items()))
def __str__(self):
return ' '.join('{}**{}'.format(k, v) if v != 1 else str(k)
for k, v in sorted(self.items()))
def __lt__(self, other):
# sort by total degree, then lexicographically on indets
self_key = self.degree(), tuple(sorted(self))
other_key = other.degree(), tuple(sorted(other))
return self_key < other_key
def degree(self):
return sum(self.values())
def concrete_shape(shape):
if type(shape) is ShapeExpr:
return shape
else:
return ShapeExpr((Poly({Mon(): d}) for d in shape))
def eval_shape_expr(env, expr):
return tuple(eval_dim_expr(env, poly) for poly in expr)
def eval_dim_expr(env, poly):
terms = [mul(coeff, prod([pow(env[id], deg) for id, deg in mon.items()]))
for mon, coeff in poly.items()]
return sum(terms) if len(terms) > 1 else terms[0]
def pow(x, deg):
try:
deg = int(deg)
except:
return x ** deg
else:
return 1 if deg == 0 else x if deg == 1 else x ** deg
def mul(coeff, mon):
try:
coeff = int(coeff)
except:
return coeff * mon
else:
return 0 if coeff == 0 else mon if coeff == 1 else coeff * mon
def is_constant(poly):
try:
([], _), = poly.items()
return True
except (ValueError, TypeError):
return False
class ShapeError(Exception): pass
class ShapeSyntaxError(Exception): pass
# To denote some shape expressions (for annotations) we use a small language.
#
# data ShapeSpec = ShapeSpec [Dim]
# data Dim = Id PyObj
# | Lit Int
# | Mul Dim Dim
# | Add Dim Dim
# | MonomorphicDim
#
# We'll also make a simple concrete syntax for annotation. The grammar is
#
# shape_spec ::= '(' dims ')'
# dims ::= dim ',' dims | ''
# dim ::= str | int | dim '*' dim | dim '+' dim | '_'
#
# ShapeSpecs encode ShapeExprs but can have some monomorphic dims inside them,
# which must be replaced with concrete shapes when known.
class ShapeSpec(list):
def __str__(self):
return 'ShapeSpec({})'.format(', '.join(map(str, self)))
def finalize_spec(spec, shape):
return ShapeExpr(parse_lit(d) if e is monomorphic_dim else e
for e, d in zip(spec, shape))
def parse_spec(spec=''):
if not spec:
return ShapeSpec(())
if spec[0] == '(':
if spec[-1] != ')': raise ShapeSyntaxError(spec)
spec = spec[1:-1]
dims = map(parse_dim, spec.replace(' ', '').strip(',').split(','))
return ShapeSpec(dims)
def parse_dim(spec):
if '+' in spec:
terms = map(parse_dim, spec.split('+'))
return reduce(op.add, terms)
elif '*' in spec:
terms = map(parse_dim, spec.split('*'))
return reduce(op.mul, terms)
elif spec in digits:
return parse_lit(spec)
elif spec in identifiers:
return parse_id(spec)
elif spec == '_':
return monomorphic_dim
else:
raise ShapeSyntaxError(spec)
digits = frozenset(string.digits)
identifiers = frozenset(string.ascii_lowercase)
def parse_id(name): return Poly({Mon({name: 1}): 1})
def parse_lit(val_str): return Poly({Mon(): int(val_str)})
class MonomorphicDim(object):
def __str__(self): return '_'
monomorphic_dim = MonomorphicDim()
# Two convenient ways to provide shape annotations:
# 1. '(m, n)'
# 2. s_['m', 'n']
class S_(object):
def __getitem__(self, idx):
if type(idx) is tuple:
return parse_spec('(' + ','.join(map(str, idx)) + ')')
else:
return parse_spec(str(idx))
s_ = S_()
### automasking tracer machinery
class MaskTracer(Tracer):
__slots__ = ["val", "shape_expr"]
def __init__(self, trace, val, shape_expr):
self.trace = trace
self.val = val
self.shape_expr = shape_expr
@property
def aval(self):
return ShapedArray(self.shape_expr, self.val.dtype)
def is_pure(self):
return all(is_constant(poly) for poly in self.shape_expr)
def full_lower(self):
if self.is_pure():
return core.full_lower(self.val)
else:
return self
class MaskTrace(Trace):
def pure(self, val):
return MaskTracer(self, val, concrete_shape(onp.shape(val)))
def lift(self, val):
return MaskTracer(self, val, concrete_shape(onp.shape(val)))
def sublift(self, val):
return MaskTracer(self, val.val, val.shape_expr)
def process_primitive(self, primitive, tracers, params):
vals, shape_exprs = unzip2((t.val, t.shape_expr) for t in tracers)
if primitive in shape_parameterized_primitive_rules:
rule = shape_parameterized_primitive_rules[primitive]
out, out_shape = rule(shape_envs, vals, shape_exprs, **params)
else:
out_shape = shape_rules[primitive](shape_exprs, **params)
logical_shapes = map(partial(eval_shape_expr, shape_envs.logical), shape_exprs)
out = masking_rules[primitive](vals, logical_shapes, **params)
if not primitive.multiple_results:
return MaskTracer(self, out, out_shape)
else:
return map(partial(MaskTracer, self), out, out_shape)
def process_call(self, call_primitive, f, tracers, params):
raise NotImplementedError # TODO mask-of-jit
shape_parameterized_primitive_rules = {}
masking_rules = {}
shape_rules = {}
def defvectorized(prim):
shape_rules[prim] = vectorized_shape_rule
masking_rules[prim] = partial(vectorized_masking_rule, prim)
def vectorized_shape_rule(shape_exprs, **unused_params):
shape_expr, = shape_exprs
return shape_expr
def vectorized_masking_rule(prim, padded_vals, logical_shapes, **params):
del logical_shapes # Unused.
padded_val, = padded_vals
return prim.bind(padded_val, **params)
def defbinop(prim):
shape_rules[prim] = binop_shape_rule
masking_rules[prim] = partial(binop_masking_rule, prim)
def binop_shape_rule(shape_exprs):
x_shape_expr, y_shape_expr = shape_exprs
if x_shape_expr == y_shape_expr:
return x_shape_expr
elif not x_shape_expr:
return y_shape_expr
elif not y_shape_expr:
return x_shape_expr
else:
raise ShapeError
def binop_masking_rule(prim, padded_vals, logical_shapes):
del logical_shapes # Unused.
padded_x, padded_y = padded_vals
return prim.bind(padded_x, padded_y)
### definition-time (import-time) shape checker tracer machinery
def shapecheck(fun, in_shapes):
with core.new_master(ShapeCheckTrace) as master:
out_shapes = check_subtrace(fun, master).call_wrapped(in_shapes)
del master
return out_shapes
@lu.transformation
def check_subtrace(master, in_shapes):
trace = ShapeCheckTrace(master, core.cur_sublevel())
in_tracers = map(partial(ShapeCheckTracer, trace), in_shapes)
outs = yield in_tracers, {}
out_tracers = map(trace.full_raise, outs)
yield [t.shape_expr for t in out_tracers]
# TODO(mattjj): add dtypes?
class ShapeCheckTracer(Tracer):
__slots__ = ["shape_expr"]
def __init__(self, trace, shape_expr):
self.trace = trace
self.shape_expr = shape_expr
@property
def aval(self):
return ShapedArray(self.shape_expr, None)
def full_lower(self):
return self
class ShapeCheckTrace(Trace):
def pure(self, val):
return ShapeCheckTracer(self, concrete_shape(onp.shape(val)))
def lift(self, val):
return ShapeCheckTracer(self, concrete_shape(onp.shape(val)))
def sublift(self, val):
return ShapeCheckTracer(self, val.shape_expr)
def process_primitive(self, primitive, tracers, params):
shape_exprs = [t.shape_expr for t in tracers]
out_shape_expr = shape_rules[primitive](shape_exprs, **params)
return ShapeCheckTracer(self, out_shape_expr)
def process_call(self, call_primitive, f, tracers, params):
raise NotImplementedError # TODO check-of-jit
|
jax-master
|
jax/interpreters/masking.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from collections import namedtuple, defaultdict
from contextlib import contextmanager
import itertools as it
import operator as op
import threading
from absl import logging
import numpy as onp
import six
from six.moves import reduce
from ..config import flags
from .. import core
from .. import linear_util as lu
from ..abstract_arrays import (ConcreteArray, ShapedArray, array_types,
raise_to_shaped)
from ..util import partial, unzip2, concatenate, prod, safe_map
from ..lib import xla_bridge as xb
from .xla import aval_to_xla_shape, xla_destructure
from .batching import broadcast, not_mapped
from . import batching
from . import partial_eval as pe
from . import xla
from . import ad
FLAGS = flags.FLAGS
_map = safe_map
### util
def identity(x): return x
def shard_args(backend, devices, assignments, axis_size, tuple_args, args):
"""Shard each argument data array along its leading axis.
Args:
backend: the platform to be used
devices: list of Devices mapping replica index to a physical device.
assignments: list of integers with the same length as `devices` mapping
replica index to an index along the leading axis (i.e. a shard).
axis_size: int, size of the leading axis to be sharded.
args: a sequence of JaxTypes representing arguments to be sharded along
their leading axes and placed on `devices`.
Returns:
A list of device buffers with the same length as `devices` indexed by
replica number, so that the nth element is the argument to be passed to the
nth replica.
"""
nargs, nrep = len(args), len(devices)
buffers = [[None] * nargs for _ in range(nrep)]
for a, arg in enumerate(args):
# The shard_arg_handlers allow an extensible set of types to be sharded, but
# inline handling for ShardedDeviceArray as a special case for performance
if type(arg) is ShardedDeviceArray:
if nrep == len(arg.device_buffers):
# The argument is already prepared for the right number of replicas, so
# we just ensure that buf[r] is on devices[r] for each replica index r
# TODO(mattjj): compared to the other case, this logic has less looping
# but could incur more device-to-device data movement
for r, buf in enumerate(arg.device_buffers):
buffers[r][a] = buf if buf.device() == devices[r] else buf.copy_to_device(devices[r])
else:
# The argument is prepared for a different number of replicas, so for
# each of our replica indices we check if there's already a buffer with
# the correct logical assignment on the correct device, and if not just
# copy one of them
prev_assignments = assign_shards_to_replicas(len(arg.device_buffers), axis_size)
candidates = defaultdict(list)
for r, buf in enumerate(arg.device_buffers):
candidates[prev_assignments[r]].append(buf)
for r in range(nrep):
for buf in candidates[assignments[r]]:
if buf.device() == devices[r]:
buffers[r][a] = buf
break
else:
buffers[r][a] = buf.copy_to_device(devices[r])
else:
bufs = shard_arg_handlers[type(arg)](arg, devices, assignments)
for r, buf in enumerate(bufs):
buffers[r][a] = buf
if tuple_args:
buffers = [[xla.make_tuple(bufs, devices[r], backend)]
for r, bufs in enumerate(buffers)]
return buffers
shard_arg_handlers = {}
shard_arg_handlers[core.Unit] = \
lambda x, devices, _: [xla.device_put(core.unit, d) for d in devices]
def _shard_array(x, devices, assignments):
nrep = len(devices)
return (xla.device_put(x[assignments[r]], devices[r]) for r in range(nrep))
for _t in array_types:
shard_arg_handlers[_t] = _shard_array
def _shard_device_array(x, devices, assignments):
nrep = len(devices)
xs = x._unstack()
return (xla.device_put(xs[assignments[r]], devices[r])
for r in range(nrep))
shard_arg_handlers[xla.DeviceArray] = _shard_device_array
def shard_aval(size, aval):
try:
return shard_aval_handlers[type(aval)](size, aval)
except KeyError:
raise TypeError("No shard_aval handler for type: {}".format(type(aval)))
shard_aval_handlers = {}
shard_aval_handlers[core.AbstractUnit] = lambda size, x: x
def _shard_abstract_array(size, x):
if x.shape[0] != size:
raise ValueError("Axis size {} does not match leading dimension of "
"shape {}".format(size, x.shape))
return ShapedArray(x.shape[1:], x.dtype)
shard_aval_handlers[ShapedArray] = _shard_abstract_array
def aval_to_result_handler(size, nrep, aval):
try:
return pxla_result_handlers[type(aval)](size, nrep, aval)
except KeyError:
raise TypeError("No pxla_result_handler for type: {}".format(type(aval)))
pxla_result_handlers = {}
pxla_result_handlers[core.AbstractUnit] = lambda *_: lambda _: core.unit
def array_result_handler(size, nrep, aval):
full_aval = ShapedArray((size,) + aval.shape, aval.dtype)
return partial(ShardedDeviceArray, full_aval)
pxla_result_handlers[ShapedArray] = array_result_handler
pxla_result_handlers[ConcreteArray] = array_result_handler
def assign_shards_to_replicas(nrep, size):
"""Produce a mapping from replica id to shard index.
Args:
nrep: int, number of replicas (a computation-dependent value).
size: int, size of the data array axis being sharded.
Returns:
A tuple of integers of length nrep in which the elements take on values from
0 to size-1. Replica n is assgined shard data_array[assignments[n]].
"""
groupsize, ragged = divmod(nrep, size)
assert not ragged
indices = onp.tile(onp.arange(size)[:, None], (1, groupsize))
return tuple(indices.ravel())
### applying parallel primitives in op-by-op Python dispatch
# There are at least two cases where we might want to evaluate a parallel
# primitive dispatched from Python, rather than being staged out:
# 1. axis_size = psum(1, 'axis_name'),
# 2. to enable an implicit outermost pmap-like context for multi-host
# multi-controller SPMD programs.
# In each case, we can't rely on any data dependence on a pmap trace; instead we
# need some dynamic context, basically modeling the axis name environment stack.
# To handle the former case, we don't need to communicate at all; we instead
# have a table of parallel_pure_rules. To handle the latter case, we'll have a
# globally-scoped root environment frame and compile and execute a single-op
# XLA collective.
class DynamicAxisEnvFrame(object):
__slots__ = ["name", "pmap_trace", "hard_size", "soft_trace", "soft_size"]
def __init__(self, name, pmap_trace, hard_size):
self.name = name
self.pmap_trace = pmap_trace
self.hard_size = hard_size
self.soft_trace = None
self.soft_size = None
class DynamicAxisEnv(list):
def __contains__(self, axis_name):
return axis_name in (frame.name for frame in self)
def __getitem__(self, axis_name):
if axis_name not in self:
raise NameError("unbound axis name: {}".format(axis_name))
for frame in reversed(self):
if frame.name == axis_name:
return frame
else:
assert False
@property
def sizes(self):
return tuple(frame.hard_size for frame in self)
@property
def nreps(self):
return prod(frame.hard_size for frame in self)
class _ThreadLocalState(threading.local):
def __init__(self):
self.dynamic_axis_env = DynamicAxisEnv()
_thread_local_state = _ThreadLocalState()
@contextmanager
def extend_dynamic_axis_env(axis_name, pmap_trace, hard_size):
dynamic_axis_env = _thread_local_state.dynamic_axis_env
dynamic_axis_env.append(DynamicAxisEnvFrame(axis_name, pmap_trace, hard_size))
try:
yield
finally:
dynamic_axis_env.pop()
def unmapped_device_count(backend=None):
dynamic_axis_env = _thread_local_state.dynamic_axis_env
mapped = prod(frame.hard_size for frame in dynamic_axis_env)
unmapped, ragged = divmod(xb.device_count(backend), mapped)
assert not ragged and unmapped > 0
return unmapped
def apply_parallel_primitive(prim, *args, **params):
# This is the op-by-op version of applying a collective primitive, like a psum
# that doesn't have a data dependence on the argument of a pmap function. In
# particular, this code gets hit when we write `axis_size = psum(1, 'i')`. We
# look up information in the dynamic axis env.
dynamic_axis_env = _thread_local_state.dynamic_axis_env
axis_name = params.pop('axis_name')
logical_size = lambda frame: frame.hard_size * (frame.soft_size or 1)
if isinstance(axis_name, (list, tuple)):
shape = tuple(logical_size(dynamic_axis_env[name]) for name in axis_name)
else:
shape = (logical_size(dynamic_axis_env[axis_name]),)
return parallel_pure_rules[prim](*args, shape=shape, **params)
parallel_pure_rules = {}
def axis_index(axis_name):
dynamic_axis_env = _thread_local_state.dynamic_axis_env
frame = dynamic_axis_env[axis_name]
sizes = dynamic_axis_env.sizes[:dynamic_axis_env.index(frame)+1]
nreps = dynamic_axis_env.nreps
dummy_arg = frame.pmap_trace.pure(core.unit)
if frame.soft_trace:
dummy_arg = frame.soft_trace.pure(dummy_arg)
return axis_index_p.bind(dummy_arg, nreps=nreps, sizes=sizes,
soft_size=frame.soft_size, axis_name=axis_name)
def _axis_index_partial_eval(trace, _, **params):
# This partial_eval rule adds the axis_index primitive into the jaxpr formed
# during pmap lowering. It is like the standard JaxprTrace.process_primitive
# rule except that we don't attempt to lower out of the trace.
out_aval = ShapedArray((), onp.int32)
out_tracer = pe.JaxprTracer(trace, pe.PartialVal((out_aval, core.unit)), None)
eqn = pe.new_eqn_recipe([], [out_tracer], axis_index_p, (), params)
out_tracer.recipe = eqn
return out_tracer
def _axis_index_translation_rule(c, nreps, sizes, soft_size, axis_name):
div = c.Constant(onp.array(nreps // prod(sizes), dtype=onp.uint32))
mod = c.Constant(onp.array(sizes[-1], dtype=onp.uint32))
unsigned_index = c.Rem(c.Div(c.ReplicaId(), div), mod)
return c.ConvertElementType(unsigned_index, xb.dtype_to_etype(onp.int32))
axis_index_p = core.Primitive('axis_index')
xla.translations[axis_index_p] = _axis_index_translation_rule
pe.custom_partial_eval_rules[axis_index_p] = _axis_index_partial_eval
### lazy device-memory persistence and result handling
class ShardedDeviceValue(xla.DeviceValue):
def _check_if_deleted(self):
if self.device_buffers is None:
raise ValueError("ShardedDeviceValue has been deleted.")
def block_until_ready(self):
self._check_if_deleted()
for buf in self.device_buffers:
buf.block_host_until_ready()
return self
class ShardedDeviceArray(ShardedDeviceValue, xla.DeviceArray):
"""A ShardedDeviceArray is an ndarray sharded across devices.
The purpose of a ShardedDeviceArray is to reduce the number of transfers when
executing replicated computations, by allowing results to persist on the
devices that produced them. That way dispatching a similarly replicated
computation that consumes the same sharded memory layout does not incur any
transfers.
A ShardedDeviceArray represents one logical ndarray value, and simulates the
behavior of an ndarray so that it can be treated by user code as an ndarray;
that is, it is only an optimization to reduce transfers.
The number of device buffers underlying a ShardedDeviceArray instance is equal
to the number of replicas of the computation that produced it. Each buffer
represents a shard of the original array, meaning a slice along its leading
axis. These component buffers reside on distinct devices, but need not
represent distinct logical shards. The correspondence can be computed with
the assign_shards_to_replicas function.
"""
__slots__ = ["device_buffers", "axis_size"]
_collect = staticmethod(onp.stack)
def __init__(self, aval, device_buffers):
self.aval = aval
self.device_buffers = device_buffers
self.axis_size = aval.shape[0]
self._npy_value = None
if not core.skip_checks:
assert type(aval) is ShapedArray
def _ids(self):
num_bufs = len(self.device_buffers)
assignments = assign_shards_to_replicas(num_bufs, self.axis_size)
_, ids = onp.unique(assignments, return_index=True)
return ids
def copy_to_host_async(self):
if self._npy_value is None:
for buf in self.device_buffers:
buf.copy_to_host_async()
def delete(self):
for buf in self.device_buffers:
buf.delete()
self.device_buffers = None
self._npy_value = None
@property
def _value(self):
if self._npy_value is None:
ids = self._ids()
self.copy_to_host_async()
self._npy_value = self._collect([self.device_buffers[i].to_py() for i in ids])
return self._npy_value
def __getitem__(self, idx):
if self._npy_value is None and type(idx) is int:
ids = self._ids()
device_buffer = self.device_buffers[ids[idx]]
aval = ShapedArray(self.aval.shape[1:], self.aval.dtype)
handler = xla.aval_to_result_handler(None, aval)
return handler(device_buffer)
else:
return super(ShardedDeviceArray, self).__getitem__(idx)
# This handler code is effectively dead because we in-lined it in shard_args for
# performance reasons.
def _shard_sharded_device_array(x, devices, assignments):
n = len(devices)
if n == len(x.device_buffers):
return (b if b.device() == devices[r] else b.copy_to_device(devices[r])
for r, b in enumerate(x.device_buffers))
else:
return (xla.device_put(x[assignments[r]], devices[r]) for r in range(n))
shard_arg_handlers[ShardedDeviceArray] = _shard_sharded_device_array
core.pytype_aval_mappings[ShardedDeviceArray] = ConcreteArray
xla.device_put_handlers[ShardedDeviceArray] = xla._device_put_array
xla.pytype_aval_mappings[ShardedDeviceArray] = lambda x: x.aval
xla.canonicalize_dtype_handlers[ShardedDeviceArray] = identity
xb.register_constant_handler(ShardedDeviceArray, xla._device_array_constant_handler)
class ChunkedDeviceArray(ShardedDeviceArray):
__slots__ = []
_collect = staticmethod(onp.concatenate)
def __init__(self, axis_size, aval, device_buffers):
super(ChunkedDeviceArray, self).__init__(aval, device_buffers)
self.axis_size = axis_size
def __getitem__(self, idx):
return xla.DeviceArray.__getitem__(self, idx)
shard_arg_handlers[ChunkedDeviceArray] = _shard_array
core.pytype_aval_mappings[ChunkedDeviceArray] = ConcreteArray
xla.device_put_handlers[ChunkedDeviceArray] = xla._device_put_array
xla.pytype_aval_mappings[ChunkedDeviceArray] = lambda x: x.aval
xla.canonicalize_dtype_handlers[ChunkedDeviceArray] = identity
xb.register_constant_handler(ChunkedDeviceArray,
xla._device_array_constant_handler)
### the xla_pmap primitive and its rules are comparable to xla_call in xla.py
def xla_pmap_impl(fun, *args, **params):
axis_name = params.pop('axis_name')
axis_size = params.pop('axis_size')
devices = params.pop('devices')
backend = params.pop('backend', None)
assert not params
abstract_args = map(xla.abstractify, args)
compiled_fun = parallel_callable(fun, backend, axis_name, axis_size, devices,
*abstract_args)
return compiled_fun(*args)
@lu.cache
def parallel_callable(fun, backend, axis_name, axis_size, devices, *avals):
if devices is not None and len(devices) == 0:
raise ValueError("'devices' argument to pmap must be non-empty, or None.")
if devices:
global_axis_size = len(devices)
elif xb.host_count() > 1:
# TODO(skye): relax this constraint or provide functionality for
# automatically passing appropriate `devices`.
if axis_size != xb.local_device_count():
raise ValueError(
"On multi-host platforms, the input to pmapped functions must have "
"leading axis size equal to the number of local devices if no "
"`devices` argument is specified. Got axis_size=%d, "
"num_local_devices=%d" % (axis_size, xb.local_device_count()))
global_axis_size = xb.device_count()
else:
global_axis_size = axis_size
log_priority = logging.WARNING if FLAGS.jax_log_compiles else logging.DEBUG
logging.log(log_priority,
"Compiling {} for {} devices with args {}.".format(
fun.__name__, global_axis_size, avals))
if devices:
local_devices = [d for d in devices if d.host_id == xb.host_id()]
assert len(local_devices) > 0
else:
local_devices = None
@lu.wrap_init
def dynamic_fun(dummy, *args):
with extend_dynamic_axis_env(axis_name, dummy.trace, global_axis_size):
return fun.call_wrapped(*args)
avals = tuple(map(partial(shard_aval, axis_size), avals))
pvals = [pe.PartialVal((aval, core.unit)) for aval in avals]
pval = pe.PartialVal([core.abstract_unit, core.unit]) # dummy value for axis env
with core.new_master(pe.StagingJaxprTrace, True) as master:
jaxpr, (out_pvals, consts, env) = pe.trace_to_subjaxpr(
dynamic_fun, master, False).call_wrapped([pval] + pvals)
jaxpr.invars = jaxpr.invars[1:] # ignore dummy
assert not env
del master
out_pvs, out_consts = unzip2(out_pvals)
# TODO(skye,mattjj): allow more collectives on multi-host as we test them, but
# for now raise an error
if devices is not None:
is_multi_host_pmap = any(d.host_id != xb.host_id() for d in devices)
else:
is_multi_host_pmap = xb.host_count() > 1
if is_multi_host_pmap:
used_collectives = set(xla.jaxpr_collectives(jaxpr))
if not used_collectives.issubset(multi_host_supported_collectives):
msg = "using collectives that aren't supported for multi-host: {}"
raise TypeError(msg.format(", ".join(map(str, used_collectives))))
if all(pv is None for pv in out_pvs):
# When the output doesn't depend on the input we don't need to compile an
# XLA computation at all; we handle this as a special case so we can stage
# out multi-replica XLA computations regardless of the hardware available.
# The 'None' values here are just dummies we know will be ignored.
handlers = [_pval_to_result_handler(axis_size, None, pval, local_devices,
backend)
for pval in out_pvals]
results = [handler(None) for handler in handlers]
return lambda *_: results
jaxpr_replicas = xla.jaxpr_replicas(jaxpr)
num_local_replicas = axis_size * jaxpr_replicas
num_global_replicas = global_axis_size * jaxpr_replicas
axis_env = xla.AxisEnv(num_global_replicas, [axis_name], [global_axis_size], devices)
tuple_args = len(avals) > 100 # pass long arg lists as tuple for TPU
c = xb.make_computation_builder("pmap_{}".format(fun.__name__))
xla_consts = _map(c.Constant, consts)
xla_args = xla._xla_callable_args(c, avals, tuple_args)
out_nodes = xla.jaxpr_subcomp(c, jaxpr, backend, axis_env, xla_consts, (), *xla_args)
built = c.Build(c.Tuple(*out_nodes))
if devices is None:
if num_global_replicas > xb.device_count(backend):
msg = ("compiling computation that requires {} replicas, but only {} XLA "
"devices are available")
raise ValueError(msg.format(num_global_replicas, xb.device_count(backend)))
device_assignment = None
else:
if num_local_replicas != len(local_devices):
local_devices_str = ", ".join(map(str, local_devices))
raise ValueError(
"Leading axis size of input to pmapped function must equal the "
"number of local devices passed to pmap. Got axis_size=%d, "
"num_local_devices=%d.\n(Local devices passed to pmap: %s)"
% (axis_size, len(local_devices), local_devices_str))
if num_global_replicas != len(devices):
raise ValueError("compiling computation that requires %s replicas, "
"but %s devices were specified"
% (num_global_replicas, len(devices)))
device_assignment = tuple(d.id for d in devices)
compiled = built.Compile(
compile_options=xb.get_compile_options(num_global_replicas, device_assignment),
backend=xb.get_backend(backend))
handle_args = partial(shard_args, backend, compiled.local_devices(),
assign_shards_to_replicas(num_local_replicas, axis_size),
axis_size, tuple_args)
handle_outs = _pvals_to_results_handler(axis_size, num_local_replicas,
out_pvals, compiled.local_devices(),
backend)
return partial(execute_replicated, compiled, backend, num_local_replicas, handle_args, handle_outs)
multi_host_supported_collectives = set()
class ResultToPopulate(object): pass
result_to_populate = ResultToPopulate()
def _pvals_to_results_handler(size, nrep, out_pvals, devices, backend):
nouts = len(out_pvals)
handlers = [_pval_to_result_handler(size, nrep, pval, devices, backend)
for pval in out_pvals]
def handler(out_bufs):
buffers = [[result_to_populate] * nrep for _ in range(nouts)]
for r, tuple_buf in enumerate(out_bufs):
for i, buf in enumerate(tuple_buf.destructure()):
buffers[i][r] = buf
assert not any(buf is result_to_populate for bufs in buffers
for buf in bufs)
return [h(bufs) for h, bufs in zip(handlers, buffers)]
return handler
def replicate(val, axis_size, nrep, devices=None, backend=None):
"""Replicates ``val`` across multiple devices.
Args:
val: the value to be replicated.
axis_size: the length of the output, i.e. the logical number of replicas to
create. Usually equal to `nrep`, but in the case of nested pmaps, `nrep` may
be a multiple of `axis_size`.
nrep: the number of replicas to create. If ``devices`` is set, must be equal
to ``len(devices)``.
devices: the devices to replicate across. If None, ``nrep`` will be used to
generate a default device assignment.
backend: string specifying which backend to use.
Returns:
A ShardedDeviceArray of length `axis_size` where each shard is equal to
``val``.
"""
device_count = (len(devices) if devices else xb.local_device_count())
if nrep > device_count:
msg = ("Cannot replicate across %d replicas because only %d local devices "
"are available." % (nrep, device_count))
if devices:
msg += (" (local devices = %s)"
% ", ".join(map(str, devices)) if devices else str(None))
raise ValueError(msg)
if devices is None:
assert nrep is not None
devices = xb.get_backend(backend).get_default_device_assignment(nrep)
assert nrep == len(devices)
aval = xla.abstractify(val)
aval = ShapedArray((axis_size,) + aval.shape, aval.dtype)
device_buffers = [xla.device_put(val, d) for d in devices]
return ShardedDeviceArray(aval, device_buffers)
def _pval_to_result_handler(axis_size, nrep, pval, devices, backend):
if devices:
assert all(d.host_id == xb.host_id(backend) for d in devices)
pv, const = pval
if pv is None:
if nrep is None:
nrep = axis_size
# If 'const' is a ShardedDeviceArray, it must have come from a pmap nested
# inside the one we're currently evaluating, and we should replicate
# 'const' across the total number of devices needed. We don't necessarily
# know the nested pmap's axis_size (e.g. the jaxpr for
# pmap(pmap(lambda x: 3)) is trivial, with no pmaps), but we can use the
# axis size of the output 'const'.
# TODO: we might be doing unnecessary device transfers in the inner pmap.
if isinstance(const, ShardedDeviceArray):
nrep *= len(const)
bcast_const = (core.unit if const is core.unit
else replicate(const, axis_size, nrep, devices, backend))
return lambda _: bcast_const
else:
return aval_to_result_handler(axis_size, nrep, pv)
def execute_replicated(compiled, backend, nrep, in_handler, out_handler, *args):
if nrep > xb.device_count(backend):
msg = ("executing pmap computation that requires {} replicas, but only {} "
"XLA devices are available")
raise ValueError(msg.format(nrep, xb.device_count(backend)))
input_bufs = in_handler(args)
out_bufs = compiled.ExecutePerReplica(list(input_bufs))
return out_handler(out_bufs)
xla_pmap_p = core.Primitive('xla_pmap')
xla_pmap_p.multiple_results = True
xla_pmap = partial(core.call_bind, xla_pmap_p)
xla_pmap_p.def_custom_bind(xla_pmap)
xla_pmap_p.def_impl(xla_pmap_impl)
def _pmap_translation_rule(c, jaxpr, axis_env, const_nodes, freevar_nodes,
in_nodes, axis_name, axis_size, devices, backend=None):
# We in-line here rather than generating a Call HLO as in the xla_call
# translation rule just because the extra tuple stuff is a pain.
if axis_env.devices is not None or (axis_env.names and devices is not None):
raise ValueError("Nested pmaps with explicit devices argument.")
new_env = xla.extend_axis_env(axis_env, axis_name, axis_size)
in_nodes_sharded = list(map(partial(_xla_shard, c, new_env), in_nodes))
sharded_outs = xla.jaxpr_subcomp(c, jaxpr, backend, new_env, const_nodes,
freevar_nodes, *in_nodes_sharded)
outs = [_xla_unshard(c, new_env, shard) for shard in sharded_outs]
return c.Tuple(*outs)
xla.call_translations[xla_pmap_p] = _pmap_translation_rule
ad.primitive_transposes[xla_pmap_p] = partial(ad.map_transpose, xla_pmap_p)
pe.map_primitives.add(xla_pmap_p)
def _xla_shard(c, axis_env, x):
xla_shape = c.GetShape(x)
if xla_shape.is_tuple():
assert not xla_shape.tuple_shapes()
return x
else:
dims = list(xla_shape.dimensions())
zero = c.Constant(onp.zeros((), dtype=onp.uint32))
idxs = [_unravel_index(c, axis_env)] + [zero] * (len(dims) - 1)
return c.Reshape(c.DynamicSlice(x, idxs, [1] + dims[1:]), None, dims[1:])
# TODO(b/110096942): more efficient gather
def _xla_unshard(c, axis_env, x):
xla_shape = c.GetShape(x)
if xla_shape.is_tuple():
assert not xla_shape.tuple_shapes()
return x
else:
dims = list(xla_shape.dimensions())
padded = c.Broadcast(c.Constant(onp.array(0, xla_shape.numpy_dtype())),
[axis_env.sizes[-1]] + dims)
zero = c.Constant(onp.zeros((), dtype=onp.uint32))
idxs = [_unravel_index(c, axis_env)] + [zero] * len(dims)
padded = c.DynamicUpdateSlice(padded, c.Reshape(x, None, [1] + dims), idxs)
return c.CrossReplicaSum(padded, xla.axis_groups(axis_env, axis_env.names[-1]))
def _unravel_index(c, axis_env):
div = c.Constant(onp.array(axis_env.nreps // prod(axis_env.sizes), onp.uint32))
mod = c.Constant(onp.array(axis_env.sizes[-1], onp.uint32))
return c.Rem(c.Div(c.ReplicaId(), div), mod)
### soft_pmap axis split transformation
# To allow pmap to map over logical axes larger than the number of XLA devices
# available, we use a transformation that effectively simulates having more
# devices in software. The strategy is to split the mapped axis into two axes,
# one to be hardware-mapped and the other to be software-mapped. Thus the
# transformation rewrites the function to be mapped so that it accepts a new
# leading axis (the software-mapped axis), and so that collectives in the
# original function correspond to both device-local operations and collective
# communication operations across hardware devices that implement the original
# logical semantics.
@lu.transformation
def split_axis(axis_name, chunk_size, *args):
with core.new_master(SplitAxisTrace) as master:
trace = SplitAxisTrace(master, core.cur_sublevel())
in_tracers = list(map(partial(SplitAxisTracer, trace, axis_name), args))
with add_chunk_to_axis_env(axis_name, trace, chunk_size):
outs = yield in_tracers, {}
out_tracers = list(map(trace.full_raise, outs))
out_vals, out_names = unzip2((t.val, t.axis_name) for t in out_tracers)
del master, out_tracers
out_vals = [broadcast(x, chunk_size, 0) if d is not_mapped else x
for x, d in zip(out_vals, out_names)]
yield out_vals
@lu.transformation_with_aux
def split_axis_subtrace(master, names, *vals):
trace = SplitAxisTrace(master, core.cur_sublevel())
outs = yield list(map(partial(SplitAxisTracer, trace), names, vals)), {}
out_tracers = list(map(trace.full_raise, outs))
out_vals, out_names = unzip2((t.val, t.axis_name) for t in out_tracers)
yield out_vals, out_names
@contextmanager
def add_chunk_to_axis_env(axis_name, soft_trace, soft_size):
dynamic_axis_env = _thread_local_state.dynamic_axis_env
dynamic_axis_env[axis_name].soft_trace = soft_trace
dynamic_axis_env[axis_name].soft_size = soft_size
yield
dynamic_axis_env[axis_name].soft_trace = None
dynamic_axis_env[axis_name].soft_size = None
class SplitAxisTracer(core.Tracer):
def __init__(self, trace, axis_name, val):
self.trace = trace
self.axis_name = axis_name
self.val = val
@property
def aval(self):
aval = raise_to_shaped(core.get_aval(self.val))
if self.axis_name is not_mapped:
return aval
else:
return ShapedArray(aval.shape[1:], aval.dtype)
def full_lower(self):
if self.axis_name is not_mapped:
return core.full_lower(self.val)
else:
return self
class SplitAxisTrace(core.Trace):
def pure(self, val):
return SplitAxisTracer(self, not_mapped, val)
def lift(self, val):
return SplitAxisTracer(self, not_mapped, val)
def sublift(self, val):
return SplitAxisTracer(self, val.axis_name, val.val)
def process_primitive(self, primitive, tracers, params):
vals_in, names_in = unzip2((t.val, t.axis_name) for t in tracers)
if primitive is axis_index_p:
dummy, = vals_in
hard_idx = primitive.bind(dummy, **params)
val_out = hard_idx * params['soft_size'] + onp.arange(params['soft_size'])
return SplitAxisTracer(self, params['axis_name'], val_out)
elif all(axis_name is not_mapped for axis_name in names_in):
return primitive.bind(*vals_in, **params)
else:
name, = set(n for n in names_in if n is not not_mapped)
if primitive in xla.parallel_translations:
# if it's a pmap collective primitive, do something special
if name == params['axis_name']:
# if the name matches this tracer's name, apply the split_axis rule
try:
rule = split_axis_rules[primitive]
except KeyError:
msg = "split_axis for {} not implemented. Open a feature request!"
raise NotImplementedError(msg.format(primitive))
which_mapped = [n is not not_mapped for n in names_in]
val_out, is_mapped = rule(vals_in, which_mapped, **params)
name_out = name if is_mapped else not_mapped
return SplitAxisTracer(self, name_out, val_out)
else:
# if not, bind the primitive without any processing
val_out = primitive.bind(*vals_in, **params)
return SplitAxisTracer(self, name, val_out)
else:
# if it's not a pmap collective primitive, act just like batching
rule = batching.get_primitive_batcher(primitive)
axes_in = [n if n is not_mapped else 0 for n in names_in]
val_out, axis_out = rule(vals_in, axes_in, **params)
def new_tracer(x, a):
if a is not_mapped:
return SplitAxisTracer(self, not_mapped, x)
else:
return SplitAxisTracer(self, name, batching.moveaxis(x, a, 0))
if primitive.multiple_results:
return [new_tracer(x, a) for x, a in zip(val_out, axis_out)]
else:
return new_tracer(val_out, axis_out)
def process_call(self, call_primitive, f, tracers, params):
assert call_primitive.multiple_results
if call_primitive in pe.map_primitives:
return self.process_map(call_primitive, f, tracers, params)
else:
vals, names = unzip2((t.val, t.axis_name) for t in tracers)
if all(name is not_mapped for name in names):
return call_primitive.bind(f, *vals, **params)
else:
f, names_out = split_axis_subtrace(f, self.master, names)
vals_out = call_primitive.bind(f, *vals, **params)
return [SplitAxisTracer(self, a, x) for a, x in zip(names_out(), vals_out)]
def process_map(self, map_primitive, f, tracers, params):
vals, names = unzip2((t.val, t.axis_name) for t in tracers)
if all(name is not_mapped for name in names):
return map_primitive.bind(f, *vals, **params)
else:
# because the map primitive maps over leading axes, we need to transpose
# the software-mapped axis on any mapped arguments to be the second axis;
# then we call the map primitive and resume the trace under the call
vals_trans = [batching.moveaxis(x, 0, 1) if d is not not_mapped else x
for x, d in zip(vals, names)]
f, names_out = split_axis_subtrace(f, self.master, names)
vals_out_trans = map_primitive.bind(f, *vals_trans, **params)
vals_out = [batching.moveaxis(x, 1, 0) if d is not not_mapped else x
for x, d in zip(vals_out_trans, names_out())]
return [SplitAxisTracer(self, a, x) for a, x in zip(names_out(), vals_out)]
def post_process_call(self, call_primitive, out_tracer, params):
val, name = out_tracer.val, out_tracer.axis_name
master = self.master
def todo(x):
trace = SplitAxisTrace(master, core.cur_sublevel())
return SplitAxisTracer(trace, name, x)
return val, todo
split_axis_rules = {}
|
jax-master
|
jax/interpreters/pxla.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from functools import partial
import warnings
import numpy as onp
import six
from six.moves import reduce
from .. import core
from .. import linear_util as lu
from ..core import Trace, Tracer, Primitive, new_master
from ..abstract_arrays import ShapedArray, ConcreteArray, raise_to_shaped
from ..util import safe_map, safe_zip, unzip2, unzip3, partialmethod, prod
from ..lib import xla_bridge as xb
from . import partial_eval as pe
from . import batching
from . import pxla
map = safe_map
zip = safe_zip
def identity(x): return x
### papply
def papply(fun, name, in_vals, axis_size):
# this function is for testing purposes, so we drop the out_axis
fun, _ = papply_transform(fun, name, axis_size)
return fun.call_wrapped(*in_vals)
@lu.transformation_with_aux
def papply_transform(name, axis_size, *args):
with new_master(PapplyTrace) as master:
trace = PapplyTrace(master, core.cur_sublevel())
in_tracers = map(partial(PapplyTracer, trace, name, axis_size, axis=0), args)
outs = yield in_tracers, {}
out_tracers = map(trace.full_raise, outs)
out_vals, out_axes = unzip2((t.val, t.axis) for t in out_tracers)
del master, out_tracers
yield out_vals, out_axes
@lu.transformation_with_aux
def papply_subtrace(master, name, axis_size, axes, *vals):
trace = PapplyTrace(master, core.cur_sublevel())
outs = yield map(partial(PapplyTracer, trace, name, axis_size), vals, axes), {}
out_tracers = map(trace.full_raise, outs)
out_vals, out_axes = unzip2((t.val, t.axis) for t in out_tracers)
yield out_vals, out_axes
# TODO(mattjj); use a special sentinel type rather than None
NotSharded = type(None)
not_sharded = None
class PapplyTracer(Tracer):
def __init__(self, trace, name, axis_size, val, axis):
self.trace = trace
self.name = name
self.axis_size = axis_size
self.val = val
self.axis = axis
@property
def aval(self):
aval = raise_to_shaped(core.get_aval(self.val))
if self.axis is not_sharded:
return aval
else:
if aval is core.abstract_unit:
return aval
elif type(aval) is ShapedArray:
assert 0 <= self.axis < aval.ndim + 1
new_shape = list(aval.shape)
new_shape.insert(self.axis, self.axis_size)
return ShapedArray(tuple(new_shape), aval.dtype)
else:
raise TypeError(aval)
def full_lower(self):
if self.axis is not_sharded:
return core.full_lower(self.val)
else:
return self
class PapplyTrace(Trace):
def pure(self, val):
return PapplyTracer(self, None, None, val, not_sharded)
def lift(self, val):
return PapplyTracer(self, None, None, val, not_sharded)
def sublift(self, val):
return PapplyTracer(self, val.name, val.axis_size, val.val, val.axis)
def process_primitive(self, primitive, tracers, params):
names, vals, axes = unzip3((t.name, t.val, t.axis) for t in tracers)
if all(axis is not_sharded for axis in axes):
return primitive.bind(*vals, **params)
else:
name, = {n for n in names if n is not None}
size, = {t.axis_size for t in tracers if t.axis_size is not None}
rule = papply_primitive_rules[primitive]
val_out, axis_out = rule(name, size, vals, axes, **params)
return PapplyTracer(self, name, size, val_out, axis_out)
def process_call(self, call_primitive, f, tracers, params):
if call_primitive in pe.map_primitives:
return self.process_map(call_primitive, f, tracers, params)
names, vals, axes = unzip3((t.name, t.val, t.axis) for t in tracers)
if all(axis is not_sharded for axis in axes):
return call_primitive.bind(f, *vals, **params)
else:
name, = {n for n in names if n is not None}
size, = {t.axis_size for t in tracers if t.axis_size is not None}
f_papply, axes_out = papply_subtrace(f, self.master, name, size, axes)
vals_out = call_primitive.bind(f_papply, *vals, **params)
return [PapplyTracer(self, name, size, x, a)
for x, a in zip(vals_out, axes_out())]
def post_process_call(self, call_primitive, out_tracer):
t = out_tracer
name, val, axis, size = t.name, t.val, t.axis, t.axis_size
master = self.master
def todo(x):
trace = PapplyTrace(master, core.cur_sublevel())
return PapplyTracer(trace, name, size, x, axis)
return val, todo
def process_map(self, map_primitive, f, tracers, params):
raise NotImplementedError # TODO(mattjj,frostig)
papply_primitive_rules = {}
|
jax-master
|
jax/interpreters/parallel.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import itertools as it
from collections import namedtuple, Counter, defaultdict
import contextlib
import threading
from weakref import ref
import numpy as onp
from .. import core
from .. import linear_util as lu
from ..abstract_arrays import ShapedArray, ConcreteArray, raise_to_shaped
from ..util import unzip2, safe_zip, safe_map, toposort, partial, split_list
from ..core import (Trace, Tracer, new_master, Jaxpr, Literal, get_aval,
AbstractValue, unit, unitvar, abstract_unit, Primitive,
call_p, TypedJaxpr, new_jaxpr_eqn)
map = safe_map
zip = safe_zip
def identity(x): return x
# A partial value (pval) is modeled as a pair (pv, const), as per
# type PVal = (PV, Const)
# data PV = Known | Unknown AbstractValue
# type Const = MaybeTraced JaxType
# where the Known arm, represented by a None, indicates a known (constant) value
# and the Unknown arm, represented by an AbstractValue instance, indicates an
# unknown value.
# When the pv is an AbstractValue, then the const must be unit.
class JaxprTrace(Trace):
def pure(self, val):
return self.new_const(val)
def lift(self, val):
return self.new_const(val)
def sublift(self, val):
return JaxprTracer(self, val.pval, FreeVar(val))
def new_const(self, val):
if isinstance(val, Tracer) and val.trace.level == self.level:
raise Exception
return JaxprTracer(self, PartialVal((None, val)), unit)
def new_instantiated_literal(self, val):
return JaxprTracer(self, PartialVal((get_aval(val), unit)), Literal(val))
def new_instantiated_const(self, val):
return JaxprTracer(self, PartialVal((get_aval(val), unit)), ConstVar(val))
def new_arg(self, pval):
_, const = pval
return JaxprTracer(self, pval, LambdaBinding())
def instantiate_const(self, tracer):
pv, const = tracer.pval
if isinstance(pv, AbstractValue):
return tracer
elif pv is None:
if type(const) in core.literalable_types and onp.shape(const) == ():
return self.new_instantiated_literal(const)
else:
return self.new_instantiated_const(const)
else:
raise TypeError(pv)
def instantiate_const_abstracted(self, tracer):
pv, const = tracer.pval
if isinstance(pv, AbstractValue):
return tracer
elif pv is None:
aval = raise_to_shaped(get_aval(const), onp.isscalar(const))
return JaxprTracer(self, PartialVal((aval, unit)), ConstVar(const))
else:
raise TypeError(pv)
def process_primitive(self, primitive, tracers, params):
if primitive in custom_partial_eval_rules:
return custom_partial_eval_rules[primitive](self, *tracers, **params)
else:
pvs, consts = unzip2(t.pval for t in tracers)
if all(pv is None for pv in pvs):
return primitive.bind(*consts, **params)
tracers = map(self.instantiate_const, tracers)
avals = [t.aval for t in tracers]
out_aval = primitive.abstract_eval(*avals, **params)
if primitive.multiple_results:
out_tracers = [JaxprTracer(self, PartialVal((aval, unit)), None)
for aval in out_aval]
eqn = new_eqn_recipe(tracers, out_tracers, primitive, (), params)
for t in out_tracers: t.recipe = eqn
return out_tracers
else:
out_tracer = JaxprTracer(self, PartialVal((out_aval, unit)), None)
out_tracer.recipe = new_eqn_recipe(tracers, [out_tracer], primitive, (), params)
return out_tracer
def process_call(self, call_primitive, f, tracers, params):
if self.master.trace_type is StagingJaxprTrace:
tracers = map(self.instantiate_const_abstracted, tracers)
if call_primitive in call_partial_eval_rules:
return call_partial_eval_rules[call_primitive](self, f, tracers, params)
if call_primitive in map_primitives:
return self.process_map(call_primitive, f, tracers, params)
in_pvs, in_consts = unzip2([t.pval for t in tracers])
fun, aux = partial_eval(f, self, in_pvs)
out_flat = call_primitive.bind(fun, *in_consts, **params)
out_pvs, jaxpr, env = aux()
out_pv_consts, consts = split_list(out_flat, [len(out_flat)-len(jaxpr.constvars)])
const_tracers = map(self.new_instantiated_const, consts)
bound_subjaxpr = (jaxpr, const_tracers, map(self.full_raise, env))
out_tracers = [JaxprTracer(self, PartialVal((out_pv, out_pv_const)), None)
for out_pv, out_pv_const in zip(out_pvs, out_pv_consts)]
eqn = new_eqn_recipe(tracers, out_tracers, call_primitive, (bound_subjaxpr,), params)
for t in out_tracers:
t.recipe = eqn
return out_tracers
def process_map(self, map_primitive, f, tracers, params):
in_pvs, in_consts = unzip2([t.pval for t in tracers])
reduced_pvs = [None if pv is None else _mapped_aval(pv) for pv in in_pvs]
fun, aux = partial_eval(f, self, reduced_pvs)
out_flat = map_primitive.bind(fun, *in_consts, **params)
out_pvs_reduced, jaxpr, env = aux()
out_pv_consts, consts = split_list(out_flat, [len(out_flat)-len(jaxpr.constvars)])
out_pvs = [None if pv is None else _unmapped_aval(params['axis_size'], pv)
for pv in out_pvs_reduced]
const_tracers = map(self.new_instantiated_const, consts)
lifted_jaxpr = closure_convert_jaxpr(jaxpr)
bound_subjaxpr = (lifted_jaxpr, (), map(self.full_raise, env))
out_tracers = [JaxprTracer(self, PartialVal((out_pv, out_pv_const)), None)
for out_pv, out_pv_const in zip(out_pvs, out_pv_consts)]
eqn = new_eqn_recipe(tuple(it.chain(const_tracers, tracers)),
out_tracers, map_primitive, (bound_subjaxpr,), params)
for t in out_tracers:
t.recipe = eqn
return out_tracers
def post_process_call(self, call_primitive, out_tracers, params):
if call_primitive in map_primitives:
return self.post_process_map(call_primitive, out_tracers, params)
jaxpr, consts, env = tracers_to_jaxpr([], out_tracers)
out_pvs, out_pv_consts = unzip2(t.pval for t in out_tracers)
out = out_pv_consts + consts
del consts, out_pv_consts
master = self.master
def todo(x):
n = len(jaxpr.outvars)
out_pv_consts, consts = x[:n], x[n:]
trace = JaxprTrace(master, core.cur_sublevel())
const_tracers = map(trace.new_instantiated_const, consts)
env_tracers = map(trace.full_raise, env)
bound_subjaxpr = (jaxpr, const_tracers, env_tracers)
out_tracers = [JaxprTracer(trace, PartialVal((out_pv, out_pv_const)), None)
for out_pv, out_pv_const in zip(out_pvs, out_pv_consts)]
eqn = new_eqn_recipe([], out_tracers, call_primitive, (bound_subjaxpr,), params)
for t in out_tracers:
t.recipe = eqn
return out_tracers
return out, todo
def post_process_map(self, map_primitive, out_tracers, params):
jaxpr, consts, env = tracers_to_jaxpr([], out_tracers)
out_pvs_reduced, out_pv_consts = unzip2(t.pval for t in out_tracers)
out_pvs = [None if pv is None else _unmapped_aval(params['axis_size'], pv)
for pv in out_pvs_reduced]
out = out_pv_consts + consts
del consts, out_pv_consts
master = self.master
def todo(x):
n = len(jaxpr.outvars)
out_pv_consts, consts = x[:n], x[n:]
trace = JaxprTrace(master, core.cur_sublevel())
const_tracers = map(trace.new_instantiated_const, consts)
env_tracers = map(trace.full_raise, env)
lifted_jaxpr = closure_convert_jaxpr(jaxpr)
bound_subjaxpr = (lifted_jaxpr, (), env_tracers)
out_tracers = [JaxprTracer(trace, PartialVal((out_pv, out_pv_const)), None)
for out_pv, out_pv_const in zip(out_pvs, out_pv_consts)]
eqn = new_eqn_recipe(const_tracers, out_tracers, map_primitive,
(bound_subjaxpr,), params)
for t in out_tracers:
t.recipe = eqn
return out_tracers
return out, todo
# This subclass is used just for its type tag, which switches the behavior of
# process_call to stage out into the jaxpr any call primitives encountered
# (rather than doing partial evaluation into the call).
class StagingJaxprTrace(JaxprTrace):
pass
def _mapped_aval(aval):
if aval is core.abstract_unit:
return aval
elif isinstance(aval, ShapedArray):
# might be raising abstraction level from Concrete here
return ShapedArray(aval.shape[1:], aval.dtype)
else:
raise TypeError(aval)
def _unmapped_aval(size, aval):
if aval is core.abstract_unit:
return aval
elif isinstance(aval, ShapedArray):
return ShapedArray((size,) + aval.shape, aval.dtype)
else:
raise TypeError(aval)
map_primitives = set()
custom_partial_eval_rules = {}
call_partial_eval_rules = {}
def partial_eval(f, trace, pvs):
f = trace_to_subjaxpr(f, trace.master, False)
return partial_eval_wrapper(f, tuple(pvs))
@lu.transformation_with_aux
def partial_eval_wrapper(avals, *consts):
py_args = (map(PartialVal, zip(avals, consts)),)
jaxpr, (out_pvals, consts, env) = yield py_args, {}
out_pvs, out_consts = unzip2(out_pvals)
out = tuple(out_consts) + tuple(consts) # TODO: can consts be traced?
yield out, (out_pvs, jaxpr, env)
def abstract_eval_fun(fun, *avals, **params):
pvals_in = [PartialVal((a, unit)) for a in avals]
_, pvals_out, _ = trace_to_jaxpr(lu.wrap_init(fun, params), pvals_in,
instantiate=True)
avals_out, _ = unzip2(pvals_out)
for aval_out in avals_out:
assert isinstance(aval_out, AbstractValue) # instantiate=True
return avals_out
class JaxprTracer(Tracer):
__slots__ = ['pval', 'recipe']
def __init__(self, trace, pval, recipe):
assert isinstance(pval, PartialVal)
pv, const = pval
if isinstance(const, Tracer):
assert const.trace.level < trace.level
self.trace = trace
self.pval = pval
self.recipe = recipe
def __repr__(self):
return 'Traced<{}:{}>'.format(self.aval, self.trace)
@property
def aval(self):
pv, const = self.pval
return partial_val_aval(pv, const)
@property
def parents(self):
if isinstance(self.recipe, JaxprEqnRecipe):
return eqn_parents(self.recipe)
else:
return []
def ispure(self):
pv, _ = self.pval
return pv is None # or pv is core.abstract_unit
def full_lower(self):
if self.ispure():
_, const = self.pval
return core.full_lower(const)
else:
return self
class PartialVal(tuple):
def __new__(cls, xs):
pv, const = xs
if not core.skip_checks:
# type checks
assert isinstance(pv, valid_pv_types), xs
assert isinstance(const, core.Tracer) or core.valid_jaxtype(const), xs
# invariant checks
if isinstance(pv, AbstractValue):
assert const == core.unit, xs
return tuple.__new__(cls, xs)
valid_pv_types = (AbstractValue, type(None))
def merge_pvals(val, pval):
pv, const = pval
if isinstance(pv, AbstractValue):
return val
elif pv is None:
return const
else:
raise TypeError(pv)
def partial_val_aval(pv, const):
if isinstance(pv, AbstractValue):
return pv
elif pv is None:
return get_aval(const)
else:
raise TypeError(pv)
def trace_to_jaxpr(fun, pvals, instantiate=False, stage_out_calls=False):
"""Traces a function, given abstract inputs, to a jaxpr."""
trace_type = StagingJaxprTrace if stage_out_calls else JaxprTrace
with new_master(trace_type) as master:
fun = trace_to_subjaxpr(fun, master, instantiate)
jaxpr, (out_pvals, consts, env) = fun.call_wrapped(pvals)
assert not env
del master
return jaxpr, out_pvals, consts
@lu.transformation
def trace_to_subjaxpr(master, instantiate, pvals):
assert all([isinstance(pv, PartialVal) for pv in pvals]), pvals
trace = JaxprTrace(master, core.cur_sublevel())
in_tracers = map(trace.new_arg, pvals)
ans = yield in_tracers, {}
instantiate = [instantiate] * len(ans) if type(instantiate) is bool else instantiate
out_tracers = map(trace.full_raise, map(core.full_lower, ans))
out_tracers = map(partial(instantiate_const_at, trace), instantiate, out_tracers)
jaxpr, consts, env = tracers_to_jaxpr(in_tracers, out_tracers)
out_pvals = [t.pval for t in out_tracers]
del trace, in_tracers, out_tracers
yield jaxpr, (out_pvals, consts, env)
def instantiate_const_at(trace, instantiate, tracer):
assert type(instantiate) is bool
if instantiate:
return trace.instantiate_const(trace.full_raise(tracer))
else:
return tracer
FreeVar = namedtuple('FreeVar', ['val'])
ConstVar = namedtuple('ConstVar', ['val'])
LambdaBinding = namedtuple('LambdaBinding', [])
JaxprEqnRecipe = namedtuple('JaxprEqnRecipe',
['eqn_id', 'invars', 'outvars', 'primitive',
'bound_subjaxprs', 'params'])
def new_eqn_recipe(invars, outvars, primitive, bound_subjaxprs, params):
return JaxprEqnRecipe(object(), invars, map(ref, outvars), primitive,
bound_subjaxprs, params)
def recipe_to_eqn(unused_var, getvar, recipe):
_, in_tracers, out_tracer_refs, primitive, bound_subjaxprs, params = recipe
out_tracers = [t_ref() for t_ref in out_tracer_refs]
invars = [getvar(t) for t in in_tracers]
outvars = [unused_var() if t is None else getvar(t) for t in out_tracers]
new_bound_subjaxprs = [(j, map(getvar, c), map(getvar, f))
for j, c, f in bound_subjaxprs]
return new_jaxpr_eqn(invars, outvars, primitive, new_bound_subjaxprs, params)
def tracers_to_jaxpr(in_tracers, out_tracers):
newvar = core.gensym('')
t_to_var = defaultdict(newvar)
getvar = lambda t: t_to_var[id(t)]
sorted_tracers = toposort(out_tracers)
invars = map(getvar, in_tracers)
eqns = []
env = {}
consts = {}
const_to_var = defaultdict(newvar)
destructuring_vars = {}
processed_eqn_ids = set()
for t in sorted_tracers:
recipe = t.recipe
if isinstance(recipe, JaxprEqnRecipe):
if recipe.eqn_id not in processed_eqn_ids:
eqns.append(recipe_to_eqn(newvar, getvar, recipe))
processed_eqn_ids.add(recipe.eqn_id)
elif isinstance(recipe, LambdaBinding):
assert any(t is in_tracer for in_tracer in in_tracers), "Encountered unexpected tracer"
assert in_tracers, "Lambda binding with no args"
elif isinstance(recipe, FreeVar):
env[getvar(t)] = recipe.val
elif isinstance(recipe, ConstVar):
v = t_to_var[id(t)] = const_to_var[id(recipe.val)]
consts[v] = recipe.val
elif isinstance(recipe, Literal):
t_to_var[id(t)] = recipe
elif recipe is unit:
t_to_var[id(t)] = unitvar
else:
raise TypeError(recipe)
env_vars, env_vals = unzip2(env.items())
const_vars, const_vals = unzip2(consts.items())
jaxpr = Jaxpr(const_vars, env_vars, invars, list(map(getvar, out_tracers)), eqns)
core.skip_checks or core.check_jaxpr(jaxpr)
return jaxpr, const_vals, env_vals
def eqn_parents(eqn):
subjaxpr_tracers = [it.chain(c, f) for _, c, f in eqn.bound_subjaxprs]
return list(it.chain(eqn.invars, *subjaxpr_tracers))
def closure_convert_jaxpr(jaxpr):
core.skip_checks or core.check_jaxpr(jaxpr)
lifted_jaxpr = Jaxpr(constvars=(), freevars=jaxpr.freevars,
invars=jaxpr.constvars + jaxpr.invars,
outvars=jaxpr.outvars, eqns=jaxpr.eqns)
core.skip_checks or core.check_jaxpr(lifted_jaxpr)
return lifted_jaxpr
def convert_freevars_jaxpr(jaxpr):
core.skip_checks or core.check_jaxpr(jaxpr)
lifted_jaxpr = Jaxpr(constvars=jaxpr.constvars, freevars=(),
invars=jaxpr.freevars + jaxpr.invars,
outvars=jaxpr.outvars, eqns=jaxpr.eqns)
core.skip_checks or core.check_jaxpr(lifted_jaxpr)
return lifted_jaxpr
def partial_eval_jaxpr(jaxpr, unknowns, instantiate):
f = lu.wrap_init(core.jaxpr_as_fun(jaxpr))
cell = []
def fun(*vals):
pvals = [PartialVal((aval, unit)) if uk else PartialVal((None, val))
for aval, val, uk in zip(jaxpr.in_avals, vals, unknowns)]
jaxpr_2, out_pvals_2, consts_2 = trace_to_jaxpr(f, pvals, instantiate=instantiate)
out_pvs_2, out_consts_2 = unzip2(out_pvals_2)
cell.append((out_pvs_2, jaxpr_2, len(consts_2)))
return out_consts_2 + consts_2
pvals = [PartialVal((abstract_unit, unit)) if uk else PartialVal((aval, unit))
for aval, uk in zip(jaxpr.in_avals, unknowns)]
jaxpr_1, out_pvals, consts_1 = trace_to_jaxpr(lu.wrap_init(fun), pvals, instantiate=True)
(out_pvs_2, jaxpr_2, num_res), = cell
assert len(jaxpr_2.constvars) == num_res
# jaxpr :: a -> b
# jaxpr_1 :: a1 -> [b1, res]
# jaxpr_2 :: res | a2 -> b2
# jaxpr_2 :: [a2, res] -> b2
jaxpr_2 = closure_convert_jaxpr(jaxpr_2)
jaxpr_2.invars = jaxpr_2.invars[num_res:] + jaxpr_2.invars[:num_res]
uk_out = [pv is not None for pv in out_pvs_2]
in_avals_1, in_avals_2 = unzip2(map(_split_aval, unknowns, jaxpr.in_avals))
out_avals_1, out_avals_2 = unzip2(map(_split_aval, uk_out, jaxpr.out_avals))
# out_avals_1 and in_avals_2 need the residuals added
out_pvs, _ = unzip2(out_pvals)
res_avals = out_pvs[len(jaxpr.out_avals):]
assert len(res_avals) == num_res
out_avals_1 = out_avals_1 + res_avals
in_avals_2 = in_avals_2 + res_avals
typed_jaxpr_1 = TypedJaxpr(jaxpr_1, consts_1, in_avals_1, out_avals_1)
typed_jaxpr_2 = TypedJaxpr(jaxpr_2, (), in_avals_2, out_avals_2)
return typed_jaxpr_1, typed_jaxpr_2, uk_out
def _split_aval(unknown, aval):
return (abstract_unit, aval) if unknown else (aval, abstract_unit)
remat_call_p = core.Primitive('remat_call')
remat_call = partial(core.call_bind, remat_call_p)
remat_call_p.def_custom_bind(remat_call)
remat_call_p.def_impl(core.call_impl)
remat_call_p.multiple_results = True
def _remat_partial_eval(trace, f, tracers, params):
concrete = params['concrete']
# Unlike JaxprTrace.process_call, we want to form a jaxpr for the entirety of
# the function being called, not just for the unknown parts. To do that, we
# instantiate all the input tracers as constants in the jaxpr being formed.
# Those tracers might have concrete avals, and doing abstract interpretation
# on concrete avals engenders a tradeoff: it allows data-dependent Python
# control flow to work, but it can in some cases lead to redundant FLOPs (done
# both in the `bind` call below and the `core.jaxpr_as_fun` call). We use the
# `concrete` parameter to switch this behavior, and if `concrete` is False
# then we raise the avals to the Shaped level.
if concrete:
instantiated_tracers = map(trace.instantiate_const, tracers)
else:
instantiated_tracers = map(trace.instantiate_const_abstracted, tracers)
# Using the instantiated tracers, run call_bind like JaxprTrace.process_call.
in_pvs, in_consts = unzip2(t.pval for t in instantiated_tracers)
fun, aux = partial_eval(f, trace, in_pvs)
if concrete:
# TODO(mattjj): remove `remat_context` when confident no accidental FLOPs
with remat_context():
out_flat = remat_call_p.bind(fun, *in_consts, **params)
else:
out_flat = remat_call_p.bind(fun, *in_consts, **params)
out_pvs, jaxpr, env = aux()
env = map(trace.full_raise, env)
out_pval_consts1, consts = split_list(out_flat, [len(out_flat)-len(jaxpr.constvars)])
out_pvals1 = [PartialVal((pv, const)) for pv, const in zip(out_pvs, out_pval_consts1)]
# Since we traced with everything marked as unknown, but we need to know which
# outputs are known/unknown, we use partial_eval_jaxpr to get out_unknowns.
jaxpr_converted = convert_freevars_jaxpr(jaxpr)
in_avals = ([raise_to_shaped(t.pval[0]) for t in env]
+ [raise_to_shaped(pv) for pv in in_pvs])
out_avals = [raise_to_shaped(pv if pv is not None
else abstract_unit if var is unitvar
else get_aval(var.val) if type(var) is Literal
else get_aval(const))
for var, pv, const in zip(jaxpr.outvars, out_pvs, out_pval_consts1)]
typed_jaxpr = core.TypedJaxpr(jaxpr_converted, consts, in_avals, out_avals)
in_unknowns = [t.pval[0] is not None for t in it.chain(env, tracers)]
jaxpr_1, jaxpr_2, out_unknowns = partial_eval_jaxpr(typed_jaxpr, in_unknowns, False)
num_res = len(jaxpr_1.out_avals) - len(jaxpr_2.out_avals)
# First, we prune the jaxpr to be staged out not to have too many outputs.
typed_jaxpr = _dce_jaxpr(typed_jaxpr, out_unknowns)
# Next, we need values for the outputs that should be known. Since consts
# weren't passed through Python for evaluation, we need to evaluate jaxpr_1,
# minus the residual outputs that we don't need. When `concrete=True`, as an
# optimization we can avoid redoing *some* redundant FLOPs, namely those that
# produced concrete avals at the output, simply by using those as computed
# values. For the use case of reverse-mode ad in op-by-op ("eager mode")
# evaluation, all the primal outputs should be concrete (thus not recomputed).
to_compute = [not uk and type(pv) is not ConcreteArray
for uk, pv in zip(out_unknowns, out_pvs)]
jaxpr_1_primals = _dce_jaxpr(jaxpr_1, to_compute + [False] * num_res)
_, in_consts = unzip2(t.pval for t in it.chain(env, tracers))
out_pval_consts2 = core.jaxpr_as_fun(jaxpr_1_primals)(*in_consts)[:-num_res or None]
out_pvals = map(_reconstruct_pval, out_pvals1, out_pval_consts2, out_unknowns)
# Now that we have out_pvals, the rest is just like JaxprTrace.process_call.
instantiated_tracers = env + instantiated_tracers
const_tracers = map(trace.new_instantiated_const, consts)
bound_subjaxpr = (typed_jaxpr.jaxpr, const_tracers, ())
out_tracers = [JaxprTracer(trace, out_pval, None) for out_pval in out_pvals]
eqn = new_eqn_recipe(instantiated_tracers, out_tracers, remat_call_p,
(bound_subjaxpr,), params)
for t in out_tracers: t.recipe = eqn
return out_tracers
call_partial_eval_rules[remat_call_p] = _remat_partial_eval
def _dce_jaxpr(typed_jaxpr, outputs):
# This dead-code elimination is pretty rudimentary, and in particular doesn't
# nontrivially DCE through scan, call, or other higher-order primitives.
# TODO(mattjj): better DCE
jaxpr = typed_jaxpr.jaxpr
outvars, out_avals = jaxpr.outvars, typed_jaxpr.out_avals
out_pairs = [(var, aval) if output else (unitvar, core.abstract_unit)
for var, aval, output in zip(outvars, out_avals, outputs)]
new_outvars, new_out_avals = unzip2(out_pairs)
needed_vars = set(new_outvars)
new_eqns = []
for eqn in jaxpr.eqns[::-1]:
if set(eqn.outvars) & needed_vars:
new_eqns.append(eqn)
needed_vars.update(eqn.invars)
new_eqns = new_eqns[::-1]
new_jaxpr = core.Jaxpr(jaxpr.constvars, jaxpr.freevars, jaxpr.invars,
new_outvars, new_eqns)
return core.TypedJaxpr(new_jaxpr, typed_jaxpr.literals, typed_jaxpr.in_avals,
new_out_avals)
def _reconstruct_pval(pval1, const2, unknown):
pv1, const1 = pval1
if unknown or pv1 is None:
return pval1
else:
if type(pv1) is ConcreteArray:
return PartialVal((None, pv1.val))
else:
return PartialVal((None, const2))
# TODO(mattjj): for https://github.com/google/jax/pull/1749 we allowed
# standard_abstract_eval to perform concrete evaluation (i.e. FLOPs), but we
# don't think it should happen except for in a remat context
@contextlib.contextmanager
def remat_context():
try:
prev_state = _thread_local_state.remat
_thread_local_state.remat = True
yield
finally:
_thread_local_state.remat = prev_state
class _ThreadLocalState(threading.local):
def __init__(self):
self.remat = False
_thread_local_state = _ThreadLocalState()
def move_binders_to_front(typed_jaxpr, to_move):
assert not typed_jaxpr.jaxpr.constvars and not typed_jaxpr.jaxpr.freevars
assert len(typed_jaxpr.in_avals) == len(to_move)
new_invars = _move_to_front(typed_jaxpr.jaxpr.invars, to_move)
new_jaxpr = core.Jaxpr((), (), new_invars, typed_jaxpr.jaxpr.outvars,
typed_jaxpr.jaxpr.eqns)
new_in_avals = _move_to_front(typed_jaxpr.in_avals, to_move)
new_typed_jaxpr = core.TypedJaxpr(new_jaxpr, typed_jaxpr.literals,
new_in_avals, typed_jaxpr.out_avals)
return new_typed_jaxpr
def _move_to_front(lst, to_move):
return ([elt for elt, move in zip(lst, to_move) if move] +
[elt for elt, move in zip(lst, to_move) if not move])
|
jax-master
|
jax/interpreters/partial_eval.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from collections import namedtuple, defaultdict
from distutils.util import strtobool
import itertools as it
import operator as op
import os
from absl import logging
import numpy as onp
import six
from six.moves import xrange
from ..config import flags
from .. import core
from .. import ad_util
from .. import tree_util
from .. import dtypes
from .. import linear_util as lu
from ..abstract_arrays import (ConcreteArray, ShapedArray, AbstractToken,
make_shaped_array, array_types, raise_to_shaped,
abstract_token)
from ..core import valid_jaxtype, Literal
from ..util import (partial, partialmethod, cache, safe_map, prod, unzip2,
memoize)
from ..lib import xla_bridge as xb
from ..lib import xla_client as xc
from . import partial_eval as pe
from . import ad
FLAGS = flags.FLAGS
flags.DEFINE_bool('jax_debug_nans',
strtobool(os.getenv('JAX_DEBUG_NANS', "False")),
'Add nan checks to every operation.')
flags.DEFINE_bool('jax_log_compiles',
strtobool(os.getenv('JAX_LOG_COMPILES', "False")),
'Print a message each time a `jit` computation is compiled.')
def _map(f, *xs): return tuple(map(f, *xs))
def identity(x): return x
### handlers
xb.register_constant_handler(core.Unit, lambda c, *_: c.Tuple())
def aval_to_xla_shape(aval):
try:
return xla_shape_handlers[type(aval)](aval)
except KeyError:
raise TypeError("No xla_shape_handler for type: {}".format(type(aval)))
xla_shape_handlers = {}
xla_shape_handlers[core.AbstractUnit] = lambda _: xc.Shape.tuple_shape(())
xla_shape_handlers[ShapedArray] = lambda a: xc.Shape.array_shape(a.dtype, a.shape)
xla_shape_handlers[ConcreteArray] = lambda a: xc.Shape.array_shape(a.dtype, a.shape)
def aval_to_result_handler(device, aval):
try:
return xla_result_handlers[type(aval)](device, aval)
except KeyError:
raise TypeError("No xla_result_handler for type: {}".format(type(aval)))
xla_result_handlers = {}
xla_result_handlers[core.AbstractUnit] = lambda _, __: lambda _: core.unit
def array_result_handler(device, aval):
return partial(DeviceArray, raise_to_shaped(aval), device)
xla_result_handlers[ShapedArray] = array_result_handler
xla_result_handlers[ConcreteArray] = array_result_handler
def device_put(x, device=None):
x = canonicalize_dtype(x)
try:
return device_put_handlers[type(x)](x, device)
except KeyError:
raise TypeError("No device_put handler for type: {}".format(type(x)))
device_put_handlers = {}
device_put_handlers[core.Unit] = \
lambda _, device: xc.Buffer.from_pyval(
(), device, backend=xb.get_device_backend(device))
def _device_put_array(x, device):
return xc.Buffer.from_pyval(x, device, backend=xb.get_device_backend(device))
for _t in array_types:
device_put_handlers[_t] = _device_put_array
def _device_put_scalar(x, device):
return xc.Buffer.from_pyval(dtypes.coerce_to_array(x), device,
backend=xb.get_device_backend(device))
for _t in dtypes.python_scalar_dtypes.keys():
device_put_handlers[_t] = _device_put_array
# TODO(mattjj): try to remove this canonicalize_dtype stuff
def canonicalize_dtype(x):
typ = type(x)
handler = canonicalize_dtype_handlers.get(typ)
if handler: return handler(x)
for typ in typ.mro():
handler = canonicalize_dtype_handlers.get(typ)
if handler: return handler(x)
raise TypeError("No canonicalize_dtype handler for type: {}".format(type(x)))
canonicalize_dtype_handlers = {}
canonicalize_dtype_handlers[core.Unit] = identity
def _canonicalize_ndarray_dtype(x):
return onp.asarray(x, dtypes.canonicalize_dtype(dtypes.result_type(x)))
for _t in array_types:
canonicalize_dtype_handlers[_t] = _canonicalize_ndarray_dtype
def _canonicalize_python_scalar_dtype(typ, x):
return onp.asarray(
x, dtypes.canonicalize_dtype(dtypes.python_scalar_dtypes[typ]))
for _t in dtypes.python_scalar_dtypes.keys():
canonicalize_dtype_handlers[_t] = partial(_canonicalize_python_scalar_dtype, _t)
def abstractify(x):
typ = type(x)
aval_fn = pytype_aval_mappings.get(typ)
if aval_fn: return aval_fn(x)
for typ in typ.mro():
aval_fn = pytype_aval_mappings.get(typ)
if aval_fn: return aval_fn(x)
raise TypeError("No abstraction handler for type: {}".format(type(x)))
pytype_aval_mappings = {}
pytype_aval_mappings[core.Unit] = lambda _: core.abstract_unit
for _t in array_types:
pytype_aval_mappings[_t] = make_shaped_array
def _make_abstract_python_scalar(typ, _):
return ShapedArray((), dtypes.python_scalar_dtypes[typ], weak_type=True)
for _t in dtypes.python_scalar_dtypes.keys():
pytype_aval_mappings[_t] = partial(_make_abstract_python_scalar, _t)
### op-by-op execution
def arg_spec(x):
aval = abstractify(x)
try:
return aval, x._device
except:
return aval, None
def apply_primitive(prim, *args, **params):
"""Impl rule that compiles and runs a single primitive 'prim' using XLA."""
compiled_fun = xla_primitive_callable(prim, *map(arg_spec, args), **params)
return compiled_fun(*args)
@cache()
def xla_primitive_callable(prim, *arg_specs, **params):
avals, arg_devices = unzip2(arg_specs)
device = _device_from_arg_devices(arg_devices)
backend = xb.get_device_backend(device)
aval_out = prim.abstract_eval(*avals, **params)
if not prim.multiple_results:
handle_result = aval_to_result_handler(device, aval_out)
else:
handlers = tuple(map(partial(aval_to_result_handler, device), aval_out))
handle_result = lambda xs: tuple(h(x) for h, x in zip(handlers, xs.destructure()))
tuple_args = len(avals) > 100
built_c = primitive_computation(prim, backend, tuple_args, *avals, **params)
options = xb.get_compile_options(device_assignment=device and (device.id,))
compiled = built_c.Compile(compile_options=options, backend=backend)
return partial(_execute_compiled_primitive, prim, compiled, backend,
tuple_args, handle_result)
# TODO(mattjj): make Device instances hashable instead of handling pairs here
def _device_from_arg_devices(devices):
"""Given devices of inputs, determine where to perform a computation.
Args:
devices: list where each element is a either a pair consisting of a device
class and an int id (representing a Device instance) or a None.
Returns:
A Device instance or None.
Raises:
ValueError if input devices are inconsistent.
"""
try:
device, = set(d for d in devices if d is not None) or (None,)
except ValueError:
msg = "primitive arguments must be colocated on the same device, got {}"
names = ("{}({})".format(d[0].__name__, d[1]) for d in devices if d is not None)
raise ValueError(msg.format(", ".join(names)))
else:
all_devices = it.chain(xb.devices(), xb.devices('cpu'))
return device and next(d for d in all_devices if (type(d), d.id) == device)
@cache()
def primitive_computation(prim, backend, tuple_args, *avals, **params):
c = xb.make_computation_builder("primitive_computation_{}".format(prim.name))
c.SetOpMetadata(xc.OpMetadata(op_type=prim.name, op_name=str(params)))
platform = xb.get_backend(backend).platform
xla_args = _xla_callable_args(c, avals, tuple_args)
if prim in backend_specific_translations[platform]:
rule = backend_specific_translations[platform][prim]
rule(c, *xla_args, **params) # return val set as a side-effect on c
elif prim in translations:
rule = translations[prim]
rule(c, *xla_args, **params) # return val set as a side-effect on c
elif prim in initial_style_translations:
rule = initial_style_translations[prim]
rule(c, AxisEnv(), *xla_args, backend=backend, **params) # side-effect on c
else:
raise NotImplementedError("XLA translation rule for {} not found".format(prim))
c.ClearOpMetadata()
try:
return c.Build()
except RuntimeError as e:
msg = (" ".join(map(str, e.args)) + "\n"
"This is a bug in JAX's shape-checking rules; please report it!\n"
"https://github.com/google/jax/issues\n")
raise RuntimeError(msg)
def primitive_subcomputation(prim, *avals, **params):
return primitive_computation(prim, None, False, *avals, **params)
def _execute_compiled_primitive(prim, compiled, backend, tuple_args,
result_handler, *args):
device, = compiled.local_devices()
input_bufs = [device_put(x, device) for x in args if x is not token]
if tuple_args:
input_bufs = [make_tuple(input_bufs, device, backend)]
out_buf = compiled.Execute(input_bufs)
if FLAGS.jax_debug_nans:
check_nans(prim, out_buf.destructure() if prim.multiple_results else out_buf)
return result_handler(out_buf)
def check_nans(prim, bufs):
if prim.multiple_results:
for buf in bufs:
_check_nans(prim.name, buf.shape(), buf)
else:
_check_nans(prim.name, bufs.shape(), bufs)
def _check_nans(name, xla_shape, buf):
if xla_shape.is_tuple():
assert not xla_shape.tuple_shapes()
else:
if dtypes.issubdtype(xla_shape.element_type(), onp.floating):
if onp.any(onp.isnan(buf.to_py())):
msg = "invalid value (nan) encountered in {}"
raise FloatingPointError(msg.format(name))
### compiling jaxprs
def prefetch(x):
if isinstance(x, DeviceArray):
x.copy_to_host_async()
return x
def jaxpr_literals(jaxpr):
return it.chain.from_iterable(eqn_literals(eqn) for eqn in jaxpr.eqns)
def eqn_literals(eqn):
if eqn.bound_subjaxprs:
(subjaxpr, _, _), = eqn.bound_subjaxprs
for literal in jaxpr_literals(subjaxpr):
yield literal
if eqn.primitive in initial_style_translations:
for param in eqn.params.values():
if type(param) in (core.Jaxpr, core.TypedJaxpr):
subjaxpr = param if type(param) is core.Jaxpr else param.jaxpr
for literal in jaxpr_literals(subjaxpr):
yield literal
for v in eqn.invars:
if type(v) is core.Literal:
yield v.val
def jaxpr_subcomp(c, jaxpr, backend, axis_env, consts, freevars, *args):
platform = xb.get_backend(backend).platform
def read(v):
if type(v) is Literal:
return c.Constant(canonicalize_dtype(v.val))
else:
return env[v]
def write(v, node):
assert node is not None
env[v] = node
env = {}
write(core.unitvar, c.Tuple())
_map(write, jaxpr.constvars, consts)
_map(write, jaxpr.freevars, freevars)
_map(write, jaxpr.invars, args)
for eqn in jaxpr.eqns:
c.SetOpMetadata(xc.OpMetadata(op_type=eqn.primitive.name))
in_nodes = list(map(read, eqn.invars))
if eqn.primitive in backend_specific_translations[platform]:
rule = backend_specific_translations[platform][eqn.primitive]
ans = rule(c, *in_nodes, **eqn.params)
elif eqn.primitive in translations:
ans = translations[eqn.primitive](c, *in_nodes, **eqn.params)
elif eqn.primitive in initial_style_translations:
new_params = check_backend_params(eqn.params, backend)
rule = initial_style_translations[eqn.primitive]
ans = rule(c, axis_env, *in_nodes, backend=backend, **new_params)
elif eqn.primitive in parallel_translations:
replica_groups = axis_groups(axis_env, eqn.params['axis_name'])
new_params = {k: v for k, v in eqn.params.items() if k != 'axis_name'}
rule = parallel_translations[eqn.primitive]
ans = rule(c, *in_nodes, replica_groups=replica_groups, **new_params)
elif eqn.primitive in call_translations:
new_params = check_backend_params(eqn.params, backend)
(subjaxpr, const_bindings, freevar_bindings), = eqn.bound_subjaxprs
const_nodes = _map(read, const_bindings)
freevar_nodes = _map(read, freevar_bindings)
rule = call_translations[eqn.primitive]
ans = rule(c, subjaxpr, axis_env, const_nodes, freevar_nodes, in_nodes,
backend=backend, **new_params)
else:
msg = "XLA translation rule for primitive '{}' not found"
raise NotImplementedError(msg.format(eqn.primitive.name))
c.GetShape(ans) # force xla to do shape error checking
out_nodes = xla_destructure(c, ans) if eqn.primitive.multiple_results else [ans]
c.ClearOpMetadata()
_map(write, eqn.outvars, out_nodes)
return _map(read, jaxpr.outvars)
def xla_destructure(c, ans):
num_elements = len(c.GetShape(ans).tuple_shapes())
return [c.GetTupleElement(ans, i) for i in range(num_elements)]
def check_backend_params(params, outer_backend):
# For nested calls, the outermost call sets the backend for all inner calls;
# it's an error if the inner call has a conflicting explicit backend spec.
inner_backend = params.get('backend', None)
if inner_backend and inner_backend != outer_backend:
msg = (
"Outer-jit backend specification {} must match explicit inner-jit "
"backend specification {}.")
raise ValueError(msg.format(outer_backend, inner_backend))
return {k: params[k] for k in params if k != 'backend'}
class AxisEnv(object):
def __init__(self, nreps=1, names=None, sizes=None, devices=None):
self.nreps = nreps
self.names = names if names else []
self.sizes = sizes if sizes else []
self.devices = devices
def extend_axis_env(env, name, size):
return AxisEnv(env.nreps, env.names + [name], env.sizes + [size], env.devices)
def axis_read(axis_env, axis_name):
return max(i for i, name in enumerate(axis_env.names) if name == axis_name)
def axis_groups(axis_env, name):
if isinstance(name, (list, tuple)):
mesh_axes = tuple(map(partial(axis_read, axis_env), name))
else:
mesh_axes = (axis_read(axis_env, name),)
return _axis_groups(axis_env.nreps, axis_env.sizes, mesh_axes)
def _axis_groups(nrep, mesh_spec, mesh_axes):
trailing_size, ragged = divmod(nrep, prod(mesh_spec))
assert not ragged
full_spec = list(mesh_spec) + [trailing_size]
iota = onp.arange(prod(full_spec)).reshape(full_spec)
groups = onp.reshape(
onp.moveaxis(iota, mesh_axes, onp.arange(len(mesh_axes))),
(prod(onp.take(full_spec, mesh_axes)), -1))
return tuple(map(tuple, groups.T))
def jaxpr_replicas(jaxpr):
return max(it.chain([1], (eqn_replicas(eqn) for eqn in jaxpr.eqns)))
def eqn_replicas(eqn):
if eqn.bound_subjaxprs:
(subjaxpr, _, _), = eqn.bound_subjaxprs
return eqn.params.get('axis_size', 1) * jaxpr_replicas(subjaxpr)
elif eqn.primitive in initial_style_translations:
nums = (jaxpr_replicas(param if type(param) is core.Jaxpr else param.jaxpr)
for param in eqn.params.values()
if type(param) in (core.Jaxpr, core.TypedJaxpr))
return max(it.chain([1], nums))
else:
return 1
# TODO(mattjj,skyewm): the functions here are utilities for checking if
# not-yet-supported features are used with multi-host programming
def jaxpr_has_pmap(jaxpr):
return any(eqn_has_pmap(eqn) for eqn in jaxpr.eqns)
def eqn_has_pmap(eqn):
if eqn.bound_subjaxprs:
(subjaxpr, _, _), = eqn.bound_subjaxprs
return jaxpr_has_pmap(subjaxpr)
elif eqn.primitive in initial_style_translations:
return any(jaxpr_has_pmap(param if type(param) is core.Jaxpr else param.jaxpr)
for param in eqn.params.values()
if type(param) in (core.Jaxpr, core.TypedJaxpr))
else:
return 'pmap' in eqn.primitive.name
def jaxpr_collectives(jaxpr):
return it.chain.from_iterable(eqn_collectives(eqn) for eqn in jaxpr.eqns)
def eqn_collectives(eqn):
if eqn.bound_subjaxprs:
(subjaxpr, _, _), = eqn.bound_subjaxprs
for c in jaxpr_collectives(subjaxpr):
yield c
elif eqn.primitive in initial_style_translations:
for param in eqn.params.values():
if type(param) is core.Jaxpr:
for c in jaxpr_collectives(param):
yield c
elif type(param) is core.TypedJaxpr:
for c in jaxpr_collectives(param.jaxpr):
yield c
else:
if eqn.primitive in parallel_translations:
yield eqn.primitive
### xla_call underlying jit
def _xla_call_impl(fun, *args, **params):
device = params['device']
backend = params['backend']
compiled_fun = _xla_callable(fun, device, backend, *map(arg_spec, args))
try:
return compiled_fun(*args)
except FloatingPointError:
print("Invalid value encountered in the output of a jit function. "
"Calling the de-optimized version.")
return fun.call_wrapped(*args) # probably won't return
@lu.cache
def _xla_callable(fun, device, backend, *arg_specs):
if device is not None and backend is not None:
raise ValueError("can't specify both a device and a backend for jit, "
"got device={} and backend={}".format(device, backend))
abstract_args, arg_devices = unzip2(arg_specs)
pvals = [pe.PartialVal((aval, core.unit)) for aval in abstract_args]
with core.new_master(pe.StagingJaxprTrace, True) as master:
jaxpr, (pvals, consts, env) = pe.trace_to_subjaxpr(fun, master, False).call_wrapped(pvals)
assert not env # no subtraces here
del master, env
_map(prefetch, it.chain(consts, jaxpr_literals(jaxpr)))
nreps = jaxpr_replicas(jaxpr)
device = _xla_callable_device(nreps, backend, device, arg_devices)
result_handlers = tuple(map(partial(_pval_to_result_handler, device), pvals))
# Computations that only produce constants and/or only rearrange their inputs,
# which are often produced from partial evaluation, don't need compilation,
# and don't need to force their (potentially lazy) arguments.
if not jaxpr.eqns:
device = device or xb.get_backend(None).get_default_device_assignment(1)[0]
return partial(_execute_trivial, jaxpr, device, consts, result_handlers)
log_priority = logging.WARNING if FLAGS.jax_log_compiles else logging.DEBUG
logging.log(log_priority,
"Compiling {} for args {}.".format(fun.__name__, abstract_args))
if nreps > xb.device_count(backend):
msg = ("compiling computation that requires {} replicas, but only {} XLA "
"devices are available")
raise ValueError(msg.format(nreps, xb.device_count(backend)))
if xb.host_count() > 1 and (nreps > 1 or jaxpr_has_pmap(jaxpr)):
raise NotImplementedError(
"jit of multi-host pmap not implemented (and jit-of-pmap can cause "
"extra data movement anyway, so maybe you don't want it after all).")
tuple_args = len(abstract_args) > 100 # pass long arg lists as tuple for TPU
c = xb.make_computation_builder("jit_{}".format(fun.__name__))
xla_consts = _map(c.Constant, consts)
xla_args = _xla_callable_args(c, abstract_args, tuple_args)
out_nodes = jaxpr_subcomp(c, jaxpr, backend, AxisEnv(nreps, [], []),
xla_consts, (), *xla_args)
built = c.Build(c.Tuple(*out_nodes))
options = xb.get_compile_options(
num_replicas=nreps, device_assignment=(device.id,) if device else None)
compiled = built.Compile(compile_options=options, backend=xb.get_backend(backend))
if nreps == 1:
return partial(_execute_compiled, compiled, backend, result_handlers, tuple_args)
else:
return partial(_execute_replicated, compiled, backend, result_handlers, tuple_args)
def _xla_callable_device(nreps, backend, device, arg_devices):
if nreps > 1:
if device is not None or backend is not None:
raise ValueError("can't specify device or backend for jit-of-pmap, "
"got device={} and backend={}".format(device, backend))
return None
else:
if device is None and backend is None:
return _device_from_arg_devices(arg_devices)
elif device is not None and backend is None:
return device
elif device is None and backend is not None:
return xb.get_backend(backend).get_default_device_assignment(1)[0]
else:
assert False # Unreachable given the error check in _xla_callable
def _xla_callable_args(c, avals, tuple_args):
if not tuple_args:
xla_args = [c.ParameterWithShape(aval_to_xla_shape(a))
if a is not abstract_token else c.CreateToken() for a in avals]
return xla_args
else:
tuple_param = c.ParameterWithShape(xc.Shape.tuple_shape(
[aval_to_xla_shape(a) for a in avals if a is not abstract_token]))
xla_inputs = iter(xla_destructure(c, tuple_param))
xla_args = [next(xla_inputs) if a is not abstract_token else c.CreateToken()
for a in avals]
assert next(xla_inputs, None) is None
return xla_args
def _pval_to_result_handler(device, pval):
pv, const = pval
if pv is None:
return lambda _: const
else:
return aval_to_result_handler(device, pv)
def _execute_compiled(compiled, backend, handlers, tuple_args, *args):
device, = compiled.local_devices()
input_bufs = [device_put(x, device) for x in args if x is not token]
if tuple_args:
input_bufs = [make_tuple(input_bufs, device, backend)]
out_bufs = compiled.Execute(input_bufs).destructure()
if FLAGS.jax_debug_nans: check_nans(xla_call_p, out_bufs)
return [handler(out_buf) for handler, out_buf in zip(handlers, out_bufs)]
def _execute_replicated(compiled, backend, handlers, tuple_args, *args):
input_bufs = [
[device_put(x, device) for x in args if x is not token]
for device in compiled.local_devices()]
if tuple_args:
input_bufs = [[make_tuple(bufs, device, backend)] for bufs, device in
zip(input_bufs, compiled.local_devices())]
out_bufs = compiled.ExecutePerReplica(input_bufs)[0].destructure()
if FLAGS.jax_debug_nans: check_nans(xla_call_p, out_bufs)
return [handler(out_buf) for handler, out_buf in zip(handlers, out_bufs)]
def _execute_trivial(jaxpr, device, consts, handlers, *args):
env = {core.unitvar : core.unit}
_map(env.setdefault, jaxpr.invars, args)
_map(env.setdefault, jaxpr.constvars, consts)
outs = [canonicalize_dtype(v.val) if type(v) is Literal else env[v]
for v in jaxpr.outvars]
return [x if type(x) is DeviceArray else handler(device_put(x, device))
for handler, x in zip(handlers, outs)]
def make_tuple(bufs, device, backend):
return xb.get_backend(backend).make_tuple(bufs, device)
@memoize
def _get_device(device, backend):
# TODO(mattjj): after jaxlib update, avoid compile here, just to get device
c = xb.make_computation_builder("get_device")
built = c.Build(c.Tuple())
options = xb.get_compile_options(
num_replicas=1, device_assignment=(device.id,) if device else None)
compiled = built.Compile(compile_options=options, backend=xb.get_backend(backend))
out, = compiled.local_devices()
return out
xla_call_p = core.Primitive('xla_call')
xla_call_p.multiple_results = True
xla_call = partial(core.call_bind, xla_call_p)
xla_call_p.def_custom_bind(xla_call)
xla_call_p.def_impl(_xla_call_impl)
def _xla_call_translation_rule(c, jaxpr, axis_env, const_nodes, freevar_nodes,
in_nodes, backend, device=None):
del device # Ignored.
subc = xb.make_computation_builder("jaxpr_subcomputation") # TODO(mattjj): name
consts = [subc.ParameterWithShape(c.GetShape(n)) for n in const_nodes]
freevars = [subc.ParameterWithShape(c.GetShape(n)) for n in freevar_nodes]
args = [subc.ParameterWithShape(c.GetShape(n)) for n in in_nodes]
out_nodes = jaxpr_subcomp(subc, jaxpr, backend, axis_env, consts, freevars, *args)
subc = subc.Build(subc.Tuple(*out_nodes))
return c.Call(subc, list(const_nodes) + list(freevar_nodes) + list(in_nodes))
ad.primitive_transposes[xla_call_p] = partial(ad.call_transpose, xla_call_p)
### translation tables
translations = {}
parallel_translations = {}
initial_style_translations = {}
call_translations = {}
backend_specific_translations = defaultdict(dict)
translations[core.identity_p] = lambda c, x: x
call_translations[xla_call_p] = _xla_call_translation_rule
def zeros_like_translation_rule(c, x):
shape = c.GetShape(x)
if shape.is_tuple():
assert not shape.tuple_shapes()
return c.Tuple()
else:
zero = c.Constant(onp.array(0, shape.element_type()))
return c.Broadcast(zero, shape.dimensions())
translations[ad_util.zeros_like_p] = zeros_like_translation_rule
def add_jaxvals_translation_rule(c, x, y):
shape = c.GetShape(x)
if shape.is_tuple():
assert not shape.tuple_shapes()
return x
else:
return c.Add(x, y)
translations[ad_util.add_jaxvals_p] = add_jaxvals_translation_rule
def lower_fun(fun, instantiate=False, initial_style=False):
"""Build a translation rule for a traceable function."""
def f(c, *args, **params):
backend = params.pop('backend', None)
if initial_style:
axis_env, xla_args = args[0], args[1:]
else:
axis_env, xla_args = AxisEnv(), args
xla_shapes = tuple(map(c.GetShape, xla_args))
avals = map(_aval_from_xla_shape, xla_shapes)
pvals = [pe.PartialVal((a, core.unit)) for a in avals]
jaxpr, _, consts = pe.trace_to_jaxpr(
lu.wrap_init(fun, params), pvals, instantiate=True)
consts = _map(c.Constant, consts)
outs = jaxpr_subcomp(c, jaxpr, backend, axis_env, consts, (), *xla_args)
return c.Tuple(*outs)
return f
def _aval_from_xla_shape(xla_shape):
if xla_shape.is_tuple() and not xla_shape.tuple_shapes():
return core.abstract_unit
else:
return ShapedArray(xla_shape.dimensions(), xla_shape.element_type())
### device-persistent data
class Token(object): pass
token = Token()
pytype_aval_mappings[Token] = lambda _: abstract_token
core.pytype_aval_mappings[Token] = lambda _: abstract_token
xla_shape_handlers[AbstractToken] = lambda _: xc.Shape.token_shape()
xla_result_handlers[AbstractToken] = lambda _, __: lambda _: token
canonicalize_dtype_handlers[Token] = identity
class DeviceValue(object):
"""A DeviceValue represents a value backed by device memory."""
__slots__ = ["aval", "device_buffer", "__weakref__"]
def __init__(self, aval, device_buffer):
self.aval = aval
self.device_buffer = device_buffer
def _check_if_deleted(self):
if self.device_buffer is None:
raise ValueError("DeviceValue has been deleted.")
def block_until_ready(self):
"""Blocks the caller until the buffer's value has been computed on device.
This method is mostly useful for timing microbenchmarks that wish to
time how long a computation takes, without transferring the result back
to the host.
Returns the buffer object (`self`).
"""
self._check_if_deleted()
self.device_buffer.block_host_until_ready()
return self
def _forward_method(attrname, self, fun, *args):
return fun(getattr(self, attrname), *args)
_forward_to_value = partial(_forward_method, "_value")
class DeviceArray(DeviceValue):
"""A DeviceArray is an ndarray backed by a single device memory buffer."""
# We don't subclass ndarray because that would open up a host of issues,
# but lax_numpy.py overrides isinstance behavior and attaches ndarray methods.
__slots__ = ["_npy_value", "_device"]
__array_priority__ = 100
def __init__(self, aval, device, device_buffer):
self.aval = aval
self.device_buffer = device_buffer
self._device = device and (type(device), device.id)
self._npy_value = None
if not core.skip_checks:
assert type(aval) is ShapedArray
npy_value = self._value
assert npy_value.dtype == aval.dtype and npy_value.shape == aval.shape
@property
def _value(self):
self._check_if_deleted()
if self._npy_value is None:
self._npy_value = self.device_buffer.to_py()
self._npy_value.flags.writeable = False
return self._npy_value
@property
def shape(self):
return self.aval.shape
@property
def dtype(self):
return self.aval.dtype
@property
def size(self):
return prod(self.aval.shape)
@property
def ndim(self):
return len(self.aval.shape)
def copy(self):
"""Returns an ndarray (backed by host memory, not device memory)."""
return onp.asarray(self)
def copy_to_host_async(self):
"""Requests a copy of the buffer to the host."""
self._check_if_deleted()
if self._npy_value is None:
self.device_buffer.copy_to_host_async()
def delete(self):
"""Deletes the device array and any cached copy on the host.
It is an error to access the contents of a `DeviceArray` after it has
been deleted.
Use of this method is optional; device buffers will be reclaimed
automatically by Python when a DeviceArray object is garbage collected.
However, it is sometimes useful to have more explicit control over the
time of deletion.
"""
self.device_buffer.delete()
self.device_buffer = None
self._npy_value = None
def __repr__(self):
line_width = onp.get_printoptions()['linewidth']
prefix = '{}('.format(self.__class__.__name__)
s = onp.array2string(self._value, prefix=prefix, suffix=',',
separator=', ', max_line_width=line_width)
dtype_str = 'dtype={})'.format(self.dtype.name)
last_line_len = len(s) - s.rfind('\n') + 1
sep = ' '
if last_line_len + len(dtype_str) + 1 > line_width:
sep = ' ' * len(prefix)
return "{}{},{}{}".format(prefix, s, sep, dtype_str)
def item(self):
if dtypes.issubdtype(self.dtype, onp.complexfloating):
return complex(self)
elif dtypes.issubdtype(self.dtype, onp.floating):
return float(self)
elif dtypes.issubdtype(self.dtype, onp.integer):
return int(self)
elif dtypes.issubdtype(self.dtype, onp.bool_):
return bool(self)
else:
raise TypeError(self.dtype)
def __len__(self):
try:
return self.aval.shape[0]
except IndexError:
raise TypeError("len() of unsized object") # same as numpy error
def __iter__(self):
if self.ndim == 0:
raise TypeError("iteration over a 0-d array") # same as numpy error
else:
return self._value.__iter__()
def __reversed__(self):
if self.ndim == 0:
raise TypeError("iteration over a 0-d array")
else:
return reversed(self._value)
def __format__(self, format_spec):
# Simulates behavior of https://github.com/numpy/numpy/pull/9883
if self.ndim == 0:
return format(self._value[()], format_spec)
else:
return format(self._value, format_spec)
def __array__(self, dtype=None, context=None):
return onp.asarray(self._value, dtype=dtype)
__str__ = partialmethod(_forward_to_value, str)
__bool__ = __nonzero__ = partialmethod(_forward_to_value, bool)
__float__ = partialmethod(_forward_to_value, float)
__int__ = partialmethod(_forward_to_value, int)
if six.PY2:
__long__ = partialmethod(_forward_to_value, long) # noqa: F821
__complex__ = partialmethod(_forward_to_value, complex)
__hex__ = partialmethod(_forward_to_value, hex)
__oct__ = partialmethod(_forward_to_value, oct)
__index__ = partialmethod(_forward_to_value, op.index)
# pickle saves and loads just like an ndarray
__reduce__ = partialmethod(_forward_to_value, op.methodcaller("__reduce__"))
# clobbered when jax.numpy is imported, but useful in tests
def __eq__(self, other): return self._value == other
def __hash__(self):
raise TypeError("JAX DeviceArray, like numpy.ndarray, is not hashable.")
core.literalable_types.add(DeviceArray)
core.pytype_aval_mappings[DeviceArray] = ConcreteArray
pytype_aval_mappings[DeviceArray] = lambda x: x.aval
canonicalize_dtype_handlers[DeviceArray] = identity
def _device_array_constant_handler(c, val, canonicalize_types=True):
return c.Constant(onp.asarray(val), canonicalize_types=canonicalize_types)
xb.register_constant_handler(DeviceArray, _device_array_constant_handler)
def _device_put_device_array(x, device):
# TODO(skye): we're assuming the DeviceBuffers without "platform" are
# XrtBuffers. Figure out a less risky way to deal with XrtBuffers.
if (not hasattr(x.device_buffer, "platform") or
xb.get_device_backend(device).platform == x.device_buffer.platform()):
if device is None or x.device_buffer.device() == device:
return x.device_buffer
else:
return x.device_buffer.copy_to_device(device)
else:
# Buffers from different XLA backends are passed through the host.
return xc.Buffer.from_pyval(x, device, backend=xb.get_device_backend(device))
device_put_handlers[DeviceArray] = _device_put_device_array
def _device_put_impl(x, device=None):
try:
a = abstractify(x)
except TypeError:
raise TypeError("Argument '{}' of type {} is not a valid JAX type"
.format(x, type(x)))
handler = aval_to_result_handler(device, a)
return handler(device_put(x, device))
device_put_p = core.Primitive('device_put')
device_put_p.def_impl(_device_put_impl)
pe.custom_partial_eval_rules[device_put_p] = lambda trace, x, **params: x
ad.deflinear(device_put_p, lambda cotangent, **kwargs: [cotangent])
def _remat_translation_rule(c, jaxpr, axis_env, const_nodes, freevar_nodes, in_nodes,
backend, device=None, concrete=None):
# This looks a lot like _xla_call_translation_rule, except for a widget we use
# to foil CSE.
del device, concrete # Unused.
subc = xb.make_computation_builder("remat_call_subcomputation")
consts = [subc.ParameterWithShape(c.GetShape(n)) for n in const_nodes]
freevars = [subc.ParameterWithShape(c.GetShape(n)) for n in freevar_nodes]
args = [subc.ParameterWithShape(c.GetShape(n)) for n in in_nodes]
args = [_foil_cse(subc, x) for x in args]
out_nodes = jaxpr_subcomp(subc, jaxpr, backend, axis_env, consts, freevars, *args)
subc = subc.Build(subc.Tuple(*out_nodes))
return c.Call(subc, list(const_nodes) + list(freevar_nodes) + list(in_nodes))
call_translations[pe.remat_call_p] = _remat_translation_rule
def _foil_cse(c, x):
xla_shape = c.GetShape(x)
if xla_shape.is_tuple():
assert not xla_shape.tuple_shapes()
return x
else:
rng = c.RngNormal(c.Constant(onp.array(0, dtype=onp.float32)),
c.Constant(onp.array(1, dtype=onp.float32)),
[])
pred = c.Lt(rng, c.Constant(onp.finfo(onp.float32).max))
shape, dtype = xla_shape.dimensions(), xla_shape.numpy_dtype()
zero = c.Broadcast(c.Constant(onp.array(0, dtype=dtype)), shape)
return c.Select(pred, x, zero)
### lazy constants
class DeviceConstant(DeviceArray):
def copy_to_host_async(self): pass
@staticmethod
def constant_handler(c, constant_instance, canonicalize_types=True):
assert False
def _instantiate_device_constant(const, device=None, backend=None, cutoff=1e6):
# dispatch an XLA Computation to build the constant on the device if it's
# large, or alternatively build it on the host and transfer it if it's small
assert isinstance(const, DeviceConstant)
backend = xb.get_backend(device.platform) if device else xb.get_backend(backend)
if const.size > cutoff:
c = xb.make_computation_builder("constant_instantiating_computation")
xla_const = const.constant_handler(c, const)
device_assignment = (device.id,) if device else None
opts = xb.get_compile_options(device_assignment=device_assignment)
compiled = c.Build(xla_const).Compile((), opts, backend=backend)
return compiled.Execute(())
else:
return xc.Buffer.from_pyval(onp.asarray(const), device, backend=backend)
|
jax-master
|
jax/interpreters/xla.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import itertools as it
from . import partial_eval as pe
from .. import core as core
from ..core import Trace, Tracer, new_master, get_aval, call_p, Primitive, Literal
from ..ad_util import (add_jaxvals, add_jaxvals_p, zeros_like_jaxval, zeros_like_aval,
zeros_like_p, zero)
from ..abstract_arrays import raise_to_shaped
from ..util import unzip2, safe_map, safe_zip, partial, split_list
from ..tree_util import register_pytree_node
from .. import linear_util as lu
from ..api_util import flatten_fun, flatten_fun_nokwargs
from ..tree_util import tree_flatten, tree_unflatten
from six.moves import reduce
zip = safe_zip
map = safe_map
def identity(x): return x
def jvp(fun, has_aux=False, instantiate=True):
if not has_aux:
return jvpfun(jvp_subtrace(fun), instantiate)
else:
fun, aux = jvp_subtrace_aux(fun)
return jvpfun(fun, instantiate), aux
@lu.transformation
def jvpfun(instantiate, primals, tangents):
with new_master(JVPTrace) as master:
out_primals, out_tangents = yield (master, primals, tangents), {}
del master
if type(instantiate) is bool:
instantiate = [instantiate] * len(out_tangents)
out_tangents = [instantiate_zeros(x, t) if inst else t for x, t, inst
in zip(out_primals, out_tangents, instantiate)]
yield out_primals, out_tangents
@lu.transformation
def jvp_subtrace(master, primals, tangents):
trace = JVPTrace(master, core.cur_sublevel())
for x in list(primals) + list(tangents):
if isinstance(x, Tracer):
assert x.trace.level < trace.level
in_tracers = [JVPTracer(trace, x, t) if t is not zero else x
for x, t in zip(primals, tangents)]
ans = yield in_tracers, {}
out_tracers = map(trace.full_raise, ans)
yield unzip2([(out_tracer.primal, out_tracer.tangent)
for out_tracer in out_tracers])
@lu.transformation_with_aux
def jvp_subtrace_aux(master, primals, tangents):
trace = JVPTrace(master, core.cur_sublevel())
for x in list(primals) + list(tangents):
if isinstance(x, Tracer):
assert x.trace.level < trace.level
ans, aux = yield map(partial(JVPTracer, trace), primals, tangents), {}
ans_tracers = map(trace.full_raise, ans)
aux_tracers = map(trace.full_raise, aux)
out_primals, out_tangents = unzip2((t.primal, t.tangent) for t in ans_tracers)
aux_primals, _ = unzip2((t.primal, t.tangent) for t in aux_tracers)
yield (out_primals, out_tangents), aux_primals
def linearize(traceable, *primals, **kwargs):
has_aux = kwargs.pop('has_aux', False)
if not has_aux:
jvpfun = jvp(traceable)
else:
jvpfun, aux = jvp(traceable, has_aux=True)
in_pvals = (tuple(pe.PartialVal((None, p)) for p in primals)
+ tuple(pe.PartialVal((get_aval(p).at_least_vspace(), core.unit))
for p in primals))
_, in_tree = tree_flatten(((primals, primals), {}))
jvpfun_flat, out_tree = flatten_fun(jvpfun, in_tree)
jaxpr, out_pvals, consts = pe.trace_to_jaxpr(jvpfun_flat, in_pvals)
pval_primals, pval_tangents = tree_unflatten(out_tree(), out_pvals)
aval_primals, const_primals = unzip2(pval_primals)
assert all(aval_primal is None for aval_primal in aval_primals)
if not has_aux:
return const_primals, pval_tangents, jaxpr, consts
else:
return const_primals, pval_tangents, jaxpr, consts, aux()
def vjp(traceable, primals, has_aux=False):
if not has_aux:
out_primals, pvals, jaxpr, consts = linearize(traceable, *primals)
else:
out_primals, pvals, jaxpr, consts, aux = linearize(traceable, *primals, has_aux=True)
def vjp_(*cts):
cts = tuple(map(ignore_consts, cts, pvals))
dummy_primals_and_cts = (core.unit,) * len(cts) + cts
dummy_args = (undefined_primal,) * len(jaxpr.invars)
_, arg_cts = backward_pass(jaxpr, consts, (), dummy_args, dummy_primals_and_cts)
arg_cts = arg_cts[len(primals):]
return map(instantiate_zeros, primals, arg_cts)
if not has_aux:
return out_primals, vjp_
else:
return out_primals, vjp_, aux
def ignore_consts(ct, pval):
aval, const = pval
if isinstance(aval, core.AbstractValue):
return ct
elif aval is None:
return core.unit
else:
raise TypeError(aval)
def unpair_pval(pval):
aval, const = pval
const_1, const_2 = const
if aval is None:
return (None, const_1), (None, const_2)
else:
aval_1, aval_2 = aval
return (aval_1, const_1), (aval_2, const_2)
def backward_pass(jaxpr, consts, freevar_vals, args, cotangents_in):
if all(ct is zero for ct in cotangents_in):
return [zero] * len(jaxpr.freevars), [zero] * len(jaxpr.invars)
def write_cotangent(v, ct):
# assert v not in primal_env
if ct is not None:
ct_env[v] = add_tangents(ct_env[v], ct) if v in ct_env else ct
def read_cotangent(v):
return ct_env.get(v, zero)
def read_primal(v):
if type(v) is Literal:
return v.val
else:
return primal_env.get(v, undefined_primal)
def write_primal(v, val):
if val is not undefined_primal:
primal_env[v] = val
primal_env = {}
write_primal(core.unitvar, core.unit)
map(write_primal, jaxpr.constvars, consts)
map(write_primal, jaxpr.freevars, freevar_vals)
map(write_primal, jaxpr.invars, args)
def is_linear(var):
if type(var) is Literal:
return False
else:
return primal_env.get(var, undefined_primal) is undefined_primal
linear_eqns = []
for eqn in jaxpr.eqns:
if not eqn.bound_subjaxprs:
if any(is_linear(v) for v in eqn.invars):
linear_eqns.append(eqn)
else:
in_vals = map(read_primal, eqn.invars)
ans = eqn.primitive.bind(*in_vals, **eqn.params)
if eqn.primitive.multiple_results:
map(write_primal, eqn.outvars, ans)
else:
write_primal(eqn.outvars[0], ans)
else:
(subjaxpr, const_vars, bound_vars), = eqn.bound_subjaxprs
assert not any(is_linear(v) for v in const_vars)
if any(is_linear(v) for v in it.chain(eqn.invars, bound_vars)):
linear_eqns.append(eqn)
elif eqn.primitive is not pe.remat_call_p:
ans = _eval_subjaxpr_primals(
eqn.primitive, subjaxpr, map(read_primal, const_vars),
map(read_primal, bound_vars), map(read_primal, eqn.invars), eqn.params)
map(write_primal, eqn.outvars, ans)
# we special-case remat_call here because it can be mixed linear /
# nonlinear, so we always evaluate it even if it has a linear part
if eqn.primitive is pe.remat_call_p:
ans = _eval_subjaxpr_primals(
eqn.primitive, subjaxpr, map(read_primal, const_vars),
map(read_primal, bound_vars), map(read_primal, eqn.invars), eqn.params)
map(write_primal, eqn.outvars, ans)
ct_env = {}
map(write_cotangent, jaxpr.outvars, cotangents_in)
for eqn in linear_eqns[::-1]:
invals = map(read_primal, eqn.invars)
if eqn.primitive.multiple_results:
cts_in = map(read_cotangent, eqn.outvars)
else:
cts_in, = map(read_cotangent, eqn.outvars)
if eqn.bound_subjaxprs:
(subjaxpr, const_vars, bound_vars), = eqn.bound_subjaxprs
sub_consts = map(read_primal, const_vars)
sub_freevar_vals = map(read_primal, bound_vars)
ct_free_vars_out, cts_out = get_primitive_transpose(eqn.primitive)(
eqn.params, subjaxpr, sub_consts, sub_freevar_vals, invals, cts_in)
map(write_cotangent, bound_vars, ct_free_vars_out)
else:
cts_out = get_primitive_transpose(eqn.primitive)(cts_in, *invals, **eqn.params)
cts_out = [zero] * len(eqn.invars) if cts_out is zero else cts_out
map(write_cotangent, eqn.invars, cts_out)
freevar_cts = map(read_cotangent, jaxpr.freevars)
cotangents_out = map(read_cotangent, jaxpr.invars)
return freevar_cts, cotangents_out
def _eval_subjaxpr_primals(prim, jaxpr, consts, freevar_vals, in_vals, params):
all_args, in_tree_def = tree_flatten((consts, freevar_vals, in_vals))
fun = lu.hashable_partial(lu.wrap_init(_eval_primals), jaxpr)
fun, out_tree = flatten_fun_nokwargs(fun, in_tree_def)
out_flat = prim.bind(fun, *all_args, **params)
return tree_unflatten(out_tree(), out_flat)
def _eval_primals(jaxpr, consts, freevar_vals, args):
primal_env = {}
def read_primal(v):
if type(v) is Literal:
return v.val
else:
return primal_env.get(v, undefined_primal)
def write_primal(v, val):
if val is not undefined_primal:
primal_env[v] = val
def is_linear(var):
if type(var) is Literal:
return False
else:
return primal_env.get(var, undefined_primal) is undefined_primal
write_primal(core.unitvar, core.unit)
map(write_primal, jaxpr.constvars, consts)
map(write_primal, jaxpr.freevars, freevar_vals)
map(write_primal, jaxpr.invars, args)
for eqn in jaxpr.eqns:
if not eqn.bound_subjaxprs:
if not any(is_linear(v) for v in eqn.invars):
in_vals = map(read_primal, eqn.invars)
ans = eqn.primitive.bind(*in_vals, **eqn.params)
if eqn.primitive.multiple_results:
map(write_primal, eqn.outvars, ans)
else:
write_primal(eqn.outvars[0], ans)
else:
(subjaxpr, const_vars, bound_vars), = eqn.bound_subjaxprs
assert not any(is_linear(v) for v in const_vars)
if (eqn.primitive is pe.remat_call_p or
not any(is_linear(v) for v in it.chain(eqn.invars, bound_vars))):
ans = _eval_subjaxpr_primals(
eqn.primitive, subjaxpr, map(read_primal, const_vars),
map(read_primal, bound_vars), map(read_primal, eqn.invars), eqn.params)
map(write_primal, eqn.outvars, ans)
return map(read_primal, jaxpr.outvars)
class UndefinedPrimal(object):
def __repr__(self): return '_'
undefined_primal = UndefinedPrimal()
register_pytree_node(UndefinedPrimal,
lambda z: ((), None),
lambda *_: undefined_primal)
def get_primitive_transpose(p):
try:
return primitive_transposes[p]
except KeyError:
raise NotImplementedError(
"Reverse-mode differentiation rule for '{}' not implemented".format(p))
class JVPTrace(Trace):
def pure(self, val):
return JVPTracer(self, val, zero)
def lift(self, val):
return JVPTracer(self, val, zero)
def sublift(self, val):
return JVPTracer(self, val.primal, val.tangent)
def process_primitive(self, primitive, tracers, params):
primals_in, tangents_in = unzip2((t.primal, t.tangent) for t in tracers)
try:
jvp = primitive_jvps[primitive]
except KeyError:
raise NotImplementedError(
"Forward-mode differentiation rule for '{}' not implemented"
.format(primitive))
primal_out, tangent_out = jvp(primals_in, tangents_in, **params)
if primitive.multiple_results:
return [JVPTracer(self, x, t) for x, t in zip(primal_out, tangent_out)]
else:
return JVPTracer(self, primal_out, tangent_out)
def process_call(self, call_primitive, f, tracers, params):
assert call_primitive.multiple_results
primals = [t.primal for t in tracers]
tangents = [t.tangent for t in tracers]
nonzero_tangents, in_tree_def = tree_flatten(tangents)
f_jvp, out_tree_def = traceable(jvp_subtrace(f, self.master), len(primals), in_tree_def)
result = call_primitive.bind(f_jvp, *(primals + nonzero_tangents), **params)
primal_out, tangent_out = tree_unflatten(out_tree_def(), result)
return [JVPTracer(self, p, t) for p, t in zip(primal_out, tangent_out)]
def post_process_call(self, call_primitive, out_tracers, params):
primals, tangents = unzip2((t.primal, t.tangent) for t in out_tracers)
out = primals + tangents
del primals, tangents
master = self.master
def todo(x):
n = len(x) // 2
primals, tangents = x[:n], x[n:]
trace = JVPTrace(master, core.cur_sublevel())
return map(partial(JVPTracer, trace), primals, tangents)
return out, todo
def join(self, xt, yt):
xz, yz = xt is zero, yt is zero
if xz == yz:
return xt, yt
elif yz and not xz:
return xt, zeros_like_jaxval(xt)
elif xz and not yz:
return zeros_like_jaxval(yt), yt
else:
raise TypeError((xt, yt))
class JVPTracer(Tracer):
__slots__ = ['primal', 'tangent']
def __init__(self, trace, primal, tangent):
if not core.skip_checks:
_primal_tangent_shapes_match(primal, tangent)
self.trace = trace
self.primal = primal
self.tangent = tangent
@property
def aval(self):
# TODO(dougalm): add epsilon ball
return get_aval(self.primal)
def full_lower(self):
if self.tangent is zero:
return core.full_lower(self.primal)
else:
return self
def _primal_tangent_shapes_match(primal, tangent):
if tangent is not zero:
primal_aval = raise_to_shaped(get_aval(primal))
tangent_aval = raise_to_shaped(get_aval(tangent))
assert primal_aval == tangent_aval
# -------------------- Primitives --------------------
primitive_jvps = {}
composite_jvps = {}
primitive_transposes = {}
def deflinear(primitive, transpose_rule):
primitive_jvps[primitive] = partial(linear_jvp, primitive)
primitive_transposes[primitive] = partial(linear_transpose, transpose_rule)
def linear_jvp(primitive, primals, tangents, **params):
val_out = primitive.bind(*primals, **params)
if all(tangent is zero for tangent in tangents):
return val_out, zero
else:
tangents = map(instantiate_zeros, primals, tangents)
return val_out, primitive.bind(*tangents, **params)
def linear_transpose(transpose_rule, cotangent, *args, **kwargs):
return zero if cotangent is zero else transpose_rule(cotangent, **kwargs)
def defjvp(primitive, *jvprules):
assert isinstance(primitive, Primitive)
primitive_jvps[primitive] = partial(standard_jvp, jvprules, primitive)
def standard_jvp(jvprules, primitive, primals, tangents, **params):
val_out = primitive.bind(*primals, **params)
tangents_out = [rule(t, *primals, **params) for rule, t in zip(jvprules, tangents)
if rule is not None and t is not zero]
return val_out, reduce(add_tangents, tangents_out, zero)
def defjvp2(primitive, *jvprules):
assert isinstance(primitive, Primitive)
primitive_jvps[primitive] = partial(standard_jvp2, jvprules, primitive)
def standard_jvp2(jvprules, primitive, primals, tangents, **params):
val_out = primitive.bind(*primals, **params)
tangents_out = (rule(t, val_out, *primals, **params) for rule, t in zip(jvprules, tangents)
if rule is not None and t is not zero)
return val_out, reduce(add_tangents, tangents_out, zero)
def add_tangents(x, y):
if x is zero:
return y
elif y is zero:
return x
else:
return add_jaxvals(x, y)
def defvjp_all(prim, custom_vjp):
# see https://github.com/google/jax/pull/636
name = prim.name
def fun_jvp(xs, ts, **params):
ts = map(instantiate_zeros, xs, ts)
primals_and_tangents = fun_jvp_p.bind(*it.chain(xs, ts), **params)
primals, tangents = split_list(primals_and_tangents, [len(primals_and_tangents) // 2])
if prim.multiple_results:
return primals, tangents
else:
primal, = primals
tangent, = tangents
return primal, tangent
primitive_jvps[prim] = fun_jvp
fun_jvp_p = core.Primitive('{name}_jvp'.format(name=name))
fun_jvp_p.multiple_results = True
def fun_jvp_partial_eval(trace, *tracers, **params):
primals, tangents = split_list(tracers, [len(tracers) // 2])
primals_out, vjp_py = custom_vjp(*primals, **params)
if not prim.multiple_results:
primals_out = [primals_out]
out_avals = [raise_to_shaped(get_aval(x)) for x in primals_out]
ct_pvals = [pe.PartialVal((aval, core.unit)) for aval in out_avals]
jaxpr, _, res = pe.trace_to_jaxpr(lu.wrap_init(vjp_py), ct_pvals, instantiate=True)
tangents_out = fun_lin_p.bind(*it.chain(res, tangents), trans_jaxpr=jaxpr,
num_res=len(res), out_avals=out_avals)
return primals_out + tangents_out
pe.custom_partial_eval_rules[fun_jvp_p] = fun_jvp_partial_eval
fun_lin_p = core.Primitive('{name}_lin'.format(name=name))
fun_lin_p.multiple_results = True
fun_lin_p.def_abstract_eval(lambda *_, **kwargs: kwargs['out_avals'])
def fun_lin_transpose(cts, *args, **kwargs):
num_res, trans_jaxpr = kwargs['num_res'], kwargs['trans_jaxpr']
res, _ = split_list(args, [num_res])
cts = map(instantiate_zeros_aval, kwargs['out_avals'], cts)
outs = core.eval_jaxpr(trans_jaxpr, res, (), *cts)
return [None] * num_res + outs
primitive_transposes[fun_lin_p] = fun_lin_transpose
def defvjp(prim, *vjps):
def vjpmaker(*primals):
ans = prim.bind(*primals)
vjpfun = lambda ct: [vjp(ct, *primals) if vjp else zeros_like_jaxval(x)
for x, vjp in zip(primals, vjps)]
return ans, vjpfun
defvjp_all(prim, vjpmaker)
def defvjp2(prim, *vjps):
def vjpmaker(*primals):
ans = prim.bind(*primals)
vjpfun = lambda ct: [vjp(ct, ans, *primals) if vjp else zeros_like_jaxval(x)
for x, vjp in zip(primals, vjps)]
return ans, vjpfun
defvjp_all(prim, vjpmaker)
def defbilinear_broadcasting(bcast, prim, lhs_rule, rhs_rule):
assert isinstance(prim, Primitive)
lhs_jvp = lambda g, x, y, **kwargs: prim.bind(bcast(g, y), y, **kwargs)
rhs_jvp = lambda g, x, y, **kwargs: prim.bind(x, bcast(g, x), **kwargs)
defjvp(prim, lhs_jvp, rhs_jvp)
primitive_transposes[prim] = partial(bilinear_transpose, lhs_rule, rhs_rule)
defbilinear = partial(defbilinear_broadcasting, lambda g, x: g)
def bilinear_transpose(lhs_rule, rhs_rule, cotangent, x, y, **kwargs):
assert (x is undefined_primal) ^ (y is undefined_primal)
if x is undefined_primal:
out = zero if cotangent is zero else lhs_rule(cotangent, y, **kwargs)
return out, None
else:
out = zero if cotangent is zero else rhs_rule(cotangent, x, **kwargs)
return None, out
def defjvp_zero(primitive):
assert isinstance(primitive, Primitive)
primitive_jvps[primitive] = partial(zero_jvp, primitive)
def zero_jvp(primitive, primals, tangents, **params):
return primitive.bind(*primals, **params), zero
deflinear(zeros_like_p, lambda t: [zero])
deflinear(core.identity_p, lambda t: (t,))
deflinear(add_jaxvals_p, lambda t: (t, t))
def instantiate_zeros(example, tangent):
if tangent is zero:
return zeros_like_jaxval(example)
else:
return tangent
def instantiate_zeros_aval(aval, tangent):
if tangent is zero:
return zeros_like_aval(aval)
else:
return tangent
@lu.transformation_with_aux
def traceable(num_primals, in_tree_def, *primals_and_tangents):
new_primals = primals_and_tangents[:num_primals]
new_tangents = primals_and_tangents[num_primals:]
new_tangents = tree_unflatten(in_tree_def, new_tangents)
primal_out, tangent_out = yield (new_primals, new_tangents), {}
out_flat, tree_def = tree_flatten((primal_out, tangent_out))
yield out_flat, tree_def
def call_transpose(primitive, params, jaxpr, consts, freevar_vals, args, ct):
all_args, in_tree_def = tree_flatten((consts, freevar_vals, args, ct))
fun = lu.hashable_partial(lu.wrap_init(backward_pass), jaxpr)
fun, out_tree = flatten_fun_nokwargs(fun, in_tree_def)
out_flat = primitive.bind(fun, *all_args, **params)
return tree_unflatten(out_tree(), out_flat)
primitive_transposes[core.call_p] = partial(call_transpose, call_p)
primitive_transposes[pe.remat_call_p] = partial(call_transpose, pe.remat_call_p)
def map_transpose(primitive, params, jaxpr, consts, freevar_vals, args, ct):
all_args, in_tree_def = tree_flatten((consts, freevar_vals, args, ct))
fun = lu.hashable_partial(lu.wrap_init(backward_pass), jaxpr)
fun, out_tree = flatten_fun_nokwargs(fun, in_tree_def)
out_flat = primitive.bind(fun, *all_args, **params)
freevar_cts, arg_cts = tree_unflatten(out_tree(), out_flat)
freevar_cts = [x.sum(0) if x is not zero else x for x in freevar_cts]
return freevar_cts, arg_cts
def jvp_jaxpr(jaxpr, nonzeros, instantiate):
assert len(jaxpr.in_avals) == len(nonzeros)
f = lu.wrap_init(core.jaxpr_as_fun(jaxpr))
f_jvp, out_nonzeros = f_jvp_traceable(jvp(f, instantiate=instantiate), nonzeros)
tangent_avals = [aval for aval, nz in zip(jaxpr.in_avals, nonzeros) if nz]
avals_in = list(it.chain(jaxpr.in_avals, tangent_avals))
pvals = [pe.PartialVal((aval, core.unit)) for aval in avals_in]
jaxpr_out, pvals_out, literals_out = pe.trace_to_jaxpr(f_jvp, pvals, instantiate=True)
avals_out, _ = unzip2(pvals_out)
jaxpr_out = core.TypedJaxpr(jaxpr_out, literals_out, avals_in, avals_out)
return jaxpr_out, out_nonzeros()
@lu.transformation_with_aux
def f_jvp_traceable(nonzeros, *primals_and_nztangents):
num_primals = len(nonzeros)
primals = list(primals_and_nztangents[:num_primals])
nonzero_tangents = iter(primals_and_nztangents[num_primals:])
tangents = [next(nonzero_tangents) if nz else zero for nz in nonzeros]
primals_out, tangents_out = yield (primals, tangents), {}
out_nonzeros = [t is not zero for t in tangents_out]
nonzero_tangents_out = [t for t in tangents_out if t is not zero]
yield list(primals_out) + nonzero_tangents_out, out_nonzeros
def rearrange_binders(jaxpr, primals_in, tangents_in, primals_out, tangents_out):
new_invars = _perm(primals_in, tangents_in, jaxpr.jaxpr.invars)
new_outvars = _perm(primals_out, tangents_out, jaxpr.jaxpr.outvars)
new_jaxpr = core.Jaxpr(jaxpr.jaxpr.constvars, jaxpr.jaxpr.freevars,
new_invars, new_outvars, jaxpr.jaxpr.eqns)
new_in_avals = _perm(primals_in, tangents_in, jaxpr.in_avals)
new_out_avals = _perm(primals_out, tangents_out, jaxpr.out_avals)
new_typed_jaxpr = core.TypedJaxpr(new_jaxpr, jaxpr.literals, new_in_avals,
new_out_avals)
return new_typed_jaxpr
def _perm(primal_counts, tangent_counts, lst):
n = sum(primal_counts)
primals, tangents = lst[:n], lst[n:]
primal_groups = split_list(primals, primal_counts[:-1])
tangent_groups = split_list(tangents, tangent_counts[:-1])
return _interleave(primal_groups, tangent_groups)
def _interleave(xs, ys):
assert len(xs) == len(ys)
return [e for pair in zip(xs, ys) for l in pair for e in l]
|
jax-master
|
jax/interpreters/ad.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
"""Stax is a small but flexible neural net specification library from scratch.
For an example of its use, see examples/resnet50.py.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
import itertools
import operator as op
import numpy as onp
from six.moves import reduce
from jax import lax
from jax import random
import jax.numpy as np
from jax.nn import (relu, log_softmax, softmax, softplus, sigmoid, elu,
leaky_relu, selu, gelu, normalize)
from jax.nn.initializers import glorot_normal, normal, ones, zeros
# aliases for backwards compatibility
glorot = glorot_normal
randn = normal
logsoftmax = log_softmax
# Following the convention used in Keras and tf.layers, we use CamelCase for the
# names of layer constructors, like Conv and Relu, while using snake_case for
# other functions, like lax.conv and relu.
# Each layer constructor function returns an (init_fun, apply_fun) pair, where
# init_fun: takes an rng key and an input shape and returns an
# (output_shape, params) pair,
# apply_fun: takes params, inputs, and an rng key and applies the layer.
def Dense(out_dim, W_init=glorot_normal(), b_init=normal()):
"""Layer constructor function for a dense (fully-connected) layer."""
def init_fun(rng, input_shape):
output_shape = input_shape[:-1] + (out_dim,)
k1, k2 = random.split(rng)
W, b = W_init(k1, (input_shape[-1], out_dim)), b_init(k2, (out_dim,))
return output_shape, (W, b)
def apply_fun(params, inputs, **kwargs):
W, b = params
return np.dot(inputs, W) + b
return init_fun, apply_fun
def GeneralConv(dimension_numbers, out_chan, filter_shape,
strides=None, padding='VALID', W_init=None,
b_init=normal(1e-6)):
"""Layer construction function for a general convolution layer."""
lhs_spec, rhs_spec, out_spec = dimension_numbers
one = (1,) * len(filter_shape)
strides = strides or one
W_init = W_init or glorot_normal(rhs_spec.index('I'), rhs_spec.index('O'))
def init_fun(rng, input_shape):
filter_shape_iter = iter(filter_shape)
kernel_shape = [out_chan if c == 'O' else
input_shape[lhs_spec.index('C')] if c == 'I' else
next(filter_shape_iter) for c in rhs_spec]
output_shape = lax.conv_general_shape_tuple(
input_shape, kernel_shape, strides, padding, dimension_numbers)
bias_shape = [out_chan if c == 'C' else 1 for c in out_spec]
bias_shape = tuple(itertools.dropwhile(lambda x: x == 1, bias_shape))
k1, k2 = random.split(rng)
W, b = W_init(k1, kernel_shape), b_init(k2, bias_shape)
return output_shape, (W, b)
def apply_fun(params, inputs, **kwargs):
W, b = params
return lax.conv_general_dilated(inputs, W, strides, padding, one, one,
dimension_numbers=dimension_numbers) + b
return init_fun, apply_fun
Conv = functools.partial(GeneralConv, ('NHWC', 'HWIO', 'NHWC'))
def GeneralConvTranspose(dimension_numbers, out_chan, filter_shape,
strides=None, padding='VALID', W_init=None,
b_init=normal(1e-6)):
"""Layer construction function for a general transposed-convolution layer."""
lhs_spec, rhs_spec, out_spec = dimension_numbers
one = (1,) * len(filter_shape)
strides = strides or one
W_init = W_init or glorot_normal(rhs_spec.index('I'), rhs_spec.index('O'))
def init_fun(rng, input_shape):
filter_shape_iter = iter(filter_shape)
kernel_shape = [out_chan if c == 'O' else
input_shape[lhs_spec.index('C')] if c == 'I' else
next(filter_shape_iter) for c in rhs_spec]
output_shape = lax.conv_transpose_shape_tuple(
input_shape, kernel_shape, strides, padding, dimension_numbers)
bias_shape = [out_chan if c == 'C' else 1 for c in out_spec]
bias_shape = tuple(itertools.dropwhile(lambda x: x == 1, bias_shape))
k1, k2 = random.split(rng)
W, b = W_init(k1, kernel_shape), b_init(k2, bias_shape)
return output_shape, (W, b)
def apply_fun(params, inputs, **kwargs):
W, b = params
return lax.conv_transpose(inputs, W, strides, padding,
dimension_numbers=dimension_numbers) + b
return init_fun, apply_fun
Conv1DTranspose = functools.partial(GeneralConvTranspose, ('NHC', 'HIO', 'NHC'))
ConvTranspose = functools.partial(GeneralConvTranspose,
('NHWC', 'HWIO', 'NHWC'))
def BatchNorm(axis=(0, 1, 2), epsilon=1e-5, center=True, scale=True,
beta_init=zeros, gamma_init=ones):
"""Layer construction function for a batch normalization layer."""
_beta_init = lambda rng, shape: beta_init(rng, shape) if center else ()
_gamma_init = lambda rng, shape: gamma_init(rng, shape) if scale else ()
axis = (axis,) if np.isscalar(axis) else axis
def init_fun(rng, input_shape):
shape = tuple(d for i, d in enumerate(input_shape) if i not in axis)
k1, k2 = random.split(rng)
beta, gamma = _beta_init(k1, shape), _gamma_init(k2, shape)
return input_shape, (beta, gamma)
def apply_fun(params, x, **kwargs):
beta, gamma = params
# TODO(phawkins): np.expand_dims should accept an axis tuple.
# (https://github.com/numpy/numpy/issues/12290)
ed = tuple(None if i in axis else slice(None) for i in range(np.ndim(x)))
beta = beta[ed]
gamma = gamma[ed]
z = normalize(x, axis, epsilon=epsilon)
if center and scale: return gamma * z + beta
if center: return z + beta
if scale: return gamma * z
return z
return init_fun, apply_fun
def elementwise(fun, **fun_kwargs):
"""Layer that applies a scalar function elementwise on its inputs."""
init_fun = lambda rng, input_shape: (input_shape, ())
apply_fun = lambda params, inputs, **kwargs: fun(inputs, **fun_kwargs)
return init_fun, apply_fun
Tanh = elementwise(np.tanh)
Relu = elementwise(relu)
Exp = elementwise(np.exp)
LogSoftmax = elementwise(log_softmax, axis=-1)
Softmax = elementwise(softmax, axis=-1)
Softplus = elementwise(softplus)
Sigmoid = elementwise(sigmoid)
Elu = elementwise(elu)
LeakyRelu = elementwise(leaky_relu)
Selu = elementwise(selu)
Gelu = elementwise(gelu)
def _pooling_layer(reducer, init_val, rescaler=None):
def PoolingLayer(window_shape, strides=None, padding='VALID', spec='NHWC'):
"""Layer construction function for a pooling layer."""
strides = strides or (1,) * len(window_shape)
rescale = rescaler(window_shape, strides, padding) if rescaler else None
non_spatial_axes = spec.index('N'), spec.index('C')
for i in sorted(non_spatial_axes):
window_shape = window_shape[:i] + (1,) + window_shape[i:]
strides = strides[:i] + (1,) + strides[i:]
def init_fun(rng, input_shape):
out_shape = lax.reduce_window_shape_tuple(input_shape, window_shape,
strides, padding)
return out_shape, ()
def apply_fun(params, inputs, **kwargs):
out = lax.reduce_window(inputs, init_val, reducer, window_shape,
strides, padding)
return rescale(out, inputs, spec) if rescale else out
return init_fun, apply_fun
return PoolingLayer
MaxPool = _pooling_layer(lax.max, -np.inf)
SumPool = _pooling_layer(lax.add, 0.)
def _normalize_by_window_size(dims, strides, padding):
def rescale(outputs, inputs, spec):
non_spatial_axes = spec.index('N'), spec.index('C')
spatial_shape = tuple(inputs.shape[i]
for i in range(inputs.ndim)
if i not in non_spatial_axes)
one = np.ones(spatial_shape, dtype=inputs.dtype)
window_sizes = lax.reduce_window(one, 0., lax.add, dims, strides, padding)
for i in sorted(non_spatial_axes):
window_sizes = np.expand_dims(window_sizes, i)
return outputs / window_sizes
return rescale
AvgPool = _pooling_layer(lax.add, 0., _normalize_by_window_size)
def Flatten():
"""Layer construction function for flattening all but the leading dim."""
def init_fun(rng, input_shape):
output_shape = input_shape[0], reduce(op.mul, input_shape[1:], 1)
return output_shape, ()
def apply_fun(params, inputs, **kwargs):
return np.reshape(inputs, (inputs.shape[0], -1))
return init_fun, apply_fun
Flatten = Flatten()
def Identity():
"""Layer construction function for an identity layer."""
init_fun = lambda rng, input_shape: (input_shape, ())
apply_fun = lambda params, inputs, **kwargs: inputs
return init_fun, apply_fun
Identity = Identity()
def FanOut(num):
"""Layer construction function for a fan-out layer."""
init_fun = lambda rng, input_shape: ([input_shape] * num, ())
apply_fun = lambda params, inputs, **kwargs: [inputs] * num
return init_fun, apply_fun
def FanInSum():
"""Layer construction function for a fan-in sum layer."""
init_fun = lambda rng, input_shape: (input_shape[0], ())
apply_fun = lambda params, inputs, **kwargs: sum(inputs)
return init_fun, apply_fun
FanInSum = FanInSum()
def FanInConcat(axis=-1):
"""Layer construction function for a fan-in concatenation layer."""
def init_fun(rng, input_shape):
ax = axis % len(input_shape[0])
concat_size = sum(shape[ax] for shape in input_shape)
out_shape = input_shape[0][:ax] + (concat_size,) + input_shape[0][ax+1:]
return out_shape, ()
def apply_fun(params, inputs, **kwargs):
return np.concatenate(inputs, axis)
return init_fun, apply_fun
def Dropout(rate, mode='train'):
"""Layer construction function for a dropout layer with given rate."""
def init_fun(rng, input_shape):
return input_shape, ()
def apply_fun(params, inputs, **kwargs):
rng = kwargs.get('rng', None)
if rng is None:
msg = ("Dropout layer requires apply_fun to be called with a PRNG key "
"argument. That is, instead of `apply_fun(params, inputs)`, call "
"it like `apply_fun(params, inputs, key)` where `key` is a "
"jax.random.PRNGKey value.")
raise ValueError(msg)
if mode == 'train':
keep = random.bernoulli(rng, rate, inputs.shape)
return np.where(keep, inputs / rate, 0)
else:
return inputs
return init_fun, apply_fun
# Composing layers via combinators
def serial(*layers):
"""Combinator for composing layers in serial.
Args:
*layers: a sequence of layers, each an (init_fun, apply_fun) pair.
Returns:
A new layer, meaning an (init_fun, apply_fun) pair, representing the serial
composition of the given sequence of layers.
"""
nlayers = len(layers)
init_funs, apply_funs = zip(*layers)
def init_fun(rng, input_shape):
params = []
for init_fun in init_funs:
rng, layer_rng = random.split(rng)
input_shape, param = init_fun(layer_rng, input_shape)
params.append(param)
return input_shape, params
def apply_fun(params, inputs, **kwargs):
rng = kwargs.pop('rng', None)
rngs = random.split(rng, nlayers) if rng is not None else (None,) * nlayers
for fun, param, rng in zip(apply_funs, params, rngs):
inputs = fun(param, inputs, rng=rng, **kwargs)
return inputs
return init_fun, apply_fun
def parallel(*layers):
"""Combinator for composing layers in parallel.
The layer resulting from this combinator is often used with the FanOut and
FanInSum layers.
Args:
*layers: a sequence of layers, each an (init_fun, apply_fun) pair.
Returns:
A new layer, meaning an (init_fun, apply_fun) pair, representing the
parallel composition of the given sequence of layers. In particular, the
returned layer takes a sequence of inputs and returns a sequence of outputs
with the same length as the argument `layers`.
"""
nlayers = len(layers)
init_funs, apply_funs = zip(*layers)
def init_fun(rng, input_shape):
rngs = random.split(rng, nlayers)
return zip(*[init(rng, shape) for init, rng, shape
in zip(init_funs, rngs, input_shape)])
def apply_fun(params, inputs, **kwargs):
rng = kwargs.pop('rng', None)
rngs = random.split(rng, nlayers) if rng is not None else (None,) * nlayers
return [f(p, x, rng=r, **kwargs) for f, p, x, r in zip(apply_funs, params, inputs, rngs)]
return init_fun, apply_fun
def shape_dependent(make_layer):
"""Combinator to delay layer constructor pair until input shapes are known.
Args:
make_layer: a one-argument function that takes an input shape as an argument
(a tuple of positive integers) and returns an (init_fun, apply_fun) pair.
Returns:
A new layer, meaning an (init_fun, apply_fun) pair, representing the same
layer as returned by `make_layer` but with its construction delayed until
input shapes are known.
"""
def init_fun(rng, input_shape):
return make_layer(input_shape)[0](rng, input_shape)
def apply_fun(params, inputs, **kwargs):
return make_layer(inputs.shape)[1](params, inputs, **kwargs)
return init_fun, apply_fun
|
jax-master
|
jax/experimental/stax.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
"""A composable gradient processing and optimization library for JAX.
The `optix` module implements a number of composable gradient transformations,
typically used in the context of optimizing neural nets.
Each transformation defines:
* an `init_fn`, to initialize a (possibly empty) set of statistics, or `state`.
* an `update_fn` to transform an input gradient and update the state.
An (optional) `chain` utility can be used to build custom optimizers by
chaining arbitrary sequences of transformations. For any sequence of
transformations `chain` returns a single `init_fn` and `update_fn`.
An (optional) `apply_updates` function can be used to eventually apply the
transformed gradients to the set of parameters of interest.
Separating gradient transformations from the parameter update allows to flexibly
chain a sequence of transformations of the same gradients, as well as combine
multiple updates to the same parameters (e.g. in multi-task settings where the
different tasks may benefit from different sets of gradient transformations).
Many popular optimizers can be implemented using `optix` as one-liners, and,
for convenience, we provide aliases for some of the most popular ones.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
from jax import numpy as jnp
from jax import random as jrandom
from jax.tree_util import tree_leaves
from jax.tree_util import tree_multimap
from jax.tree_util import tree_structure
from jax.tree_util import tree_unflatten
### Composable gradient transformations. ###
InitUpdate = collections.namedtuple("InitUpdate", ("init", "update"))
ClipState = collections.namedtuple("ClipState", "")
def clip(max_delta):
"""Clip updates element-wise.
Args:
max_delta: the maximum size of an update, for each variable
Returns:
An (init_fn, update_fn) tuple.
"""
def init_fn(_):
return ClipState()
def update_fn(updates, state):
updates = tree_multimap(
lambda g: jnp.clip_by_value(g, -max_delta, max_delta), updates)
return updates, state
return InitUpdate(init_fn, update_fn)
ClipByGlobalNormState = collections.namedtuple("ClipByGlobalNormState", "")
def global_norm(items):
return jnp.sqrt(jnp.sum([jnp.sum(x**2) for x in tree_leaves(items)]))
_global_norm = global_norm # TODO(mtthss): remove when google code updated
def clip_by_global_norm(max_norm):
"""Clip updates using their global norm.
References:
[Pascanu et al, 2012](https://arxiv.org/abs/1211.5063)
Args:
max_norm: the maximum global norm for an update.
Returns:
An (init_fn, update_fn) tuple.
"""
def init_fn(_):
return ClipByGlobalNormState()
def update_fn(updates, state):
g_norm = global_norm(updates)
trigger = g_norm < max_norm
updates = tree_multimap(
lambda t: jnp.where(trigger, t, t * (max_norm / g_norm)), updates)
return updates, state
return InitUpdate(init_fn, update_fn)
TraceState = collections.namedtuple("TraceState", "trace")
def trace(decay, nesterov):
"""Compute a trace of past updates.
Args:
decay: the decay rate for the tracing of past updates.
nesterov: whether to use nesterov momentum.
Returns:
An (init_fn, update_fn) tuple.
"""
def init_fn(params):
return TraceState(trace=tree_multimap(jnp.zeros_like, params))
def update_fn(updates, state):
f = lambda g, t: g + decay * t
update_trace = tree_multimap(f, updates, state.trace)
updates = (
tree_multimap(f, updates, update_trace) if nesterov else update_trace)
return updates, TraceState(trace=update_trace)
return InitUpdate(init_fn, update_fn)
ScaleByRmsState = collections.namedtuple("ScaleByRmsState", "nu")
def _update_moment(updates, moments, decay, order):
return tree_multimap(
lambda g, t: (1 - decay) * (g ** order) + decay * t, updates, moments)
def scale_by_rms(decay=0.9, eps=1e-8):
"""Rescale updates by the root of the exp. moving avg of the square.
References:
[Hinton](www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf)
Args:
decay: decay rate for the exponentially weighted average of squared grads.
eps: term added to the denominator to improve numerical stability.
Returns:
An (init_fn, update_fn) tuple.
"""
def init_fn(params):
nu = tree_multimap(jnp.zeros_like, params) # second moment
return ScaleByRmsState(nu=nu)
def update_fn(updates, state):
nu = _update_moment(updates, state.nu, decay, 2)
updates = tree_multimap(lambda g, n: g / (jnp.sqrt(n + eps)), updates, nu)
return updates, ScaleByRmsState(nu=nu)
return InitUpdate(init_fn, update_fn)
ScaleByRStdDevState = collections.namedtuple("ScaleByRStdDevState", "mu nu")
def scale_by_stddev(decay=0.9, eps=1e-8):
"""Rescale updates by the root of the centered exp. moving average of squares.
References:
[Hinton](www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf)
Args:
decay: decay rate for the exponentially weighted average of squared grads.
eps: term added to the denominator to improve numerical stability.
Returns:
An (init_fn, update_fn) tuple.
"""
def init_fn(params):
mu = tree_multimap(jnp.zeros_like, params) # First moment
nu = tree_multimap(jnp.zeros_like, params) # Second moment
return ScaleByRStdDevState(mu=mu, nu=nu)
def update_fn(updates, state):
mu = _update_moment(updates, state.mu, decay, 1)
nu = _update_moment(updates, state.nu, decay, 2)
updates = tree_multimap(
lambda g, m, n: g / jnp.sqrt(n - m**2 + eps), updates, mu, nu)
return updates, ScaleByRStdDevState(mu=mu, nu=nu)
return InitUpdate(init_fn, update_fn)
ScaleByAdamState = collections.namedtuple("ScaleByAdamState", "count mu nu")
def scale_by_adam(b1=0.9, b2=0.999, eps=1e-8):
"""Rescale updates according to the Adam algorithm.
References:
[Kingma et al, 2014](https://arxiv.org/abs/1412.6980)
Args:
b1: decay rate for the exponentially weighted average of grads.
b2: decay rate for the exponentially weighted average of squared grads.
eps: term added to the denominator to improve numerical stability.
Returns:
An (init_fn, update_fn) tuple.
"""
def init_fn(params):
mu = tree_multimap(jnp.zeros_like, params) # First moment
nu = tree_multimap(jnp.zeros_like, params) # Second moment
return ScaleByAdamState(count=jnp.zeros([]), mu=mu, nu=nu)
def update_fn(updates, state):
mu = _update_moment(updates, state.mu, b1, 1)
nu = _update_moment(updates, state.nu, b2, 2)
mu_hat = tree_multimap(lambda t: t / (1 - b1 ** (state.count + 1)), mu)
nu_hat = tree_multimap(lambda t: t / (1 - b2 ** (state.count + 1)), nu)
updates = tree_multimap(
lambda m, v: m / (jnp.sqrt(v) + eps), mu_hat, nu_hat)
return updates, ScaleByAdamState(count=state.count + 1, mu=mu, nu=nu)
return InitUpdate(init_fn, update_fn)
ScaleState = collections.namedtuple("ScaleState", "")
def scale(step_size):
"""Scale updates by some fixed scalar `step_size`.
Args:
step_size: a scalar corresponding to a fixed scaling factor for updates.
Returns:
An (init_fn, update_fn) tuple.
"""
def init_fn(_):
return ScaleState()
def update_fn(updates, state):
updates = tree_multimap(lambda g: step_size * g, updates)
return updates, state
return InitUpdate(init_fn, update_fn)
ScaleByScheduleState = collections.namedtuple("ScaleByScheduleState", "count")
def scale_by_schedule(step_size_fn):
"""Scale updates using a custom schedule for the `step_size`.
Args:
step_size_fn: a function that takes an update count as input and proposes
the step_size to multiply the updates by.
Returns:
An (init_fn, update_fn) tuple.
"""
def init_fn(_):
return ScaleByScheduleState(count=jnp.zeros([]))
def update_fn(updates, state):
updates = tree_multimap(lambda g: step_size_fn(state.count) * g, updates)
return updates, ScaleByScheduleState(count=state.count + 1)
return InitUpdate(init_fn, update_fn)
AddNoiseState = collections.namedtuple("AddNoiseState", "count rng_key")
def add_noise(eta, gamma, seed):
"""Add gradient noise.
References:
[Neelakantan et al, 2014](https://arxiv.org/abs/1511.06807)
Args:
eta: base variance of the gaussian noise added to the gradient.
gamma: decay exponent for annealing of the variance.
seed: seed for random number generation.
Returns:
An (init_fn, update_fn) tuple.
"""
def init_fn(_):
return AddNoiseState(count=jnp.zeros([]), rng_key=jrandom.PRNGKey(seed))
def update_fn(updates, state): # pylint: disable=missing-docstring
num_vars = len(tree_leaves(updates))
treedef = tree_structure(updates)
variance = eta / (1 + state.count) ** gamma
all_keys = jrandom.split(state.rng_key, num=num_vars + 1)
noise = tree_multimap(
lambda g, k: jrandom.normal(k, shape=g.shape),
updates, tree_unflatten(treedef, all_keys[1:]))
updates = tree_multimap(
lambda g, n: g + variance * n, updates, noise)
return updates, AddNoiseState(count=state.count + 1, rng_key=all_keys[0])
return InitUpdate(init_fn, update_fn)
### Utilities for building and using custom optimizers. ###
def chain(*args):
"""Applies a list of chainable update transformations.
Given a sequence of chainable transforms, `chain` returns an `init_fn`
that constructs a `state` by concatenating the states of the individual
transforms, and returns an `update_fn` which chains the update transformations
feeding the appropriate state to each.
Args:
*args: a sequence of chainable (init_fn, update_fn) tuples.
Returns:
A single (init_fn, update_fn) tuple.
"""
init_fns, update_fns = zip(*args)
def init_fn(params):
return [fn(params) for fn in init_fns]
def update_fn(updates, state):
new_state = []
for s, fn in zip(state, update_fns):
updates, new_s = fn(updates, s)
new_state.append(new_s)
return updates, new_state
return InitUpdate(init_fn, update_fn)
def apply_updates(params, updates):
"""Applies an update to the corresponding parameters.
This is an (optional) utility functions that applies an update, and returns
the updated parameters to the caller. The update itself is typically the
result of applying any number of `chainable` transformations.
Args:
params: a tree of parameters.
updates: a tree of updates, the tree structure and the shape of the leaf
nodes must match that of `params`.
Returns:
Updated parameters, with same structure and shape as `params`.
"""
return tree_multimap(lambda p, u: p + u, params, updates)
### Aliases for popular optimizers. ###
def sgd(learning_rate, momentum=0., nesterov=False):
return chain(
trace(decay=momentum, nesterov=nesterov),
scale(-learning_rate))
def noisy_sgd(learning_rate, eta=0.01, gamma=0.55, seed=42):
return chain(
trace(decay=0., nesterov=False),
scale(-learning_rate),
add_noise(eta, gamma, seed))
def adam(learning_rate, b1=0.9, b2=0.999, eps=1e-8):
return chain(
scale_by_adam(b1=b1, b2=b2, eps=eps),
scale(-learning_rate))
def rmsprop(learning_rate, decay=0.9, eps=1e-8, centered=False):
if not centered:
return chain(
scale_by_rms(decay=decay, eps=eps),
scale(-learning_rate))
else:
return chain(
scale_by_stddev(decay=decay, eps=eps),
scale(-learning_rate))
|
jax-master
|
jax/experimental/optix.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
|
jax-master
|
jax/experimental/__init__.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
"""Optimizers for use with JAX.
This module contains some convenient optimizer definitions, specifically
initialization and update functions, which can be used with ndarrays or
arbitrarily-nested tuple/list/dicts of ndarrays.
An optimizer is modeled as an ``(init_fun, update_fun, get_params)`` triple of
functions, where the component functions have these signatures:
::
init_fun(params)
Args:
params: pytree representing the initial parameters.
Returns:
A pytree representing the initial optimizer state, which includes the
initial parameters and may also include auxiliary values like initial
momentum. The optimizer state pytree structure generally differs from that
of `params`.
::
update_fun(step, grads, opt_state)
Args:
step: integer representing the step index.
grads: a pytree with the same structure as `get_params(opt_state)`
representing the gradients to be used in updating the optimizer state.
opt_state: a pytree representing the optimizer state to be updated.
Returns:
A pytree with the same structure as the `opt_state` argument representing
the updated optimizer state.
::
get_params(opt_state)
Args:
opt_state: pytree representing an optimizer state.
Returns:
A pytree representing the parameters extracted from `opt_state`, such that
the invariant `params == get_params(init_fun(params))` holds true.
Notice that an optimizer implementation has a lot of flexibility in the form of
opt_state: it just has to be a pytree of JaxTypes (so that it can be passed to
the JAX transforms defined in api.py) and it has to be consumable by update_fun
and get_params.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from collections import namedtuple
import functools
import operator
from six.moves import reduce
import jax.numpy as np
from jax.util import partial, safe_zip, safe_map, unzip2
from jax import tree_util
from jax.tree_util import (tree_map, tree_flatten, tree_unflatten,
register_pytree_node)
map = safe_map
zip = safe_zip
# The implementation here basically works by flattening pytrees. There are two
# levels of pytrees to think about: the pytree of params, which we can think of
# as defining an "outer pytree", and a pytree produced by applying init_fun to
# each leaf of the params pytree, which we can think of as the "inner pytrees".
# Since pytrees can be flattened, that structure is isomorphic to a list of
# lists (with no further nesting).
pack = tuple
OptimizerState = namedtuple("OptimizerState",
["packed_state", "tree_def", "subtree_defs"])
register_pytree_node(
OptimizerState,
lambda xs: ((xs.packed_state,), (xs.tree_def, xs.subtree_defs)),
lambda data, xs: OptimizerState(xs[0], data[0], data[1]))
def optimizer(opt_maker):
"""Decorator to make an optimizer defined for arrays generalize to containers.
With this decorator, you can write init, update, and get_params functions that
each operate only on single arrays, and convert them to corresponding
functions that operate on pytrees of parameters. See the optimizers defined in
optimizers.py for examples.
Args:
opt_maker: a function that returns an ``(init_fun, update_fun, get_params)``
triple of functions that might only work with ndarrays, as per
.. code-block:: haskell
init_fun :: ndarray -> OptStatePytree ndarray
update_fun :: OptStatePytree ndarray -> OptStatePytree ndarray
get_params :: OptStatePytree ndarray -> ndarray
Returns:
An ``(init_fun, update_fun, get_params)`` triple of functions that work on
arbitrary pytrees, as per
.. code-block:: haskell
init_fun :: ParameterPytree ndarray -> OptimizerState
update_fun :: OptimizerState -> OptimizerState
get_params :: OptimizerState -> ParameterPytree ndarray
The OptimizerState pytree type used by the returned functions is isomorphic
to ``ParameterPytree (OptStatePytree ndarray)``, but may store the state
instead as e.g. a partially-flattened data structure for performance.
"""
@functools.wraps(opt_maker)
def tree_opt_maker(*args, **kwargs):
init, update, get_params = opt_maker(*args, **kwargs)
@functools.wraps(init)
def tree_init(x0_tree):
x0_flat, tree = tree_flatten(x0_tree)
initial_states = [init(x0) for x0 in x0_flat]
states_flat, subtrees = unzip2(map(tree_flatten, initial_states))
packed_state = pack(map(pack, states_flat))
return OptimizerState(packed_state, tree, subtrees)
@functools.wraps(update)
def tree_update(i, grad_tree, opt_state):
packed_state, tree, subtrees = opt_state
grad_flat, tree2 = tree_flatten(grad_tree)
if tree2 != tree:
msg = ("optimizer update function was passed a gradient tree that did "
"not match the parameter tree structure with which it was "
"initialized: parameter tree {} and grad tree {}.")
raise TypeError(msg.format(tree, tree2))
states = map(tree_unflatten, subtrees, packed_state)
new_states = map(partial(update, i), grad_flat, states)
new_states_flat, subtrees2 = unzip2(map(tree_flatten, new_states))
for subtree, subtree2 in zip(subtrees, subtrees2):
if subtree2 != subtree:
msg = ("optimizer update function produced an output structure that "
"did not match its input structure: input {} and output {}.")
raise TypeError(msg.format(subtree, subtree2))
new_packed_state = pack(map(pack, new_states_flat))
return OptimizerState(new_packed_state, tree, subtrees)
@functools.wraps(get_params)
def tree_get_params(opt_state):
packed_state, tree, subtrees = opt_state
states = map(tree_unflatten, subtrees, packed_state)
params = map(get_params, states)
return tree_unflatten(tree, params)
return tree_init, tree_update, tree_get_params
return tree_opt_maker
### optimizers
@optimizer
def sgd(step_size):
"""Construct optimizer triple for stochastic gradient descent.
Args:
step_size: positive scalar, or a callable representing a step size schedule
that maps the iteration index to positive scalar.
Returns:
An (init_fun, update_fun, get_params) triple.
"""
step_size = make_schedule(step_size)
def init(x0):
return x0
def update(i, g, x):
return x - step_size(i) * g
def get_params(x):
return x
return init, update, get_params
@optimizer
def momentum(step_size, mass):
"""Construct optimizer triple for SGD with momentum.
Args:
step_size: positive scalar, or a callable representing a step size schedule
that maps the iteration index to positive scalar.
mass: positive scalar representing the momentum coefficient.
Returns:
An (init_fun, update_fun, get_params) triple.
"""
step_size = make_schedule(step_size)
def init(x0):
v0 = np.zeros_like(x0)
return x0, v0
def update(i, g, state):
x, velocity = state
velocity = mass * velocity + g
x = x - step_size(i) * velocity
return x, velocity
def get_params(state):
x, _ = state
return x
return init, update, get_params
@optimizer
def nesterov(step_size, mass):
"""Construct optimizer triple for SGD with Nesterov momentum.
Args:
step_size: positive scalar, or a callable representing a step size schedule
that maps the iteration index to positive scalar.
mass: positive scalar representing the momentum coefficient.
Returns:
An (init_fun, update_fun, get_params) triple.
"""
step_size = make_schedule(step_size)
def init(x0):
v0 = np.zeros_like(x0)
return x0, v0
def update(i, g, state):
x, velocity = state
velocity = mass * velocity + g
x = x - step_size(i) * (mass * velocity + g)
return x, velocity
def get_params(state):
x, _ = state
return x
return init, update, get_params
@optimizer
def adagrad(step_size, momentum=0.9):
"""Construct optimizer triple for Adagrad.
Adaptive Subgradient Methods for Online Learning and Stochastic Optimization:
http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf
Args:
step_size: positive scalar, or a callable representing a step size schedule
that maps the iteration index to positive scalar.
momentum: optional, a positive scalar value for momentum
Returns:
An (init_fun, update_fun, get_params) triple.
"""
step_size = make_schedule(step_size)
def init(x0):
g_sq = np.zeros_like(x0)
m = np.zeros_like(x0)
return x0, g_sq, m
def update(i, g, state):
x, g_sq, m = state
g_sq += g**2
g_sq_inv_sqrt = np.where(g_sq > 0, 1. / np.sqrt(g_sq), 0.0)
m = (1. - momentum) * (g * g_sq_inv_sqrt) + momentum * m
x = x - step_size(i) * m
return x, g_sq, m
def get_params(state):
x, _, _ = state
return x
return init, update, get_params
@optimizer
def rmsprop(step_size, gamma=0.9, eps=1e-8):
"""Construct optimizer triple for RMSProp.
Args:
step_size: positive scalar, or a callable representing a step size schedule
that maps the iteration index to positive scalar.
gamma: Decay parameter.
eps: Epsilon parameter.
Returns:
An (init_fun, update_fun, get_params) triple.
"""
step_size = make_schedule(step_size)
def init(x0):
avg_sq_grad = np.zeros_like(x0)
return x0, avg_sq_grad
def update(i, g, state):
x, avg_sq_grad = state
avg_sq_grad = avg_sq_grad * gamma + g**2 * (1. - gamma)
x = x - step_size(i) * g / np.sqrt(avg_sq_grad + eps)
return x, avg_sq_grad
def get_params(state):
x, _ = state
return x
return init, update, get_params
@optimizer
def rmsprop_momentum(step_size, gamma=0.9, eps=1e-8, momentum=0.9):
"""Construct optimizer triple for RMSProp with momentum.
This optimizer is separate from the rmsprop optimizer because it needs to
keep track of additional parameters.
Args:
step_size: positive scalar, or a callable representing a step size schedule
that maps the iteration index to positive scalar.
gamma: Decay parameter.
eps: Epsilon parameter.
momentum: Momentum parameter.
Returns:
An (init_fun, update_fun, get_params) triple.
"""
step_size = make_schedule(step_size)
def init(x0):
avg_sq_grad = np.zeros_like(x0)
mom = np.zeros_like(x0)
return x0, avg_sq_grad, mom
def update(i, g, state):
x, avg_sq_grad, mom = state
avg_sq_grad = avg_sq_grad * gamma + g**2 * (1. - gamma)
mom = momentum * mom + step_size(i) * g / np.sqrt(avg_sq_grad + eps)
x = x - mom
return x, avg_sq_grad, mom
def get_params(state):
x, _, _ = state
return x
return init, update, get_params
@optimizer
def adam(step_size, b1=0.9, b2=0.999, eps=1e-8):
"""Construct optimizer triple for Adam.
Args:
step_size: positive scalar, or a callable representing a step size schedule
that maps the iteration index to positive scalar.
b1: optional, a positive scalar value for beta_1, the exponential decay rate
for the first moment estimates (default 0.9).
b2: optional, a positive scalar value for beta_2, the exponential decay rate
for the second moment estimates (default 0.999).
eps: optional, a positive scalar value for epsilon, a small constant for
numerical stability (default 1e-8).
Returns:
An (init_fun, update_fun, get_params) triple.
"""
step_size = make_schedule(step_size)
def init(x0):
m0 = np.zeros_like(x0)
v0 = np.zeros_like(x0)
return x0, m0, v0
def update(i, g, state):
x, m, v = state
m = (1 - b1) * g + b1 * m # First moment estimate.
v = (1 - b2) * (g ** 2) + b2 * v # Second moment estimate.
mhat = m / (1 - b1 ** (i + 1)) # Bias correction.
vhat = v / (1 - b2 ** (i + 1))
x = x - step_size(i) * mhat / (np.sqrt(vhat) + eps)
return x, m, v
def get_params(state):
x, m, v = state
return x
return init, update, get_params
@optimizer
def sm3(step_size, momentum=0.9):
"""Construct optimizer triple for SM3.
Memory-Efficient Adaptive Optimization for Large-Scale Learning.
https://arxiv.org/abs/1901.11150
Args:
step_size: positive scalar, or a callable representing a step size schedule
that maps the iteration index to positive scalar.
momentum: optional, a positive scalar value for momentum
Returns:
An (init_fun, update_fun, get_params) triple.
"""
step_size = make_schedule(step_size)
def splice(seq, i, x):
lst = list(seq)
lst[i:i+1] = x
return lst
def broadcast_into(ndim, x, axis):
idx = splice([None] * ndim, axis, [slice(None)])
return x[tuple(idx)]
def init(x0):
vs = [np.zeros(sz, dtype=x0.dtype) for sz in x0.shape]
return x0, np.zeros_like(x0), vs
def update(i, g, state):
x, m, vs = state
vs = [broadcast_into(g.ndim, v, i) for i, v in enumerate(vs)]
accum = reduce(np.minimum, vs) + g ** 2
accum_inv_sqrt = np.where(accum > 0, 1. / np.sqrt(accum), 0)
m = (1. - momentum) * (g * accum_inv_sqrt) + momentum * m
x = x - step_size(i) * m
vs = [accum.max(splice(range(x.ndim), j, [])) for j in range(x.ndim)]
return x, m, vs
def get_params(state):
x, _, _ = state
return x
return init, update, get_params
### learning rate schedules
def constant(step_size):
def schedule(i):
return step_size
return schedule
def exponential_decay(step_size, decay_steps, decay_rate):
def schedule(i):
return step_size * decay_rate ** (i / decay_steps)
return schedule
def inverse_time_decay(step_size, decay_steps, decay_rate, staircase=False):
if staircase:
def schedule(i):
return step_size / (1 + decay_rate * np.floor(i / decay_steps))
else:
def schedule(i):
return step_size / (1 + decay_rate * i / decay_steps)
return schedule
def polynomial_decay(step_size, decay_steps, final_step_size, power=1.0):
def schedule(step_num):
step_num = np.minimum(step_num, decay_steps)
step_mult = (1 - step_num / decay_steps) ** power
return step_mult * (step_size - final_step_size) + final_step_size
return schedule
def piecewise_constant(boundaries, values):
boundaries = np.array(boundaries)
values = np.array(values)
if not boundaries.ndim == values.ndim == 1:
raise ValueError("boundaries and values must be sequences")
if not boundaries.shape[0] == values.shape[0] - 1:
raise ValueError("boundaries length must be one longer than values length")
def schedule(i):
return values[np.sum(i > boundaries)]
return schedule
def make_schedule(scalar_or_schedule):
if callable(scalar_or_schedule):
return scalar_or_schedule
elif np.ndim(scalar_or_schedule) == 0:
return constant(scalar_or_schedule)
else:
raise TypeError(type(scalar_or_schedule))
### utilities
def l2_norm(tree):
"""Compute the l2 norm of a pytree of arrays. Useful for weight decay."""
leaves, _ = tree_flatten(tree)
return np.sqrt(sum(np.vdot(x, x) for x in leaves))
def clip_grads(grad_tree, max_norm):
"""Clip gradients stored as a pytree of arrays to maximum norm `max_norm`."""
norm = l2_norm(grad_tree)
normalize = lambda g: np.where(norm < max_norm, g, g * (max_norm / norm))
return tree_map(normalize, grad_tree)
### serialization utilities
class JoinPoint(object):
"""Marks the boundary between two joined (nested) pytrees."""
def __init__(self, subtree):
self.subtree = subtree
# Since pytrees are containers of numpy arrays, look iterable.
def __iter__(self):
yield self.subtree
def unpack_optimizer_state(opt_state):
"""Converts an OptimizerState to a marked pytree.
Converts an OptimizerState to a marked pytree with the leaves of the outer
pytree represented as JoinPoints to avoid losing information. This function is
intended to be useful when serializing optimizer states.
Args:
opt_state: An OptimizerState
Returns:
A pytree with JoinPoint leaves that contain a second level of pytrees.
"""
packed_state, tree_def, subtree_defs = opt_state
subtrees = map(tree_unflatten, subtree_defs, packed_state)
sentinels = [JoinPoint(subtree) for subtree in subtrees]
return tree_util.tree_unflatten(tree_def, sentinels)
def pack_optimizer_state(marked_pytree):
"""Converts a marked pytree to an OptimizerState.
The inverse of unpack_optimizer_state. Converts a marked pytree with the
leaves of the outer pytree represented as JoinPoints back into an
OptimizerState. This function is intended to be useful when deserializing
optimizer states.
Args:
marked_pytree: A pytree containing JoinPoint leaves that hold more pytrees.
Returns:
An equivalent OptimizerState to the input argument.
"""
sentinels, tree_def = tree_flatten(marked_pytree)
assert all(isinstance(s, JoinPoint) for s in sentinels)
subtrees = [s.subtree for s in sentinels]
states_flat, subtree_defs = unzip2(map(tree_flatten, subtrees))
packed_state = pack(map(pack, states_flat))
return OptimizerState(packed_state, tree_def, subtree_defs)
|
jax-master
|
jax/experimental/optimizers.py
|
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
"""Loops is an **experimental** module for syntactic sugar for loops and control-flow.
The current implementation should convert loops correctly to JAX internal
representation, and most transformations should work (see below), but we have
not yet fine-tuned the performance of the resulting XLA compilation!
By default, loops and control-flow in JAX are executed and inlined during tracing.
For example, in the following code the `for` loop is unrolled during JAX tracing::
arr = onp.zeros(5)
for i in range(arr.shape[0]):
arr[i] += 2.
if i % 2 == 0:
arr[i] += 1.
In order to capture the structured control-flow one has to use the higher-order
JAX operations, which require you to express the body of the loops and
conditionals as functions, and the array updates using a functional style that
returns an updated array, e.g.::
arr = onp.zeros(5)
def loop_body(i, acc_arr):
arr1 = ops.index_update(acc_arr, i, acc_arr[i] + 2.)
return lax.cond(i % 2 == 0,
arr1,
lambda arr1: ops.index_update(arr1, i, arr1[i] + 1),
arr1,
lambda arr1: arr1)
arr = lax.fori_loop(0, arr.shape[0], loop_body, arr)
The default notation quickly gets unreadable with deeper nested loops.
With the utilities in this module you can write loops and conditionals that
look closer to plain Python, as long as you keep the loop-carried state in a
special `loops.scope` object and use `for` loops over special
`scope.range` iterators::
from jax.experimental import loops
with loops.Scope() as s:
s.arr = np.zeros(5) # Create the mutable state of the loop as `scope` fields.
for i in s.range(s.arr.shape[0]):
s.arr = ops.index_update(s.arr, i, s.arr[i] + 2.)
for _ in s.cond_range(i % 2 == 0): # Conditionals as loops with 0 or 1 iterations
s.arr = ops.index_update(s.arr, i, s.arr[i] + 1.)
Loops constructed with `range` must have literal constant bounds. If you need
loops with dynamic bounds, you can use the more general `while_range` iterator.
However, in that case that `grad` transformation is not supported::
s.idx = start
for _ in s.while_range(lambda: s.idx < end):
s.idx += 1
Notes:
* Loops and conditionals to be functionalized can appear only inside scopes
constructed with `loops.Scope` and they must use one of the `Scope.range`
iterators. All other loops are unrolled during tracing, as usual in JAX.
* Only scope data (stored in fields of the scope object) is functionalized.
All other state, e.g., in other Python variables, will not be considered as
being part of the loop output. All references to the mutable state should be
through the scope: `s.arr`.
* Conceptually, this model is still "functional" in the sense that a loop over
a `Scope.range` behaves as a function whose input and output is the scope data.
* Scopes should be passed down to callees that need to use loop
functionalization, or they may be nested.
* The programming model is that the loop body over a `scope.range` is traced
only once, using abstract shape values, similar to how JAX traces function
bodies.
Restrictions:
* The tracing of the loop body should not exit prematurely with `return`,
`exception`, `break`. This would be detected and reported as errors when we
encounter unnested scopes.
* The loop index variable should not be used after the loop. Similarly, one
should not use outside the loop data computed in the loop body, except data
stored in fields of the scope object.
* No new mutable state can be created inside a loop to be functionalized.
All mutable state must be created outside all loops and conditionals.
* For a `while` loop, the conditional function is not allowed to modify the
scope state. This is a checked error. Also, for `while` loops the `grad`
transformation does not work. An alternative that allows `grad` is a bounded
loop (`range`).
Transformations:
* All transformations are supported, except `grad` is not supported for
`Scope.while_range` loops.
* `vmap` is very useful for such loops because it pushes more work into the
inner-loops, which should help performance for accelerators.
For usage example, see tests/loops_test.py.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
from functools import partial
import itertools
import numpy as onp
import six
import traceback
from jax import abstract_arrays
from jax import lax, core
from jax.lax import lax_control_flow
from jax import tree_util
from jax import numpy as jnp
from jax.interpreters import partial_eval as pe
from jax.util import unzip2, safe_map
class Scope(object):
"""A scope context manager to keep the state of loop bodies for functionalization.
Usage::
with Scope() as s:
s.data = 0.
for i in s.range(5):
s.data += 1.
return s.data
"""
def __init__(self):
self._mutable_state = {} # state to be functionalized, indexed by name.
self._active_ranges = [] # stack of active ranges, last one is the innermost.
def range(self, first, second=None, third=None):
"""Creates an iterator for bounded iterations to be functionalized.
The body is converted to a `lax.scan`, for which all JAX transformations work.
The `first`, `second`, and `third` arguments must be integer literals.
Usage::
range(5) # start=0, end=5, step=1
range(1, 5) # start=1, end=5, step=1
range(1, 5, 2) # start=1, end=5, step=2
s.out = 1.
for i in scope.range(5):
s.out += 1.
"""
if third is not None:
start = int(first)
stop = int(second)
step = int(third)
else:
step = 1
if second is not None:
start = int(first)
stop = int(second)
else:
start = 0
stop = int(first)
return _BodyTracer(self, _BoundedLoopBuilder(start, stop, step))
def cond_range(self, pred):
"""Creates a conditional iterator with 0 or 1 iterations based on the boolean.
The body is converted to a `lax.cond`. All JAX transformations work.
Usage::
for _ in scope.cond_range(s.field < 0.):
s.field = - s.field
"""
# TODO: share these checks with lax_control_flow.cond
if len(onp.shape(pred)) != 0:
raise TypeError(
"Pred must be a scalar, got {} of shape {}.".format(pred, onp.shape(pred)))
try:
pred_dtype = onp.result_type(pred)
except TypeError:
msg = ("Pred type must be either boolean or number, got {}.")
raise TypeError(msg.format(pred))
if pred_dtype.kind != 'b':
if pred_dtype.kind in 'iuf':
pred = pred != 0
else:
msg = ("Pred type must be either boolean or number, got {}.")
raise TypeError(msg.format(pred_dtype))
return _BodyTracer(self, _CondBuilder(pred))
def while_range(self, cond_func):
"""Creates an iterator that continues as long as `cond_func` returns true.
The body is converted to a `lax.while_loop`.
The `grad` transformation does not work.
Usage::
for _ in scope.while_range(lambda: s.loss > 1.e-5):
s.loss = loss(...)
Args:
cond_func: a lambda with no arguments, the condition for the "while".
"""
return _BodyTracer(self, _WhileBuilder(cond_func))
def _push_range(self, range_):
for ar in self._active_ranges:
if ar is range_:
raise ValueError("Range is reused nested inside itself.")
self._active_ranges.append(range_)
def _pop_range(self, range_):
if not (range_ is self._active_ranges[-1]):
self._error_premature_exit_range()
self._active_ranges.pop()
def _error_premature_exit_range(self):
"""Raises error about premature exit from a range"""
msg = "Some ranges have exited prematurely. The innermost such range is at\n{}"
raise ValueError(msg.format(self._active_ranges[-1].location()))
def __getattr__(self, key):
"""Accessor for scope data.
Called only if the attribute is not found, which will happen when we read
scope data that has been stored in self._mutable_state.
"""
mt_val = self._mutable_state.get(key)
if mt_val is None:
raise AttributeError(
"Reading uninitialized data '{}' from the scope.".format(key))
return mt_val
def __setattr__(self, key, value):
"""Update scope data to be functionalized.
Called for *all* attribute setting.
"""
if key in ["_active_ranges", "_mutable_state"]:
object.__setattr__(self, key, value)
else:
if self._active_ranges and key not in self._mutable_state:
raise ValueError(
"New mutable state '{}' cannot be created inside a loop.".format(key))
self._mutable_state[key] = value
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
if self._active_ranges: # We have some ranges that we did not exit properly
self._error_premature_exit_range()
return True
else:
# The exception may come from inside one or more ranges. We let the current
# exception propagate, assuming it terminates the tracing. If not, the
# tracers may be left in an inconsistent state.
return False # re-raise
class _BodyTracer(object):
"""Traces the body of the loop and builds a functional control-flow representation.
This class is also an iterator, only the first iteration is traced.
"""
def __init__(self, scope, loop_builder):
"""
Params:
scope: the current scope
loop_builder: instance of _LoopBuilder
"""
self.scope = scope
self.loop_builder = loop_builder
self.first_iteration = True # If we are tracing the first iteration
if six.PY3:
# Stack trace, without this line and the s.range function
self.stack = traceback.StackSummary.from_list(traceback.extract_stack()[:-2])
else:
self.stack = None
# Next are state kept from the start of the first iteration to the end of the iteration.
self.carried_state_initial = {}
# The parameters that were created for state upon entering an arbitrary iteration.
self.carried_state_vars = {}
self.trace = None
# List of scope fields carried through the loop
self.carried_state_names = None
self.init_tree = None # The PyTreeDef corresponding to carried_state_names
self.init_vals = None # The values corresponding to self.init_tree
def location(self):
"""A multiline string representing the source location of the range."""
if self.stack is not None:
return " ".join(self.stack.format())
else:
return ""
def __iter__(self):
"""Called before starting the first iteration."""
self.first_iteration = True # In case we reuse the range
return self
def __next__(self):
if self.first_iteration:
self.first_iteration = False
self.scope._push_range(self)
self.start_tracing_body()
return self._index_var
else:
self.end_tracing_body()
self.scope._pop_range(self)
raise StopIteration # Trace only one iteration.
def next(self): # For PY2
return self.__next__()
def start_tracing_body(self):
"""Called upon starting the tracing of the loop body."""
# Make a copy of the current value of the mutable state
self.carried_state_initial = copy.copy(self.scope._mutable_state)
# The entire state is carried.
self.carried_state_names = sorted(self.scope._mutable_state.keys())
# TODO: This is the first part of partial_eval.trace_to_subjaxpr. Share.
self.trace = _BodyTracer.start_subtrace()
# Set the scope._mutable_state to new tracing variables.
for key, initial in self.carried_state_initial.items():
mt_aval = _BodyTracer.abstractify(initial)
mt_pval = pe.PartialVal((mt_aval, core.unit))
mt_var = self.trace.new_arg(mt_pval)
self.carried_state_vars[key] = mt_var
self.scope._mutable_state[key] = mt_var
index_var_aval = _BodyTracer.abstractify(0)
index_var_pval = pe.PartialVal((index_var_aval, core.unit))
self._index_var = self.trace.new_arg(index_var_pval)
def end_tracing_body(self):
"""Called when we are done tracing one iteration of the body."""
# We will turn the body of the loop into a function that takes some values
# for the scope state (carried_state_names) and returns the values for the
# same state fields after one execution of the body. For some of the ranges,
# e.g., scope.range, the function will also take the index_var as last parameter.
in_tracers = [self.carried_state_vars[ms] for ms in self.carried_state_names]
if self.loop_builder.can_use_index_var():
in_tracers += [self._index_var]
# Make the jaxpr for the body of the loop
# TODO: See which mutable state was changed in the one iteration.
# For now, we assume all state changes.
body_out_tracers = tuple([self.scope._mutable_state[ms]
for ms in self.carried_state_names])
try:
# If the body actually uses the index variable, and is not allowed to
# (e.g., cond_range and while_range), then in_tracers will not contain
# the tracer for the index_var, and trace_to_jaxpr_finalize will throw
# an assertion error.
body_typed_jaxpr, body_const_vals = _BodyTracer.trace_to_jaxpr_finalize(
in_tracers=in_tracers,
out_tracers=body_out_tracers,
trace=self.trace)
except AssertionError as e:
if "Encountered unexpected tracer" == str(e):
raise ValueError("Body of cond_range or while_range should not use the "
"index variable returned by iterator.")
raise
# End the subtrace for the loop body, before we trace the condition
_BodyTracer.end_subtrace()
carried_init_val = tuple([self.carried_state_initial[ms]
for ms in self.carried_state_names])
carried_init_vals, carried_tree = tree_util.tree_flatten(carried_init_val)
carried_out_vals = self.loop_builder.build_output_vals(
self.scope, self.carried_state_names, carried_tree,
carried_init_vals, body_typed_jaxpr, body_const_vals)
carried_mutable_state_unflattened = tree_util.tree_unflatten(carried_tree,
carried_out_vals)
# Update the mutable state with the values of the changed vars, after the loop.
for ms, mv in zip(self.carried_state_names, carried_mutable_state_unflattened):
self.scope._mutable_state[ms] = mv
@staticmethod
def start_subtrace():
"""Starts a nested trace, returns the Trace object."""
# TODO: This follows the __enter__ part of core.new_master. share
level = core.trace_state.trace_stack.next_level(False)
master = core.MasterTrace(level, pe.JaxprTrace)
core.trace_state.trace_stack.push(master, False)
return pe.JaxprTrace(master, core.cur_sublevel())
@staticmethod
def end_subtrace():
# TODO: This follows the __exit__ part of core.new_master
core.trace_state.trace_stack.pop(False)
@staticmethod
def abstractify(x):
return abstract_arrays.raise_to_shaped(core.get_aval(x))
@staticmethod
def trace_to_jaxpr_finalize(in_tracers, out_tracers, trace, instantiate=True):
# TODO: This is the final part of the partial_eval.trace_to_subjaxpr. Share.
instantiate = [instantiate] * len(out_tracers)
out_tracers = safe_map(trace.full_raise, safe_map(core.full_lower, out_tracers))
out_tracers = safe_map(partial(pe.instantiate_const_at, trace),
instantiate, out_tracers)
jaxpr, consts, env = pe.tracers_to_jaxpr(in_tracers, out_tracers)
out_pvals = [t.pval for t in out_tracers]
# TODO: this is from partial_eval.trace_to_jaxpr. Share.
assert not env
# TODO: this is from the final part of lax_control_flow._initial_style_jaxpr
out_avals = safe_map(abstract_arrays.raise_to_shaped, unzip2(out_pvals)[0])
const_avals = tuple(abstract_arrays.raise_to_shaped(core.get_aval(c))
for c in consts)
in_pvals = [t.pval for t in in_tracers]
in_avals = tuple(safe_map(abstract_arrays.raise_to_shaped, unzip2(in_pvals)[0]))
typed_jaxpr = core.TypedJaxpr(pe.closure_convert_jaxpr(jaxpr),
(), const_avals + in_avals, out_avals)
return typed_jaxpr, consts
class _LoopBuilder(object):
"""Abstract superclass for the loop builders"""
def can_use_index_var(self):
"""Whether this kind of loop can use the index var returned by the range iterator."""
raise NotImplementedError
def build_output_vals(self, scope, carried_state_names, carried_tree,
init_vals, body_typed_jaxpr, body_const_vals):
"""Builds the output values for the loop carried state.
Params:
scope: the current Scope object.
carried_state_names: the list of names of mutable state fields that is
carried through the body.
carried_tree: the PyTreeDef for the tuple of carried_state_names.
init_vals: the initial values on body entry corresponding to the init_tree.
body_typed_jaxpr: the Jaxpr for the body returning the new values of
carried_state_names.
body_const_vals: the constant values for the body.
Returns:
the output tracer corresponding to the lax primitive representing the loop.
"""
raise NotImplementedError
def __str__(self):
raise NotImplementedError
class _BoundedLoopBuilder(_LoopBuilder):
"""Builds a lax operation corresponding to a bounded range iteration."""
def __init__(self, start, stop, step):
self.start = start
self.stop = stop
self.step = step
self._index_var = None # The parameter for the index variable
def can_use_index_var(self):
return True
def build_output_vals(self, scope, carried_state_names, carried_tree,
init_vals, body_typed_jaxpr, body_const_vals):
arange_val = jnp.arange(self.start, stop=self.stop, step=self.step)
return lax_control_flow.scan_p.bind(*itertools.chain(body_const_vals,
init_vals, [arange_val]),
forward=True, length=arange_val.shape[0],
jaxpr=body_typed_jaxpr,
num_consts=len(body_const_vals),
num_carry=len(init_vals),
linear=(False,) * (len(body_const_vals) +
len(init_vals) + 1))
class _CondBuilder(_LoopBuilder):
"""Builds a lax.cond operation."""
def __init__(self, pred):
self.pred = pred
def can_use_index_var(self):
return False
def build_output_vals(self, scope, carried_state_names, carried_tree,
init_vals, body_typed_jaxpr, body_const_vals):
# Simulate a pass-through false branch
init_avals = safe_map(_BodyTracer.abstractify, init_vals)
false_body_typed_jaxpr, false_body_const_vals, _ = (
lax_control_flow._initial_style_jaxpr(lambda *args: args,
carried_tree,
tuple(init_avals)))
return lax_control_flow.cond_p.bind(
*itertools.chain([self.pred], body_const_vals,
init_vals, false_body_const_vals, init_vals),
true_jaxpr=body_typed_jaxpr, false_jaxpr=false_body_typed_jaxpr,
true_nconsts=len(body_const_vals), false_nconsts=len(false_body_const_vals))
class _WhileBuilder(_LoopBuilder):
"""Builds a lax.while operation."""
def __init__(self, cond_func):
self.cond_func = cond_func # Function with 0 arguments (can reference the scope)
def can_use_index_var(self):
return False
def build_output_vals(self, scope, carried_state_names, carried_tree,
init_vals, body_typed_jaxpr, body_const_vals):
# Trace the conditional function. cond_func takes 0 arguments, but
# for lax.while we need a conditional function that takes the
# carried_state_names. _initial_style_jaxpr will start its own trace and
# will create tracers for all the carried state. We must put these values
# in the scope._mutable_state before we trace the conditional
# function.
def cond_func_wrapped(*args):
assert len(args) == len(carried_state_names)
for ms, init_ms in zip(carried_state_names, args):
scope._mutable_state[ms] = init_ms
res = self.cond_func()
# Conditional function is not allowed to modify the scope state
for ms, init_ms in zip(carried_state_names, args):
if not (scope._mutable_state[ms] is init_ms):
msg = "Conditional function modifies scope.{} field."
raise ValueError(msg.format(ms))
return res
init_avals = safe_map(_BodyTracer.abstractify, init_vals)
cond_jaxpr, cond_consts, cond_tree = (
lax_control_flow._initial_style_jaxpr(cond_func_wrapped,
carried_tree,
tuple(init_avals)))
# TODO: share these checks with lax_control_flow.while
if not tree_util.treedef_is_leaf(cond_tree):
msg = "cond_fun must return a boolean scalar, but got pytree {}."
raise TypeError(msg.format(cond_tree))
if cond_jaxpr.out_avals != [abstract_arrays.ShapedArray((), onp.bool_)]:
msg = "cond_fun must return a boolean scalar, but got output type(s) {}."
raise TypeError(msg.format(cond_jaxpr.out_avals))
return lax_control_flow.while_p.bind(*itertools.chain(cond_consts,
body_const_vals,
init_vals),
cond_nconsts=len(cond_consts),
cond_jaxpr=cond_jaxpr,
body_nconsts=len(body_const_vals),
body_jaxpr=body_typed_jaxpr)
|
jax-master
|
jax/experimental/loops.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
"""Extending JAX's vmap to work like NumPy's gufuncs.
By `Stephan Hoyer <https://github.com/shoyer>`_
What is a gufunc?
=================
`Generalized universal functions
<https://docs.scipy.org/doc/numpy-1.15.0/reference/c-api.generalized-ufuncs.html>`_
("gufuncs") are one of my favorite abstractions from NumPy. They generalize
NumPy's `broadcasting rules
<https://docs.scipy.org/doc/numpy-1.15.0/user/basics.broadcasting.html>`_ to
handle non-scalar operations. When a gufuncs is applied to arrays, there are:
* "core dimensions" over which an operation is defined.
* "broadcast dimensions" over which operations can be automatically vectorized.
A string `signature <https://docs.scipy.org/doc/numpy-1.15.0/reference/c-api.generalized-ufuncs.html#details-of-signature>`_
associated with each gufunc controls how this happens by indicating how core
dimensions are mapped between inputs and outputs. The syntax is easiest to
understand by looking at a few examples:
* Addition: `(),()->()`
* 1D inner product: `(i),(i)->()`
* 1D sum: `(i)->()`
* Matrix multiplcation: `(m,n),(n,k)->(m,k)`
Why write gufuncs?
=====================
From a user perspective, gufuncs are nice because they're guaranteed to
vectorize in a consistent and general fashion. For example, by default gufuncs
use the last dimensions of arrays as core dimensions, but you can control that
explicitly with the ``axis`` or ``axes`` arguments.
From a developer perspective, gufuncs are nice because they simplify your work:
you only need to think about the core logic of your function, not how it
handles arbitrary dimensional input. You can just write that down in a simple,
declarative way.
JAX makes it easy to write high-level performant code
=====================================================
Unfortunately, writing NumPy gufuncs today is somewhat non-trivial. Your
options today are:
1. Write the inner loops yourself in C.
2. `np.vectorize <https://docs.scipy.org/doc/numpy/reference/generated/numpy.vectorize.html>`_ creates something kind of like a gufunc, but it's painfully slow: the outer loop is performed in Python.
3. `numba.guvectorize <https://numba.pydata.org/numba-doc/dev/user/vectorize.html>`_ can work well, if you don't need further code transformations like automatic differentiation.
JAX's ``vmap`` contains all the core functionality we need to write functions that work like gufuncs. JAX gufuncs play nicely with other transformations like ``grad`` and ``jit``.
A simple example
================
Consider a simple example from data preprocessing, centering an array.
Here's how we might write a vectorized version using NumPy::
def center(array, axis=-1):
# array can have any number of dimensions
bias = np.mean(array, axis=axis)
debiased = array - np.expand_dims(bias, axis)
return bias, debiased
And here's how we could write a vectorized version using JAX gufuncs::
@vectorize('(n)->(),(n)')
def center(array):
# array is always a 1D vector
bias = np.mean(array)
debiased = array - bias
return bias, debiased
See the difference?
* Instead of needing to think about broadcasting while writing the entire function, we can write the function assuming the input is always a vector.
* We get the ``axis`` argument automatically, without needing to write it ourselves.
* As a bonus, the decorator makes the function self-documenting: a reader immediately knows that it handles higher dimensional input and output correctly.
"""
from jax import grad, jit, vmap
import jax.numpy as jnp
import numpy as np
import re
# See http://docs.scipy.org/doc/numpy/reference/c-api.generalized-ufuncs.html
_DIMENSION_NAME = r'\w+'
_CORE_DIMENSION_LIST = '(?:{0:}(?:,{0:})*)?'.format(_DIMENSION_NAME)
_ARGUMENT = r'\({}\)'.format(_CORE_DIMENSION_LIST)
_ARGUMENT_LIST = '{0:}(?:,{0:})*'.format(_ARGUMENT)
_SIGNATURE = '^{0:}->{0:}$'.format(_ARGUMENT_LIST)
def _parse_gufunc_signature(signature):
"""Parse string signatures for a generalized universal function.
Args:
signature : string
Generalized universal function signature, e.g., ``(m,n),(n,p)->(m,p)``
for ``np.matmul``.
Returns:
Tuple of input and output core dimensions parsed from the signature, each
of the form List[Tuple[str, ...]].
"""
if not re.match(_SIGNATURE, signature):
raise ValueError(
'not a valid gufunc signature: {}'.format(signature))
return tuple([tuple(re.findall(_DIMENSION_NAME, arg))
for arg in re.findall(_ARGUMENT, arg_list)]
for arg_list in signature.split('->'))
def _update_dim_sizes(dim_sizes, arg, core_dims):
"""Incrementally check and update core dimension sizes for a single argument.
Args:
dim_sizes : Dict[str, int]
Sizes of existing core dimensions. Will be updated in-place.
arg : ndarray
Argument to examine.
core_dims : Tuple[str, ...]
Core dimensions for this argument.
"""
if not core_dims:
return
num_core_dims = len(core_dims)
if arg.ndim < num_core_dims:
raise ValueError(
'%d-dimensional argument does not have enough '
'dimensions for all core dimensions %r'
% (arg.ndim, core_dims))
core_shape = arg.shape[-num_core_dims:]
for dim, size in zip(core_dims, core_shape):
if dim in dim_sizes:
if size != dim_sizes[dim]:
raise ValueError(
'inconsistent size for core dimension %r: %r vs %r'
% (dim, size, dim_sizes[dim]))
else:
dim_sizes[dim] = size
def _parse_input_dimensions(args, input_core_dims):
"""Parse broadcast and core dimensions for vectorize with a signature.
Args:
args : Tuple[ndarray, ...]
Tuple of input arguments to examine.
input_core_dims : List[Tuple[str, ...]]
List of core dimensions corresponding to each input.
Returns:
broadcast_shape : Tuple[int, ...]
Common shape to broadcast all non-core dimensions to.
dim_sizes : Dict[str, int]
Common sizes for named core dimensions.
"""
broadcast_args = []
dim_sizes = {}
for arg, core_dims in zip(args, input_core_dims):
_update_dim_sizes(dim_sizes, arg, core_dims)
ndim = arg.ndim - len(core_dims)
dummy_array = np.lib.stride_tricks.as_strided(0, arg.shape[:ndim])
broadcast_args.append(dummy_array)
broadcast_shape = np.lib.stride_tricks._broadcast_shape(*broadcast_args)
return broadcast_shape, dim_sizes
def _calculate_shapes(broadcast_shape, dim_sizes, list_of_core_dims):
"""Helper for calculating broadcast shapes with core dimensions."""
return [broadcast_shape + tuple(dim_sizes[dim] for dim in core_dims)
for core_dims in list_of_core_dims]
# adapted from np.vectorize (again authored by shoyer@)
def broadcast_with_core_dims(args, input_core_dims, output_core_dims):
if len(args) != len(input_core_dims):
raise TypeError('wrong number of positional arguments: '
'expected %r, got %r'
% (len(input_core_dims), len(args)))
broadcast_shape, dim_sizes = _parse_input_dimensions(
args, input_core_dims)
input_shapes = _calculate_shapes(broadcast_shape, dim_sizes,
input_core_dims)
args = [jnp.broadcast_to(arg, shape)
for arg, shape in zip(args, input_shapes)]
return args
def verify_axis_is_supported(input_core_dims, output_core_dims):
all_core_dims = set()
for input_or_output_core_dims in [input_core_dims, output_core_dims]:
for core_dims in input_or_output_core_dims:
all_core_dims.update(core_dims)
if len(core_dims) > 1:
raise ValueError('only one gufuncs with one core dim support axis')
def reorder_inputs(args, axis, input_core_dims):
return tuple(jnp.moveaxis(arg, axis, -1) if core_dims else arg
for arg, core_dims in zip(args, input_core_dims))
def reorder_outputs(result, axis, output_core_dims):
if not isinstance(result, tuple):
result = (result,)
result = tuple(jnp.moveaxis(res, -1, axis) if core_dims else res
for res, core_dims in zip(result, output_core_dims))
if len(result) == 1:
(result,) = result
return result
import functools
def vectorize(signature):
"""Vectorize a function using JAX.
Turns an arbitrary function into a numpy style "gufunc". Once
you specify the behavior of the core axis, the rest will be
broadcast naturally.
Args:
signature: an einsum style signature that defines how the core dimensions are mapped between inputs and outputs.
Returns:
The vectorized 'gufunc' that will automatically broadcast
while maintaining the specified core logic, the returned
function also has a new ``axis`` parameter for specifying
which axis should be treated as the core one.
"""
input_core_dims, output_core_dims = _parse_gufunc_signature(signature)
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
axis = kwargs.get('axis') # for python2 compat.
if axis is not None:
verify_axis_is_supported(input_core_dims, output_core_dims)
args = reorder_inputs(args, axis, input_core_dims)
broadcast_args = broadcast_with_core_dims(
args, input_core_dims, output_core_dims)
num_batch_dims = len(broadcast_args[0].shape) - len(input_core_dims[0])
vectorized_func = func
for _ in range(num_batch_dims):
vectorized_func = vmap(vectorized_func)
result = vectorized_func(*broadcast_args)
if axis is not None:
result = reorder_outputs(result, axis, output_core_dims)
return result
return wrapper
return decorator
|
jax-master
|
jax/experimental/vectorize.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
"""JAX-based Dormand-Prince ODE integration with adaptive stepsize.
Integrate systems of ordinary differential equations (ODEs) using the JAX
autograd/diff library and the Dormand-Prince method for adaptive integration
stepsize calculation. Provides improved integration accuracy over fixed
stepsize integration methods.
Adjoint algorithm based on Appendix C of https://arxiv.org/pdf/1806.07366.pdf
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
import time
import jax
from jax.flatten_util import ravel_pytree
import jax.lax
import jax.numpy as np
import jax.ops
from jax.test_util import check_vjp
import numpy as onp
import scipy.integrate as osp_integrate
@jax.jit
def interp_fit_dopri(y0, y1, k, dt):
# Fit a polynomial to the results of a Runge-Kutta step.
dps_c_mid = np.array([
6025192743 / 30085553152 / 2, 0, 51252292925 / 65400821598 / 2,
-2691868925 / 45128329728 / 2, 187940372067 / 1594534317056 / 2,
-1776094331 / 19743644256 / 2, 11237099 / 235043384 / 2])
y_mid = y0 + dt * np.dot(dps_c_mid, k)
return np.array(fit_4th_order_polynomial(y0, y1, y_mid, k[0], k[-1], dt))
@jax.jit
def fit_4th_order_polynomial(y0, y1, y_mid, dy0, dy1, dt):
"""Fit fourth order polynomial over function interval.
Args:
y0: function value at the start of the interval.
y1: function value at the end of the interval.
y_mid: function value at the mid-point of the interval.
dy0: derivative value at the start of the interval.
dy1: derivative value at the end of the interval.
dt: width of the interval.
Returns:
Coefficients `[a, b, c, d, e]` for the polynomial
p = a * x ** 4 + b * x ** 3 + c * x ** 2 + d * x + e
"""
v = np.stack([dy0, dy1, y0, y1, y_mid])
a = np.dot(np.hstack([-2. * dt, 2. * dt, np.array([-8., -8., 16.])]), v)
b = np.dot(np.hstack([5. * dt, -3. * dt, np.array([18., 14., -32.])]), v)
c = np.dot(np.hstack([-4. * dt, dt, np.array([-11., -5., 16.])]), v)
d = dt * dy0
e = y0
return a, b, c, d, e
@functools.partial(jax.jit, static_argnums=(0,))
def initial_step_size(fun, t0, y0, order, rtol, atol, f0):
"""Empirically choose initial step size.
Args:
fun: Function to evaluate like `func(y, t)` to compute the time
derivative of `y`.
t0: initial time.
y0: initial value for the state.
order: order of interpolation
rtol: relative local error tolerance for solver.
atol: absolute local error tolerance for solver.
f0: initial value for the derivative, computed from `func(t0, y0)`.
Returns:
Initial step size for odeint algorithm.
Algorithm from:
E. Hairer, S. P. Norsett G. Wanner,
Solving Ordinary Differential Equations I: Nonstiff Problems, Sec. II.4.
"""
scale = atol + np.abs(y0) * rtol
d0 = np.linalg.norm(y0 / scale)
d1 = np.linalg.norm(f0 / scale)
order_pow = (1. / (order + 1.))
h0 = np.where(np.any(np.asarray([d0 < 1e-5, d1 < 1e-5])),
1e-6,
0.01 * d0 / d1)
y1 = y0 + h0 * f0
f1 = fun(y1, t0 + h0)
d2 = np.linalg.norm((f1 - f0) / scale) / h0
h1 = np.where(np.all(np.asarray([d1 <= 1e-15, d2 <= 1e-15])),
np.maximum(1e-6, h0 * 1e-3),
(0.01 / np.max(d1 + d2))**order_pow)
return np.minimum(100. * h0, h1)
@functools.partial(jax.jit, static_argnums=(0,))
def runge_kutta_step(func, y0, f0, t0, dt):
"""Take an arbitrary Runge-Kutta step and estimate error.
Args:
func: Function to evaluate like `func(y, t)` to compute the time
derivative of `y`.
y0: initial value for the state.
f0: initial value for the derivative, computed from `func(t0, y0)`.
t0: initial time.
dt: time step.
alpha, beta, c: Butcher tableau describing how to take the Runge-Kutta
step.
Returns:
y1: estimated function at t1 = t0 + dt
f1: derivative of the state at t1
y1_error: estimated error at t1
k: list of Runge-Kutta coefficients `k` used for calculating these terms.
"""
# Dopri5 Butcher tableaux
alpha = np.array([1 / 5, 3 / 10, 4 / 5, 8 / 9, 1., 1., 0])
beta = np.array(
[[1 / 5, 0, 0, 0, 0, 0, 0],
[3 / 40, 9 / 40, 0, 0, 0, 0, 0],
[44 / 45, -56 / 15, 32 / 9, 0, 0, 0, 0],
[19372 / 6561, -25360 / 2187, 64448 / 6561, -212 / 729, 0, 0, 0],
[9017 / 3168, -355 / 33, 46732 / 5247, 49 / 176, -5103 / 18656, 0, 0],
[35 / 384, 0, 500 / 1113, 125 / 192, -2187 / 6784, 11 / 84, 0]])
c_sol = np.array([35 / 384, 0, 500 / 1113, 125 / 192, -2187 / 6784, 11 / 84,
0])
c_error = np.array([35 / 384 - 1951 / 21600, 0, 500 / 1113 - 22642 / 50085,
125 / 192 - 451 / 720, -2187 / 6784 - -12231 / 42400,
11 / 84 - 649 / 6300, -1. / 60.])
def _fori_body_fun(i, val):
ti = t0 + dt * alpha[i-1]
yi = y0 + dt * np.dot(beta[i-1, :], val)
ft = func(yi, ti)
return jax.ops.index_update(val, jax.ops.index[i, :], ft)
k = jax.lax.fori_loop(
1,
7,
_fori_body_fun,
jax.ops.index_update(np.zeros((7, f0.shape[0])), jax.ops.index[0, :], f0))
y1 = dt * np.dot(c_sol, k) + y0
y1_error = dt * np.dot(c_error, k)
f1 = k[-1]
return y1, f1, y1_error, k
@jax.jit
def error_ratio(error_estimate, rtol, atol, y0, y1):
err_tol = atol + rtol * np.maximum(np.abs(y0), np.abs(y1))
err_ratio = error_estimate / err_tol
return np.mean(err_ratio**2)
@jax.jit
def optimal_step_size(last_step,
mean_error_ratio,
safety=0.9,
ifactor=10.0,
dfactor=0.2,
order=5.0):
"""Compute optimal Runge-Kutta stepsize."""
mean_error_ratio = np.max(mean_error_ratio)
dfactor = np.where(mean_error_ratio < 1,
1.0,
dfactor)
err_ratio = np.sqrt(mean_error_ratio)
factor = np.maximum(1.0 / ifactor,
np.minimum(err_ratio**(1.0 / order) / safety,
1.0 / dfactor))
return np.where(mean_error_ratio == 0,
last_step * ifactor,
last_step / factor,)
@functools.partial(jax.jit, static_argnums=(0,))
def odeint(ofunc, y0, t, *args, **kwargs):
"""Adaptive stepsize (Dormand-Prince) Runge-Kutta odeint implementation.
Args:
ofunc: Function to evaluate `yt = ofunc(y, t, *args)` that
returns the time derivative of `y`.
y0: initial value for the state.
t: Timespan for `ofunc` evaluation like `np.linspace(0., 10., 101)`.
*args: Additional arguments to `ofunc` beyond y0 and t.
**kwargs: Two relevant keyword arguments:
'rtol': Relative local error tolerance for solver.
'atol': Absolute local error tolerance for solver.
'mxstep': Maximum number of steps to take for each timepoint.
Returns:
Integrated system values at each timepoint.
"""
rtol = kwargs.get('rtol', 1.4e-8)
atol = kwargs.get('atol', 1.4e-8)
mxstep = kwargs.get('mxstep', np.inf)
@functools.partial(jax.jit, static_argnums=(0,))
def _fori_body_fun(func, i, val):
"""Internal fori_loop body to interpolate an integral at each timestep."""
t, cur_y, cur_f, cur_t, dt, last_t, interp_coeff, solution = val
cur_y, cur_f, cur_t, dt, last_t, interp_coeff, _ = jax.lax.while_loop(
lambda x: (x[2] < t[i]) & (x[-1] < mxstep),
functools.partial(_while_body_fun, func),
(cur_y, cur_f, cur_t, dt, last_t, interp_coeff, 0.))
relative_output_time = (t[i] - last_t) / (cur_t - last_t)
out_x = np.polyval(interp_coeff, relative_output_time)
return (t, cur_y, cur_f, cur_t, dt, last_t, interp_coeff,
jax.ops.index_update(solution,
jax.ops.index[i, :],
out_x))
@functools.partial(jax.jit, static_argnums=(0,))
def _while_body_fun(func, x):
"""Internal while_loop body to determine interpolation coefficients."""
cur_y, cur_f, cur_t, dt, last_t, interp_coeff, j = x
next_t = cur_t + dt
next_y, next_f, next_y_error, k = runge_kutta_step(
func, cur_y, cur_f, cur_t, dt)
error_ratios = error_ratio(next_y_error, rtol, atol, cur_y, next_y)
new_interp_coeff = interp_fit_dopri(cur_y, next_y, k, dt)
dt = optimal_step_size(dt, error_ratios)
next_j = j + 1
new_rav, unravel = ravel_pytree(
(next_y, next_f, next_t, dt, cur_t, new_interp_coeff, next_j))
old_rav, _ = ravel_pytree(
(cur_y, cur_f, cur_t, dt, last_t, interp_coeff, next_j))
return unravel(np.where(np.all(error_ratios <= 1.),
new_rav,
old_rav))
func = lambda y, t: ofunc(y, t, *args)
f0 = func(y0, t[0])
dt = initial_step_size(func, t[0], y0, 4, rtol, atol, f0)
interp_coeff = np.array([y0] * 5)
return jax.lax.fori_loop(1,
t.shape[0],
functools.partial(_fori_body_fun, func),
(t, y0, f0, t[0], dt, t[0], interp_coeff,
jax.ops.index_update(
np.zeros((t.shape[0], y0.shape[0])),
jax.ops.index[0, :],
y0)))[-1]
def vjp_odeint(ofunc, y0, t, *args, **kwargs):
"""Return a function that calculates `vjp(odeint(func(y, t, *args))`.
Args:
ofunc: Function `ydot = ofunc(y, t, *args)` to compute the time
derivative of `y`.
y0: initial value for the state.
t: Timespan for `ofunc` evaluation like `np.linspace(0., 10., 101)`.
*args: Additional arguments to `ofunc` beyond y0 and t.
**kwargs: Two relevant keyword arguments:
'rtol': Relative local error tolerance for solver.
'atol': Absolute local error tolerance for solver.
'mxstep': Maximum number of steps to take for each timepoint.
Returns:
VJP function `vjp = vjp_all(g)` where `yt = ofunc(y, t, *args)`
and g is used for VJP calculation. To evaluate the gradient w/ the VJP,
supply `g = np.ones_like(yt)`. To evaluate the reverse Jacobian do a vmap
over the standard basis of yt.
"""
rtol = kwargs.get('rtol', 1.4e-8)
atol = kwargs.get('atol', 1.4e-8)
mxstep = kwargs.get('mxstep', np.inf)
flat_args, unravel_args = ravel_pytree(args)
flat_func = lambda y, t, flat_args: ofunc(y, t, *unravel_args(flat_args))
@jax.jit
def aug_dynamics(augmented_state, t, flat_args):
"""Original system augmented with vjp_y, vjp_t and vjp_args."""
state_len = int(np.floor_divide(
augmented_state.shape[0] - flat_args.shape[0] - 1, 2))
y = augmented_state[:state_len]
adjoint = augmented_state[state_len:2*state_len]
dy_dt, vjpfun = jax.vjp(flat_func, y, t, flat_args)
return np.hstack([np.ravel(dy_dt), np.hstack(vjpfun(-adjoint))])
rev_aug_dynamics = lambda y, t, flat_args: -aug_dynamics(y, -t, flat_args)
@jax.jit
def _fori_body_fun(i, val):
"""fori_loop function for VJP calculation."""
rev_yt, rev_t, rev_tarray, rev_gi, vjp_y, vjp_t0, vjp_args, time_vjp_list = val
this_yt = rev_yt[i, :]
this_t = rev_t[i]
this_tarray = rev_tarray[i, :]
this_gi = rev_gi[i, :]
# this is g[i-1, :] when g has been reversed
this_gim1 = rev_gi[i+1, :]
state_len = this_yt.shape[0]
vjp_cur_t = np.dot(flat_func(this_yt, this_t, flat_args), this_gi)
vjp_t0 = vjp_t0 - vjp_cur_t
# Run augmented system backwards to the previous observation.
aug_y0 = np.hstack((this_yt, vjp_y, vjp_t0, vjp_args))
aug_ans = odeint(rev_aug_dynamics,
aug_y0,
this_tarray,
flat_args,
rtol=rtol,
atol=atol,
mxstep=mxstep)
vjp_y = aug_ans[1][state_len:2*state_len] + this_gim1
vjp_t0 = aug_ans[1][2*state_len]
vjp_args = aug_ans[1][2*state_len+1:]
time_vjp_list = jax.ops.index_update(time_vjp_list, i, vjp_cur_t)
return rev_yt, rev_t, rev_tarray, rev_gi, vjp_y, vjp_t0, vjp_args, time_vjp_list
@jax.jit
def vjp_all(g, yt, t):
"""Calculate the VJP g * Jac(odeint(ofunc, y0, t, *args))."""
rev_yt = yt[-1::-1, :]
rev_t = t[-1::-1]
rev_tarray = -np.array([t[-1:0:-1], t[-2::-1]]).T
rev_gi = g[-1::-1, :]
vjp_y = g[-1, :]
vjp_t0 = 0.
vjp_args = np.zeros_like(flat_args)
time_vjp_list = np.zeros_like(t)
result = jax.lax.fori_loop(0,
rev_t.shape[0]-1,
_fori_body_fun,
(rev_yt,
rev_t,
rev_tarray,
rev_gi,
vjp_y,
vjp_t0,
vjp_args,
time_vjp_list))
time_vjp_list = jax.ops.index_update(result[-1], -1, result[-3])
vjp_times = np.hstack(time_vjp_list)[::-1]
return tuple([result[-4], vjp_times] + list(result[-2]))
primals_out = odeint(flat_func, y0, t, flat_args, rtol=rtol, atol=atol, mxstep=mxstep)
vjp_fun = lambda g: vjp_all(g, primals_out, t)
return primals_out, vjp_fun
def build_odeint(ofunc, rtol=1.4e-8, atol=1.4e-8, mxstep=onp.inf):
"""Return `f(y0, t, args) = odeint(ofunc(y, t, *args), y0, t, args)`.
Given the function ofunc(y, t, *args), return the jitted function
`f(y0, t, args) = odeint(ofunc(y, t, *args), y0, t, args)` with
the VJP of `f` defined using `vjp_odeint`, where:
`y0` is the initial condition of the ODE integration,
`t` is the time course of the integration, and
`*args` are all other arguments to `ofunc`.
Args:
ofunc: The function to be wrapped into an ODE integration.
rtol: relative local error tolerance for solver.
atol: absolute local error tolerance for solver.
mxstep: Maximum number of steps to take for each timepoint.
Returns:
`f(y0, t, args) = odeint(ofunc(y, t, *args), y0, t, args)`
"""
ct_odeint = jax.custom_transforms(
lambda y0, t, *args: odeint(ofunc, y0, t, *args, rtol=rtol, atol=atol, mxstep=mxstep))
v = lambda y0, t, *args: vjp_odeint(ofunc, y0, t, *args, rtol=rtol, atol=atol, mxstep=mxstep)
jax.defvjp_all(ct_odeint, v)
return jax.jit(ct_odeint)
def my_odeint_grad(fun):
"""Calculate the Jacobian of an odeint."""
@jax.jit
def _gradfun(*args, **kwargs):
ys, pullback = vjp_odeint(fun, *args, **kwargs)
my_grad = pullback(np.ones_like(ys))
return my_grad
return _gradfun
def my_odeint_jacrev(fun):
"""Calculate the Jacobian of an odeint."""
@jax.jit
def _jacfun(*args, **kwargs):
ys, pullback = vjp_odeint(fun, *args, **kwargs)
my_jac = jax.vmap(pullback)(jax.api._std_basis(ys))
my_jac = jax.api.tree_map(
functools.partial(jax.api._unravel_array_into_pytree, ys, 0), my_jac)
my_jac = jax.api.tree_transpose(
jax.api.tree_structure(args), jax.api.tree_structure(ys), my_jac)
return my_jac
return _jacfun
def nd(f, x, eps=0.0001):
flat_x, unravel = ravel_pytree(x)
dim = len(flat_x)
g = onp.zeros_like(flat_x)
for i in range(dim):
d = onp.zeros_like(flat_x)
d[i] = eps
g[i] = (f(unravel(flat_x + d)) - f(unravel(flat_x - d))) / (2.0 * eps)
return g
def test_grad_vjp_odeint():
"""Compare numerical and exact differentiation of a simple odeint."""
def f(y, t, arg1, arg2):
return -np.sqrt(t) - y + arg1 - np.mean((y + arg2)**2)
def onearg_odeint(args):
return np.sum(
odeint(f, *args, atol=1e-8, rtol=1e-8))
dim = 10
t0 = 0.1
t1 = 0.2
y0 = np.linspace(0.1, 0.9, dim)
arg1 = 0.1
arg2 = 0.2
wrap_args = (y0, np.array([t0, t1]), arg1, arg2)
numerical_grad = nd(onearg_odeint, wrap_args)
exact_grad, _ = ravel_pytree(my_odeint_grad(f)(*wrap_args))
assert np.allclose(numerical_grad, exact_grad)
def plot_gradient_field(ax, func, xlimits, ylimits, numticks=30):
"""Plot the gradient field of `func` on `ax`."""
x = np.linspace(*xlimits, num=numticks)
y = np.linspace(*ylimits, num=numticks)
x_mesh, y_mesh = np.meshgrid(x, y)
zs = jax.vmap(func)(y_mesh.ravel(), x_mesh.ravel())
z_mesh = zs.reshape(x_mesh.shape)
ax.quiver(x_mesh, y_mesh, np.ones(z_mesh.shape), z_mesh)
ax.set_xlim(xlimits)
ax.set_ylim(ylimits)
@jax.jit
def pend(y, t, arg1, arg2):
"""Simple pendulum system for odeint testing."""
del t
theta, omega = y
dydt = np.array([omega, -arg1*omega - arg2*np.sin(theta)])
return dydt
@jax.jit
def swoop(y, t, arg1, arg2):
return np.array(y - np.sin(t) - np.cos(t) * arg1 + arg2)
@jax.jit
def decay(y, t, arg1, arg2):
return -np.sqrt(t) - y + arg1 - np.mean((y + arg2)**2)
def benchmark_odeint(fun, y0, tspace, *args):
"""Time performance of JAX odeint method against scipy.integrate.odeint."""
n_trials = 5
for k in range(n_trials):
start = time.time()
scipy_result = osp_integrate.odeint(fun, y0, tspace, args)
end = time.time()
print('scipy odeint elapsed time ({} of {}): {}'.format(
k+1, n_trials, end-start))
for k in range(n_trials):
start = time.time()
jax_result = odeint(fun, np.array(y0), np.array(tspace), *args)
jax_result.block_until_ready()
end = time.time()
print('JAX odeint elapsed time ({} of {}): {}'.format(
k+1, n_trials, end-start))
print('norm(scipy result-jax result): {}'.format(
np.linalg.norm(np.asarray(scipy_result) - jax_result)))
return scipy_result, jax_result
def pend_benchmark_odeint():
_, _ = benchmark_odeint(pend,
(onp.pi - 0.1, 0.0),
onp.linspace(0., 10., 101),
0.25,
9.8)
def test_odeint_grad():
"""Test the gradient behavior of various ODE integrations."""
def _test_odeint_grad(func, *args):
def onearg_odeint(fargs):
return np.sum(odeint(func, *fargs))
numerical_grad = nd(onearg_odeint, args)
exact_grad, _ = ravel_pytree(my_odeint_grad(func)(*args))
assert np.allclose(numerical_grad, exact_grad)
ts = np.array((0.1, 0.2))
y0 = np.linspace(0.1, 0.9, 10)
big_y0 = np.linspace(1.1, 10.9, 10)
# check pend()
for cond in (
(np.array((onp.pi - 0.1, 0.0)), ts, 0.25, 0.98),
(np.array((onp.pi * 0.1, 0.0)), ts, 0.1, 0.4),
):
_test_odeint_grad(pend, *cond)
# check swoop
for cond in (
(y0, ts, 0.1, 0.2),
(big_y0, ts, 0.1, 0.3),
):
_test_odeint_grad(swoop, *cond)
# check decay
for cond in (
(y0, ts, 0.1, 0.2),
(big_y0, ts, 0.1, 0.3),
):
_test_odeint_grad(decay, *cond)
def test_odeint_vjp():
"""Use check_vjp to check odeint VJP calculations."""
# check pend()
y = np.array([np.pi - 0.1, 0.0])
t = np.linspace(0., 10., 11)
b = 0.25
c = 9.8
wrap_args = (y, t, b, c)
pend_odeint_wrap = lambda y, t, *args: odeint(pend, y, t, *args)
pend_vjp_wrap = lambda y, t, *args: vjp_odeint(pend, y, t, *args)
check_vjp(pend_odeint_wrap, pend_vjp_wrap, wrap_args)
# check swoop()
y = np.array([0.1])
t = np.linspace(0., 10., 11)
arg1 = 0.1
arg2 = 0.2
wrap_args = (y, t, arg1, arg2)
swoop_odeint_wrap = lambda y, t, *args: odeint(swoop, y, t, *args)
swoop_vjp_wrap = lambda y, t, *args: vjp_odeint(swoop, y, t, *args)
check_vjp(swoop_odeint_wrap, swoop_vjp_wrap, wrap_args)
# decay() check_vjp hangs!
def test_defvjp_all():
"""Use build_odeint to check odeint VJP calculations."""
n_trials = 5
swoop_build = build_odeint(swoop)
jacswoop = jax.jit(jax.jacrev(swoop_build))
y = np.array([0.1])
t = np.linspace(0., 2., 11)
arg1 = 0.1
arg2 = 0.2
wrap_args = (y, t, arg1, arg2)
for k in range(n_trials):
start = time.time()
rslt = jacswoop(*wrap_args)
rslt.block_until_ready()
end = time.time()
print('JAX jacrev elapsed time ({} of {}): {}'.format(
k+1, n_trials, end-start))
if __name__ == '__main__':
test_odeint_grad()
test_odeint_vjp()
|
jax-master
|
jax/experimental/ode.py
|
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
r"""Tool to convert a JAX function to an HLO proto.
This script is meant to be used as part of a genrule that converts a JAX program
into an HLO proto. The HLO proto represents an XLA program, and can be run from
e.g. a C++ program, without involving any Python.
This lets you use JAX as a convenient frontend for writing "XLA programs". From
another perspective, this script lets you make JAX into an ahead-of-time JAX ->
XLA compiler, although when you run the XLA program, it will still be compiled
just-in-time.
See tensorflow/compiler/xla/service/hlo_runner.h.
Usage:
$ cat prog.py
import jax.numpy as np
def fn(x, y, z):
return np.dot(x, y) / z
$ python jax_to_hlo.py \
--fn prog.fn \
--input_shapes '[("y": "f32[128,32]"), ("x", "f32[8,128]")]' \
--constants '{"z": 3.14159}' \
--hlo_text_dest /tmp/fn_hlo.txt \
--hlo_proto_dest /tmp/fn_hlo.pb
Alternatively, you can use this script via a genrule. This way bazel will
generate the hlo text/proto as part of compilation, and then e.g. a C++ program
can depend on this. See jax_to_hlo macro in build_defs.bzl.
The order of elements in input_shapes determines the order of parameters in the
resulting HLO program.
Values of `constants` which are lists are converted to Numpy arrays using
np.asarray. In addition, you can specify constants using the flag
--evaled_constants; values there that are strings are first evaluated using
ast.literal_eval. --evaled_constants is primarily useful for genrules; Skylark
doesn't support floating-point types, so genrules need to deal in strings.
Note that XLA's backwards-compatibility guarantees for saved HLO are currently
(2019-06-13) best-effort. It will mostly work, but it will occasionally break,
and the XLA team won't (and in fact will be unable to) help. One way to be sure
it won't break is to use the same version of XLA to build the HLO as you use to
run it. The genrule above makes this easy.
Implementation note: This script must be python2 compatible for now, because
Google's genrules still run with python2, b/66712815.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ast import literal_eval
import importlib
import functools
from absl import app
from absl import flags
import jax.api
import jax.numpy as np
from jax.lib import xla_client
FLAGS = flags.FLAGS
def jax_to_hlo(fn, input_shapes, constants=None):
"""Converts a JAX function to an HLO module.
Args:
fn: Function to convert.
input_shapes: List of tuples (arg name, xla_client.Shape),
indicating the shapes of the arguments to fn. The order of parameters in
the resulting XLA program will match the order in this list.
constants: Dict mapping function argument name to a Python value. Specified
arguments these values as compile-time constants.
Returns:
A tuple (serialized_hlo_proto, hlo_text).
"""
if not constants:
constants = {}
overlapping_args = set(arg_name for arg_name, _ in input_shapes) & set(
constants.keys())
if overlapping_args:
raise ValueError(
'Arguments appear in both `input_shapes` and `constants`: %s' %
', '.join(sorted(overlapping_args)))
args = []
for arg_name, shape in input_shapes:
if not shape.is_array():
raise ValueError('Shape %s is not an array, but currently only arrays '
'are supported (i.e., no tuples).' % str(shape))
# Check that `shape` either doesn't have a layout or has the default layout.
#
# TODO(jlebar): This could be simpler if the Shape class exposed its layout,
# or if Shape exposed a function to unconditionally use the default layout.
shape_with_default_layout = xla_client.Shape.array_shape(
shape.xla_element_type(),
shape.dimensions()).with_major_to_minor_layout_if_absent()
if (shape.with_major_to_minor_layout_if_absent() !=
shape_with_default_layout):
raise ValueError('Shape %s has a non-default layout, but only '
'the default layout is allowed.' % str(shape))
args.append(np.zeros(shape.dimensions(), dtype=shape.numpy_dtype()))
# Curry `constants` into the function.
fn_curried = functools.partial(fn, **constants)
# Wrapper that takes in args in the order of `input_shapes` and converts them
# to kwargs for calling `fn`.
def ordered_wrapper(*args):
arg_names = [arg_name for arg_name, _ in input_shapes]
return fn_curried(**dict(zip(arg_names, args)))
comp = jax.api.xla_computation(ordered_wrapper)(*args)
return (comp.GetSerializedProto(), comp.GetHloText())
def main(argv):
if len(argv) != 1:
raise app.UsageError('No positional arguments are accepted.')
if not FLAGS.hlo_proto_dest and not FLAGS.hlo_text_dest:
raise app.Error('At least one of --hlo_proto_dest and '
'--hlo_text_dest is required.')
module_name, fn_name = FLAGS.fn.rsplit('.', 1)
module = importlib.import_module(module_name)
fn = getattr(module, fn_name)
input_shapes = [(name, xla_client.Shape(shape_str))
for name, shape_str in literal_eval(FLAGS.input_shapes)]
# Parse --constants and --evaled_constants.
constants = {}
for k, v in literal_eval(FLAGS.constants).items():
if isinstance(v, list):
v = np.asarray(v)
constants[k] = v
for k, v in literal_eval(FLAGS.evaled_constants).items():
if isinstance(v, str):
v = literal_eval(v)
if isinstance(v, list):
v = np.asarray(v)
if k in constants:
raise ValueError(
'Argument appears in both --constants and --evaled_constants: %s' % k)
constants[k] = v
hlo_proto, hlo_text = jax_to_hlo(fn, input_shapes, constants)
if FLAGS.hlo_proto_dest:
with open(FLAGS.hlo_proto_dest, 'wb') as f:
f.write(hlo_proto)
if FLAGS.hlo_text_dest:
with open(FLAGS.hlo_text_dest, 'w') as f:
f.write(hlo_text)
def set_up_flags():
flags.DEFINE_string(
'fn', None,
"Fully-qualified name of function that we're going to convert")
flags.DEFINE_string('input_shapes', None,
'Python dict indicating XLA shapes of params')
flags.DEFINE_string('constants', '{}',
'Python dict giving constant values for some params')
flags.DEFINE_string('evaled_constants', '{}',
'Python dict giving constant values for some params. '
'Values in this dict that are of type str are evaluated '
'using ast.literal_eval.')
flags.DEFINE_string('hlo_proto_dest', None, 'File to write HLO proto')
flags.DEFINE_string('hlo_text_dest', None, 'File to write HLO text')
flags.mark_flag_as_required('fn')
flags.mark_flag_as_required('input_shapes')
if __name__ == '__main__':
set_up_flags()
app.run(main)
|
jax-master
|
jax/tools/jax_to_hlo.py
|
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
|
jax-master
|
jax/tools/__init__.py
|
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
"""Shared neural network activations and other functions."""
from __future__ import absolute_import
from __future__ import division
import numpy as onp
from jax import lax
from jax import random
from jax.scipy.special import expit
import jax.numpy as np
from jax import jarrett
# activations
def relu(x):
r"""Rectified linear unit activation function.
Computes the element-wise function:
.. math::
\mathrm{relu}(x) = \max(x, 0)
"""
return np.maximum(x, 0)
def softplus(x):
r"""Softplus activation function.
Computes the element-wise function
.. math::
\mathrm{softplus}(x) = \log(1 + e^x)
"""
return np.logaddexp(x, 0)
def soft_sign(x):
r"""Soft-sign activation function.
Computes the element-wise function
.. math::
\mathrm{soft\_sign}(x) = \frac{x}{|x| + 1}
"""
return x / (np.abs(x) + 1)
def sigmoid(x):
r"""Sigmoid activation function.
Computes the element-wise function:
.. math::
\mathrm{sigmoid}(x) = \frac{1}{1 + e^{-x}}
"""
return expit(x)
def swish(x):
r"""Swish activation function.
Computes the element-wise function:
.. math::
\mathrm{swish}(x) = x \cdot \mathrm{sigmoid}(x) = \frac{x}{1 + e^{-x}}
"""
return x * sigmoid(x)
def log_sigmoid(x):
r"""Log-sigmoid activation function.
Computes the element-wise function:
.. math::
\mathrm{log\_sigmoid}(x) = \log(\mathrm{sigmoid}(x)) = -\log(1 + e^{-x})
"""
return -softplus(-x)
def elu(x, alpha=1.0):
r"""Exponential linear unit activation function.
Computes the element-wise function:
.. math::
\mathrm{elu}(x) = \begin{cases}
x, & x > 0\\
\alpha \exp(x - 1), & x \le 0
\end{cases}
"""
safe_x = np.where(x > 0, 0., x)
return np.where(x > 0, x, alpha * np.expm1(safe_x))
def leaky_relu(x, negative_slope=1e-2):
r"""Leaky rectified linear unit activation function.
Computes the element-wise function:
.. math::
\mathrm{leaky\_relu}(x) = \begin{cases}
x, & x \ge 0\\
\alpha x, & x < 0
\end{cases}
where :math:`\alpha` = :code:`negative_slope`.
"""
return np.where(x >= 0, x, negative_slope * x)
def hard_tanh(x):
r"""Hard :math:`\mathrm{tanh}` activation function.
Computes the element-wise function:
.. math::
\mathrm{hard\_tanh}(x) = \begin{cases}
-1, & x < -1\\
x, & 0 \le x \le 1\\
1, & 1 < x
\end{cases}
"""
return np.where(x > 1, 1, np.where(x < -1, -1, x))
def celu(x, alpha=1.0):
r"""Continuously-differentiable exponential linear unit activation.
Computes the element-wise function:
.. math::
\mathrm{celu}(x) = \begin{cases}
x, & x > 0\\
\alpha \exp(\frac{x}{\alpha} - 1), & x \le 0
\end{cases}
For more information, see
`Continuously Differentiable Exponential Linear Units
<https://arxiv.org/pdf/1704.07483.pdf>`_."""
return np.where(x > 0, x, alpha * np.expm1(x / alpha))
def selu(x):
r"""Scaled exponential linear unit activation.
Computes the element-wise function:
.. math::
\mathrm{selu}(x) = \lambda \begin{cases}
x, & x > 0\\
\alpha e^x - \alpha, & x \le 0
\end{cases}
where :math:`\lambda = 1.0507009873554804934193349852946` and
:math:`\alpha = 1.6732632423543772848170429916717`.
For more information, see
`Self-Normalizing Neural Networks
<https://papers.nips.cc/paper/6698-self-normalizing-neural-networks.pdf>`_.
"""
alpha = 1.6732632423543772848170429916717
scale = 1.0507009873554804934193349852946
return scale * elu(x, alpha)
def gelu(x):
r"""Gaussian error linear unit activation function.
Computes the element-wise function:
.. math::
\mathrm{gelu}(x) = \frac{x}{2} \left(1 + \mathrm{tanh} \left(
\sqrt{\frac{2}{\pi}} \left(x + 0.044715 x^3 \right) \right) \right)
We explicitly use the approximation rather than the exact formulation for
speed. For more information, see `Gaussian Error Linear Units (GELUs)
<https://arxiv.org/abs/1606.08415>`_, section 2.
"""
cdf = 0.5 * (1.0 + np.tanh((np.sqrt(2 / np.pi) * (x + 0.044715 * x**3))))
return x * cdf
def glu(x, axis=-1):
"""Gated linear unit activation function."""
size = x.shape[axis]
assert size % 2 == 0, "axis size must be divisible by 2"
return x[..., :size] * sigmoid(x[..., size:])
# other functions
def log_softmax(x, axis=-1):
r"""Log-Softmax function.
Computes the logarithm of the :code:`softmax` function, which rescales
elements to the range :math:`[-\infty, 0)`.
.. math ::
\mathrm{log\_softmax}(x) = \log \left( \frac{\exp(x_i)}{\sum_j \exp(x_j)}
\right)
Args:
axis: the axis or axes along which the :code:`log_softmax` should be
computed. Either an integer or a tuple of integers.
"""
shifted = x - x.max(axis, keepdims=True)
return shifted - np.log(np.sum(np.exp(shifted), axis, keepdims=True))
def softmax(x, axis=-1):
r"""Softmax function.
Computes the function which rescales elements to the range :math:`[0, 1]`
such that the elements along :code:`axis` sum to :math:`1`.
.. math ::
\mathrm{softmax}(x) = \frac{\exp(x_i)}{\sum_j \exp(x_j)}
Args:
axis: the axis or axes along which the softmax should be computed. The
softmax output summed across these dimensions should sum to :math:`1`.
Either an integer or a tuple of integers.
"""
unnormalized = np.exp(x - x.max(axis, keepdims=True))
return unnormalized / unnormalized.sum(axis, keepdims=True)
def normalize(x, axis=-1, mean=None, variance=None, epsilon=1e-5):
"""Normalizes an array by subtracting mean and dividing by sqrt(var)."""
if mean is None:
mean = np.mean(x, axis, keepdims=True)
if variance is None:
# this definition is traditionally seen as less accurate than np.var's
# mean((x - mean(x))**2) but may be faster and even, given typical
# activation distributions and low-precision arithmetic, more accurate
# when used in neural network normalization layers
variance = np.mean(x**2, axis, keepdims=True) - mean**2
return (x - mean) * lax.rsqrt(variance + epsilon)
|
jax-master
|
jax/nn/functions.py
|
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
"""Common functions for neural network libraries."""
from . import initializers
from .functions import *
|
jax-master
|
jax/nn/__init__.py
|
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
"""
Common neural network layer initializers, consistent with definitions
used in Keras and Sonnet.
"""
from __future__ import absolute_import
from __future__ import division
from functools import partial
import numpy as onp
import jax.numpy as np
from jax import lax
from jax import ops
from jax import random
def zeros(key, shape, dtype=np.float32): return np.zeros(shape, dtype)
def ones(key, shape, dtype=np.float32): return np.ones(shape, dtype)
def uniform(scale=1e-2):
def init(key, shape, dtype=np.float32):
return random.uniform(key, shape, dtype) * scale
return init
def normal(stddev=1e-2):
def init(key, shape, dtype=np.float32):
return random.normal(key, shape, dtype) * stddev
return init
def _compute_fans(shape, in_axis=-2, out_axis=-1):
receptive_field_size = onp.prod(shape) / shape[in_axis] / shape[out_axis]
fan_in = shape[in_axis] * receptive_field_size
fan_out = shape[out_axis] * receptive_field_size
return fan_in, fan_out
def variance_scaling(scale, mode, distribution, in_axis=-2, out_axis=-1):
def init(key, shape, dtype=np.float32):
fan_in, fan_out = _compute_fans(shape, in_axis, out_axis)
if mode == "fan_in": denominator = fan_in
elif mode == "fan_out": denominator = fan_out
elif mode == "fan_avg": denominator = (fan_in + fan_out) / 2
else:
raise ValueError(
"invalid mode for variance scaling initializer: {}".format(mode))
variance = np.array(scale / denominator, dtype=dtype)
if distribution == "truncated_normal":
# constant is stddev of standard normal truncated to (-2, 2)
stddev = np.sqrt(variance) / np.array(.87962566103423978, dtype)
return random.truncated_normal(key, -2, 2, shape, dtype) * stddev
elif distribution == "normal":
return random.normal(key, shape, dtype) * np.sqrt(variance)
elif distribution == "uniform":
return random.uniform(key, shape, dtype, -1) * onp.sqrt(3 * variance)
else:
raise ValueError("invalid distribution for variance scaling initializer")
return init
xavier_uniform = glorot_uniform = partial(variance_scaling, 1.0, "fan_avg", "uniform")
xavier_normal = glorot_normal = partial(variance_scaling, 1.0, "fan_avg", "truncated_normal")
lecun_uniform = partial(variance_scaling, 1.0, "fan_in", "uniform")
lecun_normal = partial(variance_scaling, 1.0, "fan_in", "truncated_normal")
kaiming_uniform = he_uniform = partial(variance_scaling, 2.0, "fan_in", "uniform")
kaiming_normal = he_normal = partial(variance_scaling, 2.0, "fan_in", "truncated_normal")
def orthogonal(scale=1.0, column_axis=-1):
"""
Construct an initializer for uniformly distributed orthogonal matrices.
If the shape is not square, the matrices will have orthonormal rows or columns
depending on which side is smaller.
"""
def init(key, shape, dtype=np.float32):
if len(shape) < 2:
raise ValueError("orthogonal initializer requires at least a 2D shape")
n_rows, n_cols = onp.prod(shape) // shape[column_axis], shape[column_axis]
matrix_shape = (n_cols, n_rows) if n_rows < n_cols else (n_rows, n_cols)
A = random.normal(key, matrix_shape, dtype)
Q, R = np.linalg.qr(A)
Q *= np.sign(np.diag(R)) # needed for a uniform distribution
if n_rows < n_cols: Q = Q.T
Q = np.reshape(Q, tuple(onp.delete(shape, column_axis)) + (shape[column_axis],))
Q = np.moveaxis(Q, -1, column_axis)
return scale * Q
return init
def delta_orthogonal(scale=1.0, column_axis=-1):
"""
Construct an initializer for delta orthogonal kernels; see arXiv:1806.05393.
The shape must be 3D, 4D or 5D.
"""
def init(key, shape, dtype=np.float32):
if len(shape) not in [3, 4, 5]:
raise ValueError("Delta orthogonal initializer requires a 3D, 4D or 5D "
"shape.")
if shape[-1] < shape[-2]:
raise ValueError("`fan_in` must be less or equal than `fan_out`. ")
ortho_init = orthogonal(scale=scale, column_axis=column_axis)
ortho_matrix = ortho_init(key, shape[-2:])
W = np.zeros(shape)
if len(shape) == 3:
k = shape[0]
return ops.index_update(W, ops.index[(k-1)//2, ...], ortho_matrix)
elif len(shape) == 4:
k1, k2 = shape[:2]
return ops.index_update(W, ops.index[(k1-1)//2, (k2-1)//2, ...], ortho_matrix)
else:
k1, k2, k3 = shape[:3]
return ops.index_update(W, ops.index[(k1-1)//2, (k2-1)//2, (k3-1)//2, ...],
ortho_matrix)
return init
|
jax-master
|
jax/nn/initializers.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import enum
import functools
import itertools
import operator
import string
import warnings
import six
from six.moves import builtins, xrange
import numpy as onp
from ..util import partial, prod
from .. import core
from .. import ad_util
from .. import api
from .. import linear_util as lu
from .. import dtypes
from ..config import flags
from ..core import Primitive
from ..abstract_arrays import (UnshapedArray, ShapedArray, ConcreteArray,
AbstractToken, array_types, make_shaped_array,
raise_to_shaped, abstract_token)
from ..interpreters import partial_eval as pe
from ..interpreters import xla
from ..interpreters import pxla
from ..interpreters import ad
from ..interpreters import batching
from ..interpreters import masking
from ..interpreters.masking import ShapeExpr, ShapeError
from ..util import curry, cache, safe_zip, unzip2, prod
from ..tree_util import build_tree, tree_unflatten, tree_map
from ..lib import pytree
from ..lib import xla_bridge
from ..lib import xla_client
FLAGS = flags.FLAGS
_max = builtins.max
_min = builtins.max
_reduce = six.moves.reduce
@cache()
def broadcast_shapes(*shapes):
"""Returns the shape that results from NumPy broadcasting of `shapes`."""
if len(shapes) == 1:
return shapes[0]
ndim = _max(len(shape) for shape in shapes)
shapes = onp.array([(1,) * (ndim - len(shape)) + shape for shape in shapes])
min_shape = onp.min(shapes, axis=0)
max_shape = onp.max(shapes, axis=0)
result_shape = onp.where(min_shape == 0, 0, max_shape)
if not onp.all((shapes == result_shape) | (shapes == 1)):
raise ValueError("Incompatible shapes for broadcasting: {}"
.format(tuple(map(tuple, shapes))))
return tuple(result_shape)
def _canonicalize_shape(shape):
"""Canonicalizes and checks for errors in a user-provided shape value.
Args:
shape: a Python value that represents a shape.
Returns:
A tuple of integers.
"""
# TODO(mattjj): this next check is a temporary workaround for masking
if (type(shape) is ShapeExpr
or type(shape) is tuple and any(type(d) is masking.Poly for d in shape)):
return shape
try:
return tuple(map(operator.index, shape))
except TypeError:
pass
msg = ("Shapes must be 1D sequences of concrete values of integer type, "
"got {}")
raise TypeError(msg.format(shape))
def _identity(x): return x
### traceables
def neg(x):
r"""Elementwise negation: :math:`-x`."""
return neg_p.bind(x)
def sign(x):
r"""Elementwise sign.
:math:`\mathrm{sign}(x) = \begin{cases}
-1 & x < 0\\
-0 & x = -0\\
\mathit{NaN} & x = \mathit{NaN}\\
+0 & x = +0\\
1 & x > 0
\end{cases}`.
"""
return sign_p.bind(x)
def nextafter(x1, x2):
r"""Returns the next representable value after `x1` in the direction of `x2`."""
return nextafter_p.bind(_brcast(x1, x2), _brcast(x2, x1))
def floor(x):
r"""Elementwise floor: :math:`\left\lfloor x \right\rfloor`."""
return floor_p.bind(x)
def ceil(x):
r"""Elementwise ceiling: :math:`\left\lceil x \right\rceil`."""
return ceil_p.bind(x)
def round(x):
r"""Elementwise round.
Rounds values to the nearest integer. Halfway values (e.g., `0.5`) are rounded
away from zero."""
return round_p.bind(x)
def is_finite(x):
r"""Elementwise :math:`\mathrm{isfinite}`.
For each element x returns `True` if and only if x is not :math:`\pm\infty` or
:math:`\mathit{NaN}`.
"""
return is_finite_p.bind(x)
def exp(x):
r"""Elementwise exponential: :math:`e^x`."""
return exp_p.bind(x)
def expm1(x):
r"""Elementwise :math:`e^{x - 1}`."""
return expm1_p.bind(x)
def log(x):
r"""Elementwise natural logarithm: :math:`\mathrm{log}(x)`."""
return log_p.bind(x)
def log1p(x):
r"""Elementwise :math:`\mathrm{log}(1 + x)`."""
return log1p_p.bind(x)
def tanh(x):
r"""Elementwise hyperbolic tangent: :math:`\mathrm{tanh}(x)`."""
return tanh_p.bind(x)
def sin(x):
r"""Elementwise sine: :math:`\mathrm{sin}(x)`."""
return sin_p.bind(x)
def cos(x):
r"""Elementwise cosine: :math:`\mathrm{cos}(x)`."""
return cos_p.bind(x)
def atan2(x, y):
r"""Elementwise arc tangent of two variables:
:math:`\mathrm{atan}({x \over y})`."""
return atan2_p.bind(x, y)
def lgamma(x):
r"""Elementwise log gamma: :math:`\mathrm{log}(\Gamma(x))`."""
return lgamma_p.bind(x)
def digamma(x):
r"""Elementwise digamma: :math:`\psi(x)`."""
return digamma_p.bind(x)
def bessel_i0e(x):
r"""Exponentially scaled modified Bessel function of order 0:
:math:`\mathrm{i0e}(x) = e^{-|x|} \mathrm{i0}(x)`
"""
return bessel_i0e_p.bind(x)
def bessel_i1e(x):
r"""Exponentially scaled modified Bessel function of order 1:
:math:`\mathrm{i1e}(x) = e^{-|x|} \mathrm{i1}(x)`
"""
return bessel_i1e_p.bind(x)
def erf(x):
r"""Elementwise error function: :math:`\mathrm{erf}(x)`."""
return erf_p.bind(x)
def erfc(x):
r"""Elementwise complementary error function:
:math:`\mathrm{erfc}(x) = 1 - \mathrm{erf}(x)`."""
return erfc_p.bind(x)
def erf_inv(x):
r"""Elementwise inverse error function: :math:`\mathrm{erf}^{-1}(x)`."""
return erf_inv_p.bind(x)
def real(x):
r"""Elementwise extract real part: :math:`\mathrm{Re}(x)`.
Returns the real part of a complex number.
"""
return real_p.bind(x)
def imag(x):
r"""Elementwise extract imaginary part: :math:`\mathrm{Im}(x)`.
Returns the imaginary part of a complex number.
"""
return imag_p.bind(x)
def complex(x, y):
r"""Elementwise make complex number: :math:`x + jy`.
Builds a complex number from real and imaginary parts.
"""
return complex_p.bind(_brcast(x, y), _brcast(y, x))
def conj(x):
r"""Elementwise complex conjugate function: :math:`\overline{x}`."""
return conj_p.bind(x, input_dtype=_dtype(x))
def abs(x):
r"""Elementwise absolute value: :math:`|x|`."""
return abs_p.bind(x)
def pow(x, y):
r"""Elementwise power: :math:`x^y`."""
return pow_p.bind(x, y)
def sqrt(x):
r"""Elementwise square root: :math:`\sqrt{x}`."""
return sqrt_p.bind(x)
def rsqrt(x):
r"""Elementwise reciprocal square root: :math:`1 \over \sqrt{x}."""
return rsqrt_p.bind(x)
def bitwise_not(x):
r"""Elementwise NOT: :math:`\neg x`."""
return not_p.bind(x)
def bitwise_and(x, y):
r"""Elementwise AND: :math:`x \wedge y`."""
return and_p.bind(x, y)
def bitwise_or(x, y):
r"""Elementwise OR: :math:`x \vee y`."""
return or_p.bind(x, y)
def bitwise_xor(x, y):
r"""Elementwise exclusive OR: :math:`x \oplus y`."""
return xor_p.bind(x, y)
def add(x, y):
r"""Elementwise addition: :math:`x + y`."""
return add_p.bind(x, y)
def sub(x, y):
r"""Elementwise subtraction: :math:`x - y`."""
return sub_p.bind(x, y)
def mul(x, y):
r"""Elementwise multiplication: :math:`x \times y`."""
return mul_p.bind(x, y)
def div(x, y):
r"""Elementwise division: :math:`x \over y`."""
return div_p.bind(x, y)
def rem(x, y):
r"""Elementwise remainder: :math:`x \bmod y`."""
return rem_p.bind(x, y)
def max(x, y):
r"""Elementwise maximum: :math:`\mathrm{max}(x, y)`
For complex numbers, uses a lexicographic comparison on the
`(real, imaginary)` pairs."""
return max_p.bind(x, y)
def min(x, y):
r"""Elementwise minimum: :math:`\mathrm{min}(x, y)`
For complex numbers, uses a lexicographic comparison on the
`(real, imaginary)` pairs."""
return min_p.bind(x, y)
def shift_left(x, y):
r"""Elementwise left shift: :math:`x \ll y`."""
return shift_left_p.bind(x, y)
def shift_right_arithmetic(x, y):
r"""Elementwise arithmetic right shift: :math:`x \gg y`."""
return shift_right_arithmetic_p.bind(x, y)
def shift_right_logical(x, y):
r"""Elementwise logical right shift: :math:`x \gg y`."""
return shift_right_logical_p.bind(x, y)
def eq(x, y):
r"""Elementwise equals: :math:`x = y`."""
return eq_p.bind(x, y)
def ne(x, y):
r"""Elementwise not-equals: :math:`x \neq y`."""
return ne_p.bind(x, y)
def ge(x, y):
r"""Elementwise greater-than-or-equals: :math:`x \geq y`."""
return ge_p.bind(x, y)
def gt(x, y):
r"""Elementwise greater-than: :math:`x > y`."""
return gt_p.bind(x, y)
def le(x, y):
r"""Elementwise less-than-or-equals: :math:`x \leq y`."""
return le_p.bind(x, y)
def lt(x, y):
r"""Elementwise less-than: :math:`x < y`."""
return lt_p.bind(x, y)
def convert_element_type(operand, new_dtype):
"""Elementwise cast.
Wraps XLA's `ConvertElementType
<https://www.tensorflow.org/xla/operation_semantics#convertelementtype>`_
operator, which performs an elementwise conversion from one type to another.
Similar to a C++ `static_cast`.
Args:
operand: an array or scalar value to be cast
new_dtype: the new type. Should be a NumPy type.
Returns:
An array with the same shape as `operand`, cast elementwise to `new_dtype`.
"""
new_dtype = dtypes.canonicalize_dtype(new_dtype)
# Avoids dropping precision by casting Python scalars to the default Jax
# type. If we passed a Python scalar directly to the bind call below, it is
# cast to the default type as part of the calling convention.
if type(operand) in dtypes.python_scalar_dtypes:
operand = onp.asarray(operand, new_dtype)
old_dtype = dtypes.canonicalize_dtype(_dtype(operand))
if old_dtype == new_dtype:
return operand
if (dtypes.issubdtype(old_dtype, onp.complexfloating) and
not dtypes.issubdtype(new_dtype, onp.complexfloating)):
msg = "Casting complex values to real discards the imaginary part"
warnings.warn(msg, onp.ComplexWarning, stacklevel=2)
operand = real(operand)
old_dtype = _dtype(operand)
# TODO(b/143311238, b/142974574): work around bfloat16 conversion bugs by
# introducing an intermediate cast via float32.
if ((old_dtype == dtypes.bfloat16 and new_dtype != onp.float32) or
(new_dtype == dtypes.bfloat16 and old_dtype != onp.float32)):
operand = convert_element_type_p.bind(
operand, new_dtype=onp.float32, old_dtype=old_dtype)
old_dtype = onp.float32
return convert_element_type_p.bind(
operand, new_dtype=new_dtype, old_dtype=old_dtype)
def bitcast_convert_type(operand, new_dtype):
"""Elementwise bitcast.
Wraps XLA's `BitcastConvertType
<https://www.tensorflow.org/xla/operation_semantics#bitcastconverttype>`_
operator, which performs a bit cast from one type to another. The bitwidth
of the source and destination types must match.
Args:
operand: an array or scalar value to be cast
new_dtype: the new type. Should be a NumPy type.
Returns:
An array with the same shape as `operand`, bitcast elementwise to
`new_dtype`.
"""
new_dtype = dtypes.canonicalize_dtype(new_dtype)
old_dtype = _dtype(operand)
if old_dtype != new_dtype:
return bitcast_convert_type_p.bind(operand, new_dtype=new_dtype)
else:
return operand
def clamp(min, x, max):
r"""Elementwise clamp.
Returns :math:`\mathrm{clamp}(x) = \begin{cases}
\mathit{min} & \text{if } x < \mathit{min},\\
\mathit{max} & \text{if } x > \mathit{max},\\
x & \text{otherwise}
\end{cases}`.
"""
return clamp_p.bind(min, x, max)
def concatenate(operands, dimension):
"""Concatenates a sequence of arrays along `dimension`.
Wraps XLA's `Concatenate
<https://www.tensorflow.org/xla/operation_semantics#concatenate>`_
operator.
Args:
operands: a sequence of arrays to concatenate. The arrays must have equal
shapes, except in the `dimension` axis.
dimension: the dimension along which to concatenate the arrays.
Returns:
An array containing the concatenation.
"""
return concatenate_p.bind(*operands, dimension=dimension,
operand_shapes=tuple(o.shape for o in operands))
Precision = xla_client.PrecisionConfig.Precision
Precision.__str__ = lambda precision: precision.name
def conv_general_dilated(lhs, rhs, window_strides, padding, lhs_dilation=None,
rhs_dilation=None, dimension_numbers=None,
feature_group_count=1, precision=None):
"""General n-dimensional convolution operator, with optional dilation.
Wraps XLA's `Conv
<https://www.tensorflow.org/xla/operation_semantics#conv_convolution>`_
operator.
Args:
lhs: a rank `n+2` dimensional input array.
rhs: a rank `n+2` dimensional array of kernel weights.
window_strides: a sequence of `n` integers, representing the inter-window
strides.
padding: either the string `'SAME'`, the string `'VALID'`, or a sequence of
`n` `(low, high)` integer pairs that give the padding to apply before and
after each spatial dimension.
lhs_dilation: `None`, or a sequence of `n` integers, giving the
dilation factor to apply in each spatial dimension of `lhs`. LHS dilation
is also known as transposed convolution.
rhs_dilation: `None`, or a sequence of `n` integers, giving the
dilation factor to apply in each spatial dimension of `rhs`. RHS dilation
is also known as atrous convolution.
dimension_numbers: either `None`, a `ConvDimensionNumbers` object, or
a 3-tuple `(lhs_spec, rhs_spec, out_spec)`, where each element is a string
of length `n+2`.
feature_group_count: integer, default 1. See XLA HLO docs.
precision: Optional. Either `None`, which means the default precision for
the backend, or a `Precision` enum value.
Returns:
An array containing the convolution result.
In the string case of `dimension_numbers`, each character identifies by
position:
- the batch dimensions in `lhs`, `rhs`, and the output with the character
'N',
- the feature dimensions in `lhs` and the output with the character 'C',
- the input and output feature dimensions in rhs with the characters 'I'
and 'O' respectively, and
- spatial dimension correspondences between lhs, rhs, and the output using
any distinct characters.
For example, to indicate dimension numbers consistent with the `conv` function
with two spatial dimensions, one could use `('NCHW', 'OIHW', 'NCHW')`. As
another example, to indicate dimension numbers consistent with the TensorFlow
Conv2D operation, one could use `('NHWC', 'HWIO', 'NHWC')`. When using the
latter form of convolution dimension specification, window strides are
associated with spatial dimension character labels according to the order in
which the labels appear in the `rhs_spec` string, so that `window_strides[0]`
is matched with the dimension corresponding to the first character
appearing in rhs_spec that is not `'I'` or `'O'`.
If `dimension_numbers` is `None`, the default is `('NCHW', 'OIHW', 'NCHW')`
(for a 2D convolution).
"""
if type(dimension_numbers) is not ConvDimensionNumbers:
dimension_numbers = conv_dimension_numbers(
lhs.shape, rhs.shape, dimension_numbers)
if lhs_dilation is None:
lhs_dilation = (1,) * (lhs.ndim - 2)
elif isinstance(padding, str) and not len(lhs_dilation) == lhs_dilation.count(1):
raise ValueError(
"String padding is not implemented for transposed convolution "
"using this op. Please either exactly specify the required padding or "
"use conv_transpose.")
if rhs_dilation is None:
rhs_dilation = (1,) * (rhs.ndim - 2)
if isinstance(padding, str):
lhs_perm, rhs_perm, _ = dimension_numbers
rhs_shape = onp.take(rhs.shape, rhs_perm)[2:]
effective_rhs_shape = [(k-1) * r + 1 for k, r in zip(rhs_shape, rhs_dilation)]
padding = padtype_to_pads(
onp.take(lhs.shape, lhs_perm)[2:], effective_rhs_shape,
window_strides, padding)
return conv_general_dilated_p.bind(
lhs, rhs, window_strides=tuple(window_strides), padding=tuple(padding),
lhs_dilation=tuple(lhs_dilation), rhs_dilation=tuple(rhs_dilation),
dimension_numbers=dimension_numbers,
feature_group_count=feature_group_count,
lhs_shape=lhs.shape, rhs_shape=rhs.shape,
precision=_canonicalize_precision(precision))
def dot(lhs, rhs, precision=None):
"""Vector/vector, matrix/vector, and matrix/matrix multiplication.
Wraps XLA's `Dot
<https://www.tensorflow.org/xla/operation_semantics#dot>`_
operator.
For more general contraction, see the `dot_general` operator.
Args:
lhs: an array of rank 1 or 2.
rhs: an array of rank 1 or 2.
precision: Optional. Either `None`, which means the default precision for
the backend, or a `Precision` enum value.
Returns:
An array containing the product.
"""
if 1 <= lhs.ndim <= 2 and 1 <= rhs.ndim <= 2 and lhs.shape[-1] == rhs.shape[0]:
return dot_general(lhs, rhs, (((lhs.ndim - 1,), (0,)), ((), ())),
precision=precision)
else:
raise TypeError("Incompatible shapes for dot: got {} and {}.".format(
lhs.shape, rhs.shape))
def dot_general(lhs, rhs, dimension_numbers, precision=None):
"""More general contraction operator.
Wraps XLA's `DotGeneral
<https://www.tensorflow.org/xla/operation_semantics#dotgeneral>`_
operator.
Args:
lhs: an array
rhs: an array
dimension_numbers: a tuple of tuples of the form
`((lhs_contracting_dims, rhs_contracting_dims),
(lhs_batch_dims, rhs_batch_dims))`
precision: Optional. Either `None`, which means the default precision for
the backend, or a `Precision` enum value.
Returns:
An array containing the result.
"""
contract_dims, batch_dims = dimension_numbers
contract_dims = tuple(map(tuple, contract_dims))
batch_dims = tuple(map(tuple, batch_dims))
if not dtypes.issubdtype(lhs.dtype, onp.inexact):
# TODO(b/134526360): XLA doesn't support bool or integer dots, so we emit a
# sum of products instead.
lhs_contract_dims, rhs_contract_dims = contract_dims
lhs_batch_dims, rhs_batch_dims = batch_dims
lhs_noncontract_dims = tuple(sorted(
set(range(onp.ndim(lhs))) - set(lhs_batch_dims) - set(lhs_contract_dims)))
rhs_noncontract_dims = tuple(sorted(
set(range(onp.ndim(rhs))) - set(rhs_batch_dims) - set(rhs_contract_dims)))
lhs = transpose(lhs,
lhs_batch_dims + lhs_noncontract_dims + lhs_contract_dims)
rhs = transpose(rhs,
rhs_batch_dims + rhs_noncontract_dims + rhs_contract_dims)
new_lhs_shape = onp.insert(onp.array(onp.shape(lhs), dtype=onp.int64),
len(lhs_batch_dims) + len(lhs_noncontract_dims),
(1,) * len(rhs_noncontract_dims))
new_rhs_shape = onp.insert(onp.array(onp.shape(rhs), dtype=onp.int64),
len(lhs_batch_dims),
(1,) * len(lhs_noncontract_dims))
lhs = reshape(lhs, new_lhs_shape)
rhs = reshape(rhs, new_rhs_shape)
out_ndim = (len(lhs_batch_dims) + len(lhs_noncontract_dims) +
len(rhs_noncontract_dims))
op_product = bitwise_and if lhs.dtype == onp.bool_ else mul
op_sum = bitwise_or if lhs.dtype == onp.bool_ else add
return reduce(op_product(lhs, rhs), _zero(lhs), op_sum,
tuple(range(out_ndim, out_ndim + len(lhs_contract_dims))))
return dot_general_p.bind(lhs, rhs,
dimension_numbers=(contract_dims, batch_dims),
precision=_canonicalize_precision(precision))
def broadcast(operand, sizes):
"""Broadcasts an array, adding new major dimensions.
Wraps XLA's `Broadcast
<https://www.tensorflow.org/xla/operation_semantics#broadcast>`_
operator.
Args:
operand: an array
sizes: a sequence of integers, giving the sizes of new major dimensions
to add.
Returns:
An array containing the result.
"""
return broadcast_p.bind(operand, sizes=tuple(sizes))
def broadcast_in_dim(operand, shape, broadcast_dimensions):
if onp.ndim(operand) == len(shape) and not len(broadcast_dimensions):
return operand
if any(x < 0 or x >= len(shape) for x in broadcast_dimensions):
msg = ("broadcast dimensions must be >= 0 and < ndim(shape), got {} for "
"shape {}")
raise ValueError(msg.format(broadcast_dimensions, shape))
return broadcast_in_dim_p.bind(
operand, shape=tuple(shape),
broadcast_dimensions=tuple(broadcast_dimensions))
def reshape(operand, new_sizes, dimensions=None):
"""Wraps XLA's `Reshape
<https://www.tensorflow.org/xla/operation_semantics#reshape>`_
operator.
"""
new_sizes = _canonicalize_shape(new_sizes) # TODO
new_sizes = tuple(new_sizes)
same_shape = onp.shape(operand) == new_sizes
same_dims = dimensions is None or tuple(dimensions) == tuple(range(onp.ndim(operand)))
if onp.shape(operand) and same_shape and same_dims:
return operand
else:
return reshape_p.bind(
operand, new_sizes=new_sizes,
dimensions=None if same_dims else tuple(dimensions),
old_sizes=onp.shape(operand))
def pad(operand, padding_value, padding_config):
"""Wraps XLA's `Pad
<https://www.tensorflow.org/xla/operation_semantics#pad>`_
operator.
"""
return pad_p.bind(operand, padding_value, padding_config=tuple(padding_config))
def rev(operand, dimensions):
"""Wraps XLA's `Rev
<https://www.tensorflow.org/xla/operation_semantics#rev_reverse>`_
operator.
"""
return rev_p.bind(operand, dimensions=tuple(dimensions))
def select(pred, on_true, on_false):
"""Wraps XLA's `Select
<https://www.tensorflow.org/xla/operation_semantics#select>`_
operator.
"""
return select_p.bind(pred, on_true, on_false)
def slice(operand, start_indices, limit_indices, strides=None):
"""Wraps XLA's `Slice
<https://www.tensorflow.org/xla/operation_semantics#slice>`_
operator.
"""
if (onp.all(onp.equal(start_indices, 0))
and onp.all(onp.equal(limit_indices, operand.shape))
and strides is None):
return operand
else:
return slice_p.bind(operand, start_indices=tuple(start_indices),
limit_indices=tuple(limit_indices),
strides=None if strides is None else tuple(strides),
operand_shape=operand.shape)
def dynamic_slice(operand, start_indices, slice_sizes):
"""Wraps XLA's `DynamicSlice
<https://www.tensorflow.org/xla/operation_semantics#dynamicslice>`_
operator.
Args:
operand: an array to slice.
start_indices: a list of scalar indices, one per dimension.
slice_sizes: the size of the slice. Must be a sequence of non-negative
integers with length equal to `ndim(operand)`.
Returns:
An array containing the slice.
"""
start_indices = _dynamic_slice_indices(operand, start_indices)
return dynamic_slice_p.bind(
operand, *start_indices, slice_sizes=tuple(slice_sizes),
operand_shape=operand.shape)
def dynamic_update_slice(operand, update, start_indices):
"""Wraps XLA's `DynamicUpdateSlice
<https://www.tensorflow.org/xla/operation_semantics#dynamicupdateslice>`_
operator.
Args:
operand: an array to slice.
update: an array containing the new values to write onto `operand`.
start_indices: a list of scalar indices, one per dimension.
Returns:
An array containing the slice.
"""
start_indices = _dynamic_slice_indices(operand, start_indices)
return dynamic_update_slice_p.bind(operand, update, *start_indices,
update_shape=update.shape)
def gather(operand, start_indices, dimension_numbers, slice_sizes):
"""Gather operator.
Wraps `XLA's Gather operator
<https://www.tensorflow.org/xla/operation_semantics#gather>`_.
The semantics of gather are complicated, and its API might change in the
future. For most use cases, you should prefer `Numpy-style indexing
<https://docs.scipy.org/doc/numpy-1.16.0/reference/arrays.indexing.html>`_
(e.g., `x[:, (1,4,7), ...]`), rather than using `gather` directly.
Args:
operand: an array from which slices should be taken
start_indices: the indices at which slices should be taken
dimension_numbers: a `lax.GatherDimensionNumbers` object that describes
how dimensions of `operand`, `start_indices` and the output relate.
slice_sizes: the size of each slice. Must be a sequence of non-negative
integers with length equal to `ndim(operand)`.
Returns:
An array containing the gather output.
"""
return gather_p.bind(
operand, start_indices, dimension_numbers=dimension_numbers,
slice_sizes=_canonicalize_shape(slice_sizes), operand_shape=operand.shape)
def scatter_add(operand, scatter_indices, updates, dimension_numbers):
"""Scatter-add operator.
Wraps `XLA's Scatter operator
<https://www.tensorflow.org/xla/operation_semantics#scatter>`_, where
addition is used to combine updates and values from `operand`.
The semantics of scatter are complicated and its API is subject to change.
Args:
operand: an array to which the scatter should be applied
scatter_indices: an array that gives the indices in `operand` to which each
update in `updates` should be applied.
updates: the updates that should be scattered onto `operand`.
dimension_numbers: a `lax.ScatterDimensionNumbers` object that describes
how dimensions of `operand`, `start_indices`, `updates` and the output
relate.
Returns:
An array containing the sum of `operand` and the scattered updates.
"""
jaxpr, consts = _reduction_jaxpr(add, _abstractify(_const(operand, 0)))
return scatter_add_p.bind(
operand, scatter_indices, updates, update_jaxpr=jaxpr,
update_consts=consts, dimension_numbers=dimension_numbers,
updates_shape=updates.shape)
def scatter_min(operand, scatter_indices, updates, dimension_numbers):
"""Scatter-min operator.
Wraps `XLA's Scatter operator
<https://www.tensorflow.org/xla/operation_semantics#scatter>`_, where
the `min` function is used to combine updates and values from `operand`.
The semantics of scatter are complicated and its API is subject to change.
Args:
operand: an array to which the scatter should be applied
scatter_indices: an array that gives the indices in `operand` to which each
update in `updates` should be applied.
updates: the updates that should be scattered onto `operand`.
dimension_numbers: a `lax.ScatterDimensionNumbers` object that describes
how dimensions of `operand`, `start_indices`, `updates` and the output
relate.
Returns:
An array containing the sum of `operand` and the scattered updates.
"""
jaxpr, consts = _reduction_jaxpr(min, _abstractify(_const(operand, 0)))
return scatter_min_p.bind(
operand, scatter_indices, updates, update_jaxpr=jaxpr,
update_consts=consts, dimension_numbers=dimension_numbers,
updates_shape=updates.shape)
def scatter_max(operand, scatter_indices, updates, dimension_numbers):
"""Scatter-max operator.
Wraps `XLA's Scatter operator
<https://www.tensorflow.org/xla/operation_semantics#scatter>`_, where
the `max` function is used to combine updates and values from `operand`.
The semantics of scatter are complicated and its API is subject to change.
Args:
operand: an array to which the scatter should be applied
scatter_indices: an array that gives the indices in `operand` to which each
update in `updates` should be applied.
updates: the updates that should be scattered onto `operand`.
dimension_numbers: a `lax.ScatterDimensionNumbers` object that describes
how dimensions of `operand`, `start_indices`, `updates` and the output
relate.
Returns:
An array containing the sum of `operand` and the scattered updates.
"""
jaxpr, consts = _reduction_jaxpr(max, _abstractify(_const(operand, 0)))
return scatter_max_p.bind(
operand, scatter_indices, updates, update_jaxpr=jaxpr,
update_consts=consts, dimension_numbers=dimension_numbers,
updates_shape=updates.shape)
# Define this outside of scatter to ensure cache hits.
_scatter_reduction_computation = lambda x, y: y
def scatter(operand, scatter_indices, updates, dimension_numbers):
"""Scatter-update operator.
Wraps `XLA's Scatter operator
<https://www.tensorflow.org/xla/operation_semantics#scatter>`_, where updates
replace values from `operand`.
If multiple updates are performed to the same index of operand, they may be
applied in any order.
The semantics of scatter are complicated and its API is subject to change.
Args:
operand: an array to which the scatter should be applied
scatter_indices: an array that gives the indices in `operand` to which each
update in `updates` should be applied.
updates: the updates that should be scattered onto `operand`.
dimension_numbers: a `lax.ScatterDimensionNumbers` object that describes
how dimensions of `operand`, `start_indices`, `updates` and the output
relate.
Returns:
An array containing the sum of `operand` and the scattered updates.
"""
jaxpr, consts = _reduction_jaxpr(_scatter_reduction_computation,
_abstractify(_const(operand, 0)))
return scatter_p.bind(
operand, scatter_indices, updates, update_jaxpr=jaxpr,
update_consts=consts, dimension_numbers=dimension_numbers,
updates_shape=updates.shape)
def index_take(src, idxs, axes):
indices = concatenate([reshape(i, [i.shape[0], 1]) for i in idxs], 1)
indices = indices % onp.array([src.shape[ax] for ax in axes])
slice_sizes = list(src.shape)
for ax in axes:
slice_sizes[ax] = 1
slice_sizes = tuple(slice_sizes)
offset_dims = tuple(range(1, src.ndim - indices.shape[1] + 1))
dnums = GatherDimensionNumbers(
offset_dims=offset_dims,
collapsed_slice_dims=axes,
start_index_map=axes)
return gather(src, indices, dimension_numbers=dnums, slice_sizes=slice_sizes)
def transpose(operand, permutation):
"""Wraps XLA's `Transpose
<https://www.tensorflow.org/xla/operation_semantics#transpose>`_
operator.
"""
permutation = tuple(permutation)
if permutation == tuple(range(len(permutation))):
return operand
else:
return transpose_p.bind(operand, permutation=permutation)
def reduce(operand, init_value, computation, dimensions):
"""Wraps XLA's `Reduce
<https://www.tensorflow.org/xla/operation_semantics#reduce>`_
operator.
"""
monoid_reducer = _get_monoid_reducer(computation, init_value)
if monoid_reducer:
return monoid_reducer(operand, dimensions)
else:
jaxpr, consts = _reduction_jaxpr(computation, _abstractify(init_value))
return reduce_p.bind(operand, init_value, computation=computation,
jaxpr=jaxpr, consts=consts, dimensions=tuple(dimensions))
@cache()
def _reduction_jaxpr(computation, aval):
pval = pe.PartialVal((aval, core.unit))
comp = lu.wrap_init(lambda x, y: (computation(x, y),))
jaxpr, _, consts = pe.trace_to_jaxpr(comp, (pval, pval), instantiate=False)
return jaxpr, consts
def _get_monoid_reducer(monoid_op, x):
aval = core.get_aval(x)
dtype = _dtype(x)
if (type(aval) is ConcreteArray) and aval.shape == ():
if monoid_op is add:
return aval.val == 0 and _reduce_sum
if monoid_op is mul:
return aval.val == 1 and _reduce_prod
elif monoid_op is bitwise_or and dtype == onp.bool_:
return aval.val == _get_max_identity(dtype) and _reduce_or
elif monoid_op is bitwise_and and dtype == onp.bool_:
return aval.val == _get_min_identity(dtype) and _reduce_and
elif monoid_op is max:
return aval.val == _get_max_identity(dtype) and _reduce_max
elif monoid_op is min:
return aval.val == _get_min_identity(dtype) and _reduce_min
def _get_max_identity(dtype):
if dtypes.issubdtype(dtype, onp.inexact):
return onp.array(-onp.inf, dtype)
elif dtypes.issubdtype(dtype, onp.integer):
return onp.array(dtypes.iinfo(dtype).min, dtype)
elif dtypes.issubdtype(dtype, onp.bool_):
return onp.array(False, onp.bool_)
def _get_min_identity(dtype):
if dtypes.issubdtype(dtype, onp.inexact):
return onp.array(onp.inf, dtype)
elif dtypes.issubdtype(dtype, onp.integer):
return onp.array(dtypes.iinfo(dtype).max, dtype)
elif dtypes.issubdtype(dtype, onp.bool_):
return onp.array(True, onp.bool_)
def _reduce_sum(operand, axes):
return reduce_sum_p.bind(operand, axes=tuple(axes),
input_shape=onp.shape(operand))
def _reduce_prod(operand, axes):
return reduce_prod_p.bind(operand, axes=tuple(axes))
def _reduce_max(operand, axes):
return reduce_max_p.bind(operand, axes=tuple(axes))
def _reduce_min(operand, axes):
return reduce_min_p.bind(operand, axes=tuple(axes))
def _reduce_or(operand, axes):
return reduce_or_p.bind(operand, axes=tuple(axes))
def _reduce_and(operand, axes):
return reduce_and_p.bind(operand, axes=tuple(axes))
def reduce_window(operand, init_value, computation, window_dimensions,
window_strides, padding):
"""Wraps XLA's `ReduceWindow
<https://www.tensorflow.org/xla/operation_semantics#reducewindow>`_
operator.
"""
monoid_reducer = _get_monoid_window_reducer(computation, init_value)
if monoid_reducer:
return monoid_reducer(operand, window_dimensions, window_strides, padding)
else:
jaxpr, consts = _reduction_jaxpr(computation, _abstractify(init_value))
return reduce_window_p.bind(
operand, init_value, jaxpr=jaxpr, consts=consts,
window_dimensions=tuple(window_dimensions),
window_strides=tuple(window_strides), padding=padding)
def _get_monoid_window_reducer(monoid_op, x):
aval = core.get_aval(x)
if (type(aval) is ConcreteArray) and aval.shape == ():
if monoid_op is add:
return aval.val == 0 and _reduce_window_sum
elif monoid_op is max:
return aval.val == _get_max_identity(aval.dtype) and _reduce_window_max
elif monoid_op is min:
return aval.val == _get_min_identity(aval.dtype) and _reduce_window_min
def _reduce_window_sum(operand, window_dimensions, window_strides, padding):
return reduce_window_sum_p.bind(
operand, window_dimensions=tuple(window_dimensions),
window_strides=tuple(window_strides), padding=padding,
input_shape=operand.shape)
def _reduce_window_prod(operand, window_dimensions, window_strides, padding):
init_value = _const(operand, 1)
jaxpr, consts = _reduction_jaxpr(mul, _abstractify(init_value))
return reduce_window_p.bind(
operand, init_value, jaxpr=jaxpr, consts=consts,
window_dimensions=tuple(window_dimensions),
window_strides=tuple(window_strides), padding=padding)
def _reduce_window_max(operand, window_dimensions, window_strides, padding):
return reduce_window_max_p.bind(
operand, window_dimensions=tuple(window_dimensions),
window_strides=tuple(window_strides), padding=padding)
def _reduce_window_min(operand, window_dimensions, window_strides, padding):
return reduce_window_min_p.bind(
operand, window_dimensions=tuple(window_dimensions),
window_strides=tuple(window_strides), padding=padding)
def _select_and_scatter(operand, select, window_dimensions, window_strides,
padding, source, init_value, scatter):
select_jaxpr, select_consts = _reduction_jaxpr(select, _abstractify(init_value))
scatter_jaxpr, scatter_consts = _reduction_jaxpr(scatter, _abstractify(init_value))
return select_and_scatter_p.bind(
operand, source, init_value, select_jaxpr=select_jaxpr,
select_consts=select_consts, scatter_jaxpr=scatter_jaxpr,
scatter_consts=scatter_consts, window_dimensions=tuple(window_dimensions),
window_strides=tuple(window_strides), padding=padding)
def _select_and_scatter_add(source, operand, select_prim, window_dimensions,
window_strides, padding):
return select_and_scatter_add_p.bind(
source, operand, select_prim=select_prim,
window_dimensions=tuple(window_dimensions),
window_strides=tuple(window_strides), padding=padding)
def _select_and_gather_add(tangents, operand, select_prim, window_dimensions,
window_strides, padding):
return select_and_gather_add_p.bind(
tangents, operand, select_prim=select_prim,
window_dimensions=tuple(window_dimensions),
window_strides=tuple(window_strides), padding=padding)
def sort(operand, dimension=-1):
"""Wraps XLA's `Sort
<https://www.tensorflow.org/xla/operation_semantics#sort>`_
operator.
"""
return sort_p.bind(operand, dimension=dimension)
def sort_key_val(keys, values, dimension=-1):
# TODO(mattjj): new sort_key_val is variadic
result = sort_key_val_p.bind(keys, values, dimension=dimension)
sorted_keys, sorted_values = result
return sorted_keys, sorted_values
def tie_in(x, y):
return tie_in_p.bind(x, y)
def full(shape, fill_value, dtype=None):
"""Returns an array of `shape` filled with `fill_value`.
Arguments:
shape: sequence of integers, describing the shape of the output array
fill_value: the value to fill the new array with
dtype: the type of the output array, or `None`. If not `None`, `fill_value`
will be cast to `dtype`.
"""
try:
shape = _canonicalize_shape(shape)
except TypeError as e:
msg = ("Note: `full` requires shapes to be concrete. If using `jit`, try "
"using `static_argnums` or applying `jit` to smaller subfunctions.")
raise TypeError("{}. {}".format(e.message, msg))
if onp.shape(fill_value):
msg = "full must be called with scalar fill_value, got fill_value.shape {}."
raise TypeError(msg.format(onp.shape(fill_value)))
dtype = dtype or _dtype(fill_value)
dtype = dtypes.canonicalize_dtype(dtype)
# For constants (defined as Python scalars, raw ndarrays, or DeviceValues),
# create a _FilledConstant value, otherwise just call broadcast.
if onp.isscalar(fill_value) or type(fill_value) is onp.ndarray:
return _FilledConstant(onp.asarray(fill_value, dtype), shape)
elif isinstance(fill_value, xla.DeviceValue):
val = onp.asarray(fill_value, dtype)
return _FilledConstant(val, shape)
else:
return broadcast(convert_element_type(fill_value, dtype), shape)
def iota(dtype, size):
"""Wraps XLA's `Iota
<https://www.tensorflow.org/xla/operation_semantics#iota>`_
operator.
"""
return broadcasted_iota(dtype, (int(size),), 0)
def broadcasted_iota(dtype, shape, dimension):
"""Wraps XLA's `Iota
<https://www.tensorflow.org/xla/operation_semantics#iota>`_
operator.
"""
dtype = dtypes.canonicalize_dtype(dtype)
shape = _canonicalize_shape(shape)
dimension = int(dimension)
return _IotaConstant(dtype, shape, dimension)
def eye(dtype, size):
return broadcasted_eye(dtype, (size, size), (0, 1))
def broadcasted_eye(dtype, shape, axes):
if not isinstance(axes, (list, tuple)) or not len(axes) >= 2:
raise TypeError("make_diagonal `axes` must be a tuple with len at least 2.")
dtype = dtypes.canonicalize_dtype(dtype)
shape = _canonicalize_shape(shape)
axes = tuple(map(int, axes))
return _EyeConstant(shape, axes, dtype)
def stop_gradient(x):
"""Stops gradient computation.
Operationally `stop_gradient` is the identity function, that is, it returns
argument `x` unchanged. However, `stop_gradient` prevents the flow of
gradients during forward or reverse-mode automatic differentiation. If there
are multiple nested gradient computations, `stop_gradient` stops gradients
for all of them.
For example:
>>> jax.grad(lambda x: x**2)(3.)
array(6., dtype=float32)
>>> jax.grad(lambda x: jax.lax.stop_gradient(x)**2)(3.)
array(0., dtype=float32)
>>> jax.grad(jax.grad(lambda x: x**2))(3.)
array(2., dtype=float32)
>>> jax.grad(jax.grad(lambda x: jax.lax.stop_gradient(x)**2))(3.)
array(0., dtype=float32)
"""
return tree_map(stop_gradient_p.bind, x)
def _safe_mul(x, y): return safe_mul_p.bind(x, y)
### convenience wrappers around traceables
def conv(lhs, rhs, window_strides, padding, precision=None):
"""Convenience wrapper around `conv_general_dilated`.
Args:
lhs: a rank `n+2` dimensional input array.
rhs: a rank `n+2` dimensional array of kernel weights.
window_strides: a sequence of `n` integers, representing the inter-window
strides.
padding: either the string `'SAME'`, the string `'VALID'`.
precision: Optional. Either `None`, which means the default precision for
the backend, or a `Precision` enum value.
Returns:
An array containing the convolution result.
"""
pads = padtype_to_pads(lhs.shape[2:], rhs.shape[2:], window_strides, padding)
return conv_general_dilated(lhs, rhs, window_strides, padding,
precision=precision)
def conv_with_general_padding(lhs, rhs, window_strides, padding,
lhs_dilation, rhs_dilation, precision=None):
"""Convenience wrapper around `conv_general_dilated`.
Args:
lhs: a rank `n+2` dimensional input array.
rhs: a rank `n+2` dimensional array of kernel weights.
window_strides: a sequence of `n` integers, representing the inter-window
strides.
padding: either the string `'SAME'`, the string `'VALID'`, or a sequence of
`n` `(low, high)` integer pairs that give the padding to apply before and
after each spatial dimension.
lhs_dilation: `None`, or a sequence of `n` integers, giving the
dilation factor to apply in each spatial dimension of `lhs`. LHS dilation
is also known as transposed convolution.
rhs_dilation: `None`, or a sequence of `n` integers, giving the
dilation factor to apply in each spatial dimension of `rhs`. RHS dilation
is also known as atrous convolution.
precision: Optional. Either `None`, which means the default precision for
the backend, or a `Precision` enum value.
Returns:
An array containing the convolution result.
"""
return conv_general_dilated(
lhs, rhs, window_strides, padding, lhs_dilation=lhs_dilation,
rhs_dilation=rhs_dilation, precision=precision)
def _conv_transpose_padding(k, s, padding):
"""Calculate before and after padding for a dim of transposed convolution.
Args:
k: int: kernel dimension.
s: int: dimension stride value.
padding: 'same' or 'valid' padding mode for original forward conv.
Returns:
2-tuple: ints: before and after padding for transposed convolution.
"""
if padding == 'SAME':
pad_len = k + s - 2
if s > k - 1:
pad_a = k - 1
else:
pad_a = int(onp.ceil(pad_len / 2))
elif padding == 'VALID':
pad_len = k + s - 2 + _max(k - s, 0)
pad_a = k - 1
else:
raise ValueError('Padding mode must be `SAME` or `VALID`.')
pad_b = pad_len - pad_a
return pad_a, pad_b
def _flip_axes(x, axes):
"""Flip ndarray 'x' along each axis specified in axes tuple."""
for axis in axes:
x = onp.flip(x, axis)
return x
def conv_transpose(lhs, rhs, strides, padding, rhs_dilation=None,
dimension_numbers=None, transpose_kernel=False, precision=None):
"""Convenience wrapper for calculating the N-d convolution "transpose".
This function directly calculates a fractionally strided conv rather than
indirectly calculating the gradient (transpose) of a forward convolution.
Args:
lhs: a rank `n+2` dimensional input array.
rhs: a rank `n+2` dimensional array of kernel weights.
strides: sequence of `n` integers, sets fractional stride.
padding: 'SAME', 'VALID' will set as transpose of corresponding forward
conv, or a sequence of `n` integer 2-tuples describing before-and-after
padding for each `n` spatial dimension.
rhs_dilation: `None`, or a sequence of `n` integers, giving the
dilation factor to apply in each spatial dimension of `rhs`. RHS dilation
is also known as atrous convolution.
dimension_numbers: tuple of dimension descriptors as in
lax.conv_general_dilated. Defaults to tensorflow convention.
transpose_kernel: if True flips spatial axes and swaps the input/output
channel axes of the kernel. This makes the output of this function identical
to the gradient-derived functions like keras.layers.Conv2DTranspose
applied to the same kernel. For typical use in neural nets this is completely
pointless and just makes input/output channel specification confusing.
precision: Optional. Either `None`, which means the default precision for
the backend, or a `Precision` enum value.
Returns:
Transposed N-d convolution, with output padding following the conventions of
keras.layers.Conv2DTranspose.
"""
assert len(lhs.shape) == len(rhs.shape) and len(lhs.shape) > 2
ndims = len(lhs.shape)
one = (1,) * (ndims - 2)
# Set dimensional layout defaults if not specified.
if dimension_numbers is None:
if ndims == 3:
dimension_numbers = ('NHC', 'HIO', 'NHC')
elif ndims == 4:
dimension_numbers = ('NHWC', 'HWIO', 'NHWC')
elif ndims == 5:
dimension_numbers = ('NHWDC', 'HWDIO', 'NHWDC')
else:
raise ValueError('No 4+ dimensional dimension_number defaults.')
dn = conv_dimension_numbers(lhs.shape, rhs.shape, dimension_numbers)
k_shape = onp.take(rhs.shape, dn.rhs_spec)
k_sdims = k_shape[2:]
# Calculate correct output shape given padding and strides.
if padding in {'SAME', 'VALID'}:
if rhs_dilation is None:
rhs_dilation = (1,) * (rhs.ndim - 2)
effective_k_size = map(lambda k, r: (k-1) * r + 1, k_sdims, rhs_dilation)
pads = [_conv_transpose_padding(k, s, padding)
for k,s in zip(effective_k_size, strides)]
else:
pads = padding
if transpose_kernel:
# flip spatial dims and swap input / output channel axes
rhs = _flip_axes(rhs, onp.array(dn.rhs_spec)[2:])
rhs = onp.swapaxes(rhs, dn.rhs_spec[0], dn.rhs_spec[1])
return conv_general_dilated(lhs, rhs, one, pads, strides, rhs_dilation, dn,
precision=precision)
def full_like(x, fill_value, dtype=None, shape=None):
"""Create a full array like np.full based on the example array `x`.
Args:
x: example array-like, used for shape and dtype information.
fill_value: a scalar value to fill the entries of the output array.
dtype: optional, a dtype parameter for the output ndarray.
shape: optional, a shape parameter for the output ndarray.
Returns:
An ndarray with the same shape as `x` with its entries set equal to
`fill_value`, similar to the output of np.full.
"""
shape = onp.shape(x) if shape is None else _canonicalize_shape(shape)
fill_value = tie_in(x, fill_value)
return full(shape, fill_value, dtype or _dtype(x))
def collapse(operand, start_dimension, stop_dimension):
lo, hi = start_dimension, stop_dimension
size = prod(operand.shape[lo:hi])
new_shape = operand.shape[:lo] + (size,) + operand.shape[hi:]
return reshape(operand, new_shape)
def slice_in_dim(operand, start_index, limit_index, stride=1, axis=0):
"""Convenience wrapper around slice applying to only one dimension."""
start_indices = [0] * operand.ndim
limit_indices = list(operand.shape)
strides = [1] * operand.ndim
axis = int(axis)
start_indices[axis] = int(start_index)
limit_indices[axis] = int(limit_index)
strides[axis] = int(stride)
return slice(operand, start_indices, limit_indices, strides)
def index_in_dim(operand, index, axis=0, keepdims=True):
"""Convenience wrapper around slice to perform int indexing."""
index, axis = int(index), int(axis)
axis_size = operand.shape[axis]
wrapped_index = index + axis_size if index < 0 else index
if not 0 <= wrapped_index < axis_size:
msg = 'index {} is out of bounds for axis {} with size {}'
raise IndexError(msg.format(index, axis, axis_size))
result = slice_in_dim(operand, wrapped_index, wrapped_index + 1, 1, axis)
if keepdims:
return result
else:
return reshape(result, onp.delete(operand.shape, axis))
def dynamic_slice_in_dim(operand, start_index, slice_size, axis=0):
"""Convenience wrapper around dynamic_slice applying to one dimension."""
start_indices = [_zero(start_index)] * operand.ndim
slice_sizes = list(operand.shape)
axis = int(axis)
start_indices[axis] = start_index
slice_sizes[axis] = int(slice_size)
return dynamic_slice(operand, start_indices, slice_sizes)
def dynamic_index_in_dim(operand, index, axis=0, keepdims=True):
"""Convenience wrapper around dynamic_slice to perform int indexing."""
result = dynamic_slice_in_dim(operand, index, 1, axis)
if keepdims:
return result
else:
return reshape(result, onp.delete(operand.shape, axis))
def dynamic_update_slice_in_dim(operand, update, start_index, axis):
axis = int(axis)
start_indices = [_zero(start_index)] * _ndim(operand)
start_indices[axis] = start_index
return dynamic_update_slice(operand, update, start_indices)
def dynamic_update_index_in_dim(operand, update, index, axis):
axis = int(axis)
if _ndim(update) != _ndim(operand):
assert _ndim(update) + 1 == _ndim(operand)
ax = axis % _ndim(operand)
update = reshape(update, operand.shape[:ax] + (1,) + operand.shape[ax+1:])
return dynamic_update_slice_in_dim(operand, update, index, axis)
def batch_matmul(lhs, rhs, precision=None):
"""Batch matrix multiplication."""
if _min(lhs.ndim, rhs.ndim) < 2:
raise ValueError('Arguments to batch_matmul must be at least 2D, got {}, {}'
.format(lhs.ndim, rhs.ndim))
if lhs.ndim != rhs.ndim:
raise ValueError('Arguments to batch_matmul must have same ndim, got {}, {}'
.format(lhs.ndim, rhs.ndim))
lhs_contract = (lhs.ndim - 1,)
rhs_contract = (rhs.ndim - 2,)
batch = tuple(range(lhs.ndim - 2))
return dot_general(lhs, rhs, [(lhs_contract, rhs_contract), (batch, batch)],
precision=precision)
# These functions also exist in the XLA client library, but we treat them
# as non-primitive to maintain a smaller set of autodiff primitives.
def square(x):
r"""Elementwise square: :math:`x^2`."""
return mul(x, x)
def reciprocal(x):
r"""Elementwise reciprocal: :math:`1 \over x`."""
return div(_const(x, 1), x)
def _upcast_fp16_for_computation(f):
@functools.wraps(f)
def f_wrapped(x):
dtype = _dtype(x)
if dtype == onp.float16 or dtype == dtypes.bfloat16:
return convert_element_type(
f(convert_element_type(x, onp.float32)), dtype)
return f(x)
return f_wrapped
@api.jit
@_upcast_fp16_for_computation
def tan(x):
r"""Elementwise tangent: :math:`\mathrm{tan}(x)`."""
return div(sin(x), cos(x))
@api.jit
def asin(x):
r"""Elementwise arc sine: :math:`\mathrm{asin}(x)`."""
return mul(_const(x, 2),
atan2(x, add(_const(x, 1), sqrt(sub(_const(x, 1), square(x))))))
@api.jit
def acos(x):
r"""Elementwise arc cosine: :math:`\mathrm{acos}(x)`."""
return select(
ne(x, _const(x, -1.0)),
mul(_const(x, 2),
atan2(sqrt(sub(_const(x, 1), square(x))), add(_const(x, 1), x))),
full_like(x, onp.pi))
def atan(x):
r"""Elementwise arc tangent: :math:`\mathrm{atan}(x)`."""
return atan2(x, _const(x, 1))
@api.jit
@_upcast_fp16_for_computation
def sinh(x):
r"""Elementwise hyperbolic sine: :math:`\mathrm{sinh}(x)`."""
log_half = _const(x, onp.log(0.5))
# This formulation avoids overflow when e^x is inf but e^x/2 is not inf.
return sub(exp(add(log_half, x)), exp(sub(log_half, x)))
@api.jit
@_upcast_fp16_for_computation
def cosh(x):
r"""Elementwise hyperbolic cosine: :math:`\mathrm{cosh}(x)`."""
log_half = _const(x, onp.log(0.5))
# This formulation avoids overflow when e^x is inf but e^x/2 is not inf.
return add(exp(add(log_half, x)), exp(sub(log_half, x)))
# Add some methods to ShapedArray that rely on lax primitives
ShapedArray.broadcast = core.aval_method(broadcast)
ShapedArray.transpose = core.aval_method(transpose) # clobbered by lax_numpy
ShapedArray.reshape = core.aval_method(reshape) # clobbered by lax_numpy
def _iter(tracer):
if tracer.ndim == 0:
raise TypeError("iteration over a 0-d array") # same as numpy error
else:
n = tracer.shape[0]
# return (index_in_dim(tracer, i, keepdims=False) for i in xrange(n))
return iter([index_in_dim(tracer, i, keepdims=False) for i in xrange(n)])
ShapedArray._iter = staticmethod(_iter)
# Add some ad handlers that use (or could use) lax primitives
def zeros_like_array(x):
return full_like(x, 0)
for t in itertools.chain(dtypes.python_scalar_dtypes.keys(), array_types,
[xla.DeviceArray]):
ad_util.jaxval_adders[t] = add
ad_util.jaxval_zeros_likers[xla.DeviceArray] = zeros_like_array
### primitives
_input_dtype = lambda *args, **_: dtypes.canonicalize_dtype(args[0].dtype)
_fixed_dtype = lambda dtype: lambda *args, **kwargs: dtypes.canonicalize_dtype(dtype)
_complex_basetype = lambda dtype: onp.abs(onp.zeros((), dtype)).dtype
def standard_primitive(shape_rule, dtype_rule, name, translation_rule=None):
prim = Primitive(name)
prim.def_impl(partial(xla.apply_primitive, prim))
prim.def_abstract_eval(partial(standard_abstract_eval, prim, shape_rule, dtype_rule))
xla.translations[prim] = translation_rule or partial(standard_translate, name)
return prim
def standard_abstract_eval(prim, shape_rule, dtype_rule, *args, **kwargs):
assert all(isinstance(arg, UnshapedArray) for arg in args), args
least_specialized = _max(
map(type, args), key=operator.attrgetter('array_abstraction_level'))
if least_specialized is ConcreteArray:
msg = ("If you see this error, please let us know by opening an issue at\n"
"https://github.com/google/jax/issues \n"
"since we thought this was unreachable!")
assert pe._thread_local_state.remat, msg
return ConcreteArray(prim.impl(*[x.val for x in args], **kwargs))
elif least_specialized is ShapedArray:
return ShapedArray(shape_rule(*args, **kwargs), dtype_rule(*args, **kwargs))
elif least_specialized is UnshapedArray:
return UnshapedArray(dtype_rule(*args, **kwargs))
else:
raise TypeError(args, least_specialized)
def standard_translate(name, c, *args, **kwargs):
xla_opname = ''.join(term.capitalize() for term in name.split('_'))
return getattr(c, xla_opname)(*args, **kwargs)
def unop_dtype_rule(result_dtype, accepted_dtypes, name, aval, **kwargs):
if not any(dtypes.issubdtype(aval.dtype, t) for t in accepted_dtypes):
msg = '{} does not accept dtype {}. Accepted dtypes are subtypes of {}.'
typename = str(onp.dtype(aval.dtype).name)
accepted_typenames = (t.__name__ for t in accepted_dtypes)
raise TypeError(msg.format(name, typename, ', '.join(accepted_typenames)))
return result_dtype(aval.dtype)
def unop(result_dtype, accepted_dtypes, name):
dtype_rule = partial(unop_dtype_rule, result_dtype, accepted_dtypes, name)
prim = standard_primitive(_attrgetter('shape'), dtype_rule, name)
batching.defvectorized(prim)
masking.defvectorized(prim)
return prim
standard_unop = partial(unop, _identity)
_attrgetter = lambda name: lambda x, **kwargs: getattr(x, name)
def binop_dtype_rule(result_dtype, accepted_dtypes, name, *avals, **kwargs):
aval_dtypes = [aval.dtype for aval in avals]
for i, (aval_dtype, types) in enumerate(zip(aval_dtypes, accepted_dtypes)):
if not any(dtypes.issubdtype(aval_dtype, t) for t in types):
msg = ('{} does not accept dtype {} at position {}. '
'Accepted dtypes at position {} are subtypes of {}.')
typename = str(onp.dtype(aval_dtype).name)
typenames = ', '.join(t.__name__ for t in types)
raise TypeError(msg.format(name, typename, i, i, typenames))
_check_same_dtypes(name, False, *aval_dtypes)
return result_dtype(*avals)
def _broadcasting_shape_rule(name, *avals):
shapes = onp.array([aval.shape for aval in avals if aval.shape])
if not shapes.size:
return ()
if len({len(shape) for shape in shapes}) != 1:
msg = '{} got arrays of different rank: {}.'
raise TypeError(msg.format(name, ', '.join(map(str, map(tuple, shapes)))))
min_shape = onp.min(shapes, axis=0)
max_shape = onp.max(shapes, axis=0)
result_shape = onp.where(min_shape == 0, 0, max_shape)
if not onp.all((shapes == result_shape) | (shapes == 1)):
msg = '{} got incompatible shapes for broadcasting: {}.'
raise TypeError(msg.format(name, ', '.join(map(str, map(tuple, shapes)))))
return tuple(result_shape)
def binop(result_dtype, accepted_dtypes, name, translation_rule=None):
dtype_rule = partial(binop_dtype_rule, result_dtype, accepted_dtypes, name)
shape_rule = partial(_broadcasting_shape_rule, name)
prim = standard_primitive(shape_rule, dtype_rule, name,
translation_rule=translation_rule)
batching.defbroadcasting(prim)
masking.defbinop(prim)
return prim
standard_binop = partial(binop, _input_dtype)
# NOTE(mattjj): this isn't great for orchestrate fwd mode because it means JVPs
# get two extra ops in them: a reshape and a broadcast_in_dim (or sometimes just
# a broadcast). but saving the shape info with the primitives isn't great either
# because then we can't trace these ops without shape data.
def _brcast(x, *others):
# Used in jvprules to make binop broadcasting explicit for transposability.
# Requires shape info during jvp tracing, which isn't strictly necessary.
# We don't need full numpy broadcasting, but otherwise the logic is the same
# so we reuse the broadcast_shapes function after filtering out scalars.
shapes = tuple(filter(None, map(onp.shape, (x,) + others)))
shape = shapes and broadcast_shapes(*shapes)
if onp.shape(x) != shape:
return _brcast_to(x, shape)
else:
return x
def _brcast_to(x, shape):
x_shape = onp.shape(x)
assert x_shape != shape
if x_shape:
assert len(x_shape) == len(shape)
broadcast_dimensions, = onp.where(onp.equal(x_shape, shape))
squeezed_dimensions, = onp.where(onp.not_equal(x_shape, shape))
inshape = onp.delete(x_shape, squeezed_dimensions)
return broadcast_in_dim(reshape(x, inshape), shape, broadcast_dimensions)
else:
return broadcast(x, shape)
_float = {onp.floating}
_complex = {onp.complexfloating}
_complex_elem_types = {onp.float32, onp.float64}
_int = {onp.integer}
_bool = {onp.bool_}
_num = _int | _float | _complex
_any = _int | _float | _complex | _bool
neg_p = standard_unop(_num, 'neg')
ad.deflinear(neg_p, lambda t: [neg(t)])
sign_p = standard_unop(_num, 'sign')
ad.defjvp_zero(sign_p)
nextafter_p = standard_binop(
[_float, _float], 'nextafter',
translation_rule=lambda c, x1, x2: c.NextAfter(x1, x2))
floor_p = standard_unop(_float, 'floor')
ad.defjvp_zero(floor_p)
ceil_p = standard_unop(_float, 'ceil')
ad.defjvp_zero(ceil_p)
round_p = standard_unop(_float, 'round')
ad.defjvp_zero(round_p)
is_finite_p = unop(_fixed_dtype(onp.bool_), _float, 'is_finite')
ad.defjvp_zero(is_finite_p)
exp_p = standard_unop(_float | _complex, 'exp')
ad.defjvp2(exp_p, lambda g, ans, x: _safe_mul(g, ans))
log_p = standard_unop(_float | _complex, 'log')
ad.defjvp(log_p, lambda g, x: div(g, x))
expm1_p = standard_unop(_float | _complex, 'expm1')
ad.defjvp2(expm1_p, lambda g, ans, x: mul(g, add(ans, _one(ans))))
log1p_p = standard_unop(_float | _complex, 'log1p')
ad.defjvp(log1p_p, lambda g, x: div(g, add(x, _one(x))))
tanh_p = standard_unop(_float | _complex, 'tanh')
ad.defjvp2(tanh_p, lambda g, ans, x: mul(g, sub(_one(x), mul(ans, ans))))
sin_p = standard_unop(_float | _complex, 'sin')
ad.defjvp(sin_p, lambda g, x: mul(g, cos(x)))
cos_p = standard_unop(_float | _complex, 'cos')
ad.defjvp(cos_p, lambda g, x: neg(mul(g, sin(x))))
atan2_p = standard_binop([_float, _float], 'atan2')
ad.defjvp(atan2_p,
lambda g, x, y: _brcast(g, y) * (y / (square(x) + square(y))),
lambda g, x, y: _brcast(g, x) * -x / (square(x) + square(y)))
lgamma_p = standard_unop(_float, 'lgamma')
ad.defjvp(lgamma_p, lambda g, x: mul(g, digamma(x)))
digamma_p = standard_unop(_float, 'digamma')
bessel_i0e_p = standard_unop(_float, 'bessel_i0e')
ad.defjvp2(bessel_i0e_p, lambda g, y, x: g * (bessel_i1e(x) - sign(x) * y))
bessel_i1e_p = standard_unop(_float, 'bessel_i1e')
def _bessel_i1e_jvp(g, y, x):
eps = dtypes.finfo(_dtype(x)).eps
x_is_not_tiny = abs(x) > eps
safe_x = select(x_is_not_tiny, x, full_like(x, eps))
dy_dx = bessel_i0e(safe_x) - y * (sign(safe_x) + reciprocal(safe_x))
dy_dx = select(x_is_not_tiny, dy_dx, full_like(x, 0.5))
return g * dy_dx
ad.defjvp2(bessel_i1e_p, _bessel_i1e_jvp)
erf_p = standard_unop(_float, 'erf')
ad.defjvp(erf_p, lambda g, x: mul(_const(x, 2. / onp.sqrt(onp.pi)),
mul(g, exp(neg(square(x))))))
erfc_p = standard_unop(_float, 'erfc')
ad.defjvp(erfc_p, lambda g, x: mul(_const(x, 2. / onp.sqrt(onp.pi)),
mul(neg(g), exp(neg(square(x))))))
erf_inv_p = standard_unop(_float, 'erf_inv')
ad.defjvp2(erf_inv_p, lambda g, ans, x: mul(_const(x, onp.sqrt(onp.pi) / 2.),
mul(g, exp(square(ans)))))
real_p = unop(_complex_basetype, _complex, 'real')
ad.deflinear(real_p, lambda t: [complex(t, onp.zeros((), _dtype(t)))])
imag_p = unop(_complex_basetype, _complex, 'imag')
ad.defjvp(imag_p, lambda g, _: real(mul(_const(g, -1j), g)))
_complex_dtype = lambda dtype, *args: (onp.zeros((), dtype) + onp.zeros((), onp.complex64)).dtype
complex_p = binop(_complex_dtype, [_complex_elem_types, _complex_elem_types],
'complex')
ad.deflinear(complex_p, lambda t: [real(t), imag(neg(t))])
conj_p = unop(_complex_dtype, _complex_elem_types | _complex, 'conj')
def _conj_transpose_rule(t, x, input_dtype):
assert x is ad.undefined_primal
if dtypes.issubdtype(input_dtype, onp.complexfloating):
return [conj(t)]
else:
return [real(t)]
xla.translations[conj_p] = lambda c, x, **kwargs: c.Conj(x)
ad.primitive_jvps[conj_p] = partial(ad.linear_jvp, conj_p)
ad.primitive_transposes[conj_p] = _conj_transpose_rule
abs_p = unop(_complex_basetype, _num, 'abs')
def _abs_jvp_rule(g, ans, x):
if _iscomplex(x):
return _maybe_real(mul(g, div(_maybe_conj(x),
_replace_zero(convert_element_type(ans, _dtype(x))))))
else:
return select(ge(x, _zero(x)), g, neg(g))
ad.defjvp2(abs_p, _abs_jvp_rule)
_maybe_conj = lambda x: conj(x) if _iscomplex(x) else x
_maybe_real = lambda x: real(x) if _iscomplex(x) else x
sqrt_p = standard_unop(_float | _complex, 'sqrt')
ad.defjvp2(sqrt_p, lambda g, ans, x: _safe_mul(g, div(_const(x, 0.5), ans)))
rsqrt_p = standard_unop(_float | _complex, 'rsqrt')
ad.defjvp2(rsqrt_p,
lambda g, ans, x:
_safe_mul(g, mul(_const(x, -0.5), pow(x, _const(x, -1.5)))))
pow_p = standard_binop([_float | _complex, _float | _complex], 'pow')
def _pow_jvp_lhs(g, ans, x, y):
# we call _safe_mul here so that we get the behavior 0*inf = 0, since when a
# coefficient in `g` is zero we want to keep it at zero, not produce a nan.
# see https://github.com/google/jax/pull/383
jac = mul(y, pow(x, select(eq(y, _zeros(y)), _ones(y), sub(y, _ones(y)))))
return _safe_mul(_brcast(g, y), jac)
def _pow_jvp_rhs(g, ans, x, y):
return mul(_brcast(g, x), mul(log(_replace_zero(x)), ans))
ad.defjvp2(pow_p, _pow_jvp_lhs, _pow_jvp_rhs)
_replace_zero = lambda x: select(eq(x, _const(x, 0)), _ones(x), x)
not_p = standard_unop(_int | _bool, 'not')
and_p = standard_binop([_any, _any], 'and')
ad.defjvp_zero(and_p)
or_p = standard_binop([_any, _any], 'or')
ad.defjvp_zero(or_p)
xor_p = standard_binop([_any, _any], 'xor')
ad.defjvp_zero(xor_p)
def _add_transpose(t, x, y):
# assert x is ad.undefined_primal and y is ad.undefined_primal # not affine
return [t, t]
add_p = standard_binop([_num, _num], 'add')
ad.defjvp(add_p, lambda g, x, y: _brcast(g, y), lambda g, x, y: _brcast(g, x))
ad.primitive_transposes[add_p] = _add_transpose
def _sub_transpose(t, x, y):
assert x is ad.undefined_primal and y is ad.undefined_primal # not affine
return [t, neg(t) if t is not ad_util.zero else ad_util.zero]
sub_p = standard_binop([_num, _num], 'sub')
ad.defjvp(sub_p,
lambda g, x, y: _brcast(g, y),
lambda g, x, y: _brcast(neg(g), x))
ad.primitive_transposes[sub_p] = _sub_transpose
mul_p = standard_binop([_num, _num], 'mul')
ad.defbilinear_broadcasting(_brcast, mul_p, mul, mul)
def _safe_mul_translation_rule(c, x, y):
dtype = c.GetShape(x).numpy_dtype()
zero = c.Constant(onp.array(0, dtype=dtype))
out_shape = broadcast_shapes(c.GetShape(x).dimensions(),
c.GetShape(y).dimensions())
return c.Select(c.Or(c.Eq(x, zero), c.Eq(y, zero)),
c.Broadcast(zero, out_shape),
c.Mul(x, y))
safe_mul_p = standard_binop([_num, _num], 'safe_mul',
translation_rule=_safe_mul_translation_rule)
ad.defbilinear_broadcasting(_brcast, safe_mul_p, _safe_mul, _safe_mul)
def _div_transpose_rule(cotangent, x, y):
assert x is ad.undefined_primal and y is not ad.undefined_primal
res = ad_util.zero if cotangent is ad_util.zero else div(cotangent, y)
return res, None
div_p = standard_binop([_num, _num], 'div')
ad.defjvp(div_p,
lambda g, x, y: div(_brcast(g, y), y),
lambda g, x, y: div(mul(neg(_brcast(g, x)), x), square(y)))
ad.primitive_transposes[div_p] = _div_transpose_rule
rem_p = standard_binop([_num, _num], 'rem')
ad.defjvp(rem_p,
lambda g, x, y: _brcast(g, y),
lambda g, x, y: mul(_brcast(neg(g), x), floor(div(x, y))))
def _broadcasting_select(c, which, x, y):
"""Wrapper around XLA `Select` that broadcasts its arguments."""
which_shape, x_shape, y_shape = (
c.GetShape(t).dimensions() for t in (which, x, y))
out_shape = broadcast_shapes(which_shape, x_shape, y_shape)
bcast_dims = lambda shape: tuple(range(len(out_shape) - len(shape),
len(out_shape)))
which = c.BroadcastInDim(which, out_shape, bcast_dims(which_shape))
x = c.BroadcastInDim(x, out_shape, bcast_dims(x_shape))
y = c.BroadcastInDim(y, out_shape, bcast_dims(y_shape))
return c.Select(which, x, y)
def _minmax_translation_rule(c, x, y, minmax=None, cmp=None):
dtype = c.GetShape(x).numpy_dtype()
if dtypes.issubdtype(dtype, onp.complexfloating):
comparator = cmp(c)
rx = c.Real(x)
ry = c.Real(y)
return _broadcasting_select(
c, c.Select(c.Eq(rx, ry), comparator(c.Imag(x), c.Imag(y)),
comparator(rx, ry)),
x, y)
return minmax(c)(x, y)
max_p = standard_binop([_any, _any], 'max', translation_rule=partial(
_minmax_translation_rule, minmax=lambda c: c.Max, cmp=lambda c: c.Gt))
ad.defjvp2(max_p,
lambda g, ans, x, y: mul(_brcast(g, y), _balanced_eq(x, ans, y)),
lambda g, ans, x, y: mul(_brcast(g, x), _balanced_eq(y, ans, x)))
min_p = standard_binop([_any, _any], 'min', translation_rule=partial(
_minmax_translation_rule, minmax=lambda c: c.Min, cmp=lambda c: c.Lt))
ad.defjvp2(min_p,
lambda g, ans, x, y: mul(_brcast(g, y), _balanced_eq(x, ans, y)),
lambda g, ans, x, y: mul(_brcast(g, x), _balanced_eq(y, ans, x)))
shift_left_p = standard_binop([_int, _int], 'shift_left')
ad.defjvp_zero(shift_left_p)
shift_right_arithmetic_p = standard_binop([_int, _int], 'shift_right_arithmetic')
ad.defjvp_zero(shift_right_arithmetic_p)
shift_right_logical_p = standard_binop([_int, _int], 'shift_right_logical')
ad.defjvp_zero(shift_right_logical_p)
eq_p = binop(_fixed_dtype(onp.bool_), [_any, _any], 'eq')
ad.defjvp_zero(eq_p)
ne_p = binop(_fixed_dtype(onp.bool_), [_any, _any], 'ne')
ad.defjvp_zero(ne_p)
ge_p = binop(_fixed_dtype(onp.bool_), [_any, _any], 'ge')
ad.defjvp_zero(ge_p)
gt_p = binop(_fixed_dtype(onp.bool_), [_any, _any], 'gt')
ad.defjvp_zero(gt_p)
le_p = binop(_fixed_dtype(onp.bool_), [_any, _any], 'le')
ad.defjvp_zero(le_p)
lt_p = binop(_fixed_dtype(onp.bool_), [_any, _any], 'lt')
ad.defjvp_zero(lt_p)
def _convert_element_type_shape_rule(operand, new_dtype, old_dtype):
return operand.shape
def _convert_element_type_dtype_rule(operand, new_dtype, old_dtype):
return new_dtype
def _convert_element_type_translation_rule(c, operand, new_dtype, old_dtype):
new_etype = xla_client.dtype_to_etype(new_dtype)
return c.ConvertElementType(operand, new_element_type=new_etype)
convert_element_type_p = standard_primitive(
_convert_element_type_shape_rule, _convert_element_type_dtype_rule,
'convert_element_type', _convert_element_type_translation_rule)
ad.deflinear(
convert_element_type_p,
lambda t, new_dtype, old_dtype: [convert_element_type(t, old_dtype)])
batching.defvectorized(convert_element_type_p)
masking.defvectorized(convert_element_type_p)
def _bitcast_convert_type_shape_rule(operand, new_dtype):
return operand.shape
def _bitcast_convert_type_dtype_rule(operand, new_dtype):
return new_dtype
def _bitcast_convert_type_translation_rule(c, operand, new_dtype):
new_etype = xla_bridge.dtype_to_etype(new_dtype)
return c.BitcastConvertType(operand, new_element_type=new_etype)
bitcast_convert_type_p = standard_primitive(
_bitcast_convert_type_shape_rule, _bitcast_convert_type_dtype_rule,
'bitcast_convert_type', _bitcast_convert_type_translation_rule)
ad.defjvp_zero(bitcast_convert_type_p)
batching.defvectorized(bitcast_convert_type_p)
masking.defvectorized(bitcast_convert_type_p)
def _conv_general_dilated_shape_rule(
lhs, rhs, window_strides, padding, lhs_dilation, rhs_dilation,
dimension_numbers, feature_group_count, **unused_kwargs):
assert type(dimension_numbers) is ConvDimensionNumbers
if not feature_group_count > 0:
msg = ("conv_general_dilated feature_group_count "
"must be a positive integer, got {}.")
raise ValueError(msg.format(feature_group_count))
lhs_feature_count = lhs.shape[dimension_numbers.lhs_spec[1]]
quot, rem = divmod(lhs_feature_count, feature_group_count)
if rem:
msg = ("conv_general_dilated feature_group_count must divide lhs feature "
"dimension size, but {} does not divide {}.")
raise ValueError(msg.format(feature_group_count, lhs_feature_count))
if quot != rhs.shape[dimension_numbers.rhs_spec[1]]:
msg = ("conv_general_dilated lhs feature dimension size divided by "
"feature_group_count must equal the rhs input feature dimension "
"size, but {} // {} != {}.")
raise ValueError(msg.format(lhs_feature_count, feature_group_count,
rhs.shape[dimension_numbers.rhs_spec[1]]))
if rhs.shape[dimension_numbers.rhs_spec[0]] % feature_group_count:
msg = ("conv_general_dilated rhs output feature dimension size must be a "
"multiple of feature_group_count, but {} is not a multiple of {}.")
raise ValueError(msg.format(rhs.shape[dimension_numbers.rhs_spec[0]],
feature_group_count))
lhs_perm, rhs_perm, out_perm = dimension_numbers
lhs_trans = _dilate_shape(onp.take(lhs.shape, lhs_perm), lhs_dilation)
rhs_trans = _dilate_shape(onp.take(rhs.shape, rhs_perm), rhs_dilation)
out_trans = conv_shape_tuple(lhs_trans, rhs_trans, window_strides, padding)
return tuple(onp.take(out_trans, onp.argsort(out_perm)))
def _conv_general_dilated_dtype_rule(
lhs, rhs, window_strides, padding, lhs_dilation, rhs_dilation,
dimension_numbers, **unused_kwargs):
return binop_dtype_rule(_input_dtype, [_float, _float],
'conv_general_dilated', lhs, rhs)
_conv_spec_transpose = lambda spec: (spec[1], spec[0]) + spec[2:]
_conv_sdims = lambda spec: spec[2:]
def _conv_general_dilated_transpose_lhs(
g, rhs, window_strides, padding, lhs_dilation, rhs_dilation,
dimension_numbers, feature_group_count,
lhs_shape, rhs_shape, precision):
assert type(dimension_numbers) is ConvDimensionNumbers
lhs_sdims, rhs_sdims, out_sdims = map(_conv_sdims, dimension_numbers)
lhs_spec, rhs_spec, out_spec = dimension_numbers
t_rhs_spec = _conv_spec_transpose(rhs_spec)
if feature_group_count > 1:
# in addition to switching the dims in the spec, need to move the feature
# group axis into the transposed rhs's output feature dim
rhs = _reshape_axis_out_of(rhs_spec[0], feature_group_count, rhs)
rhs = _reshape_axis_into(rhs_spec[0], rhs_spec[1], rhs)
trans_dimension_numbers = ConvDimensionNumbers(out_spec, t_rhs_spec, lhs_spec)
padding = _conv_general_vjp_lhs_padding(
onp.take(lhs_shape, lhs_sdims), onp.take(rhs_shape, rhs_sdims),
window_strides, onp.take(g.shape, out_sdims), padding, lhs_dilation,
rhs_dilation)
revd_weights = rev(rhs, rhs_sdims)
return conv_general_dilated(
g, revd_weights, window_strides=lhs_dilation, padding=padding,
lhs_dilation=window_strides, rhs_dilation=rhs_dilation,
dimension_numbers=trans_dimension_numbers,
feature_group_count=feature_group_count, precision=precision)
def _conv_general_dilated_transpose_rhs(
g, lhs, window_strides, padding, lhs_dilation, rhs_dilation,
dimension_numbers, feature_group_count,
lhs_shape, rhs_shape, precision):
assert type(dimension_numbers) is ConvDimensionNumbers
if onp.size(g) == 0:
# Avoids forming degenerate convolutions where the RHS has spatial size 0.
return ad_util.zero
lhs_sdims, rhs_sdims, out_sdims = map(_conv_sdims, dimension_numbers)
lhs_trans, rhs_trans, out_trans = map(_conv_spec_transpose, dimension_numbers)
if feature_group_count > 1:
lhs = _reshape_axis_out_of(lhs_trans[0], feature_group_count, lhs)
lhs = _reshape_axis_into(lhs_trans[0], lhs_trans[1], lhs)
trans_dimension_numbers = ConvDimensionNumbers(lhs_trans, out_trans, rhs_trans)
padding = _conv_general_vjp_rhs_padding(
onp.take(lhs_shape, lhs_sdims), onp.take(rhs_shape, rhs_sdims),
window_strides, onp.take(g.shape, out_sdims), padding, lhs_dilation,
rhs_dilation)
return conv_general_dilated(
lhs, g, window_strides=rhs_dilation, padding=padding,
lhs_dilation=lhs_dilation, rhs_dilation=window_strides,
dimension_numbers=trans_dimension_numbers,
feature_group_count=feature_group_count, precision=precision)
def _conv_general_dilated_translation_rule(
c, lhs, rhs, window_strides, padding, lhs_dilation, rhs_dilation,
dimension_numbers, feature_group_count, precision, **unused_kwargs):
assert type(dimension_numbers) is ConvDimensionNumbers
dimension_numbers = _conv_general_proto(dimension_numbers)
return c.ConvGeneralDilated(lhs, rhs, window_strides, padding, lhs_dilation,
rhs_dilation, dimension_numbers,
feature_group_count,
precision_config=_precision_config(precision))
def _conv_general_dilated_batch_rule(
batched_args, batch_dims, window_strides, padding,
lhs_dilation, rhs_dilation, dimension_numbers,
feature_group_count, precision, **unused_kwargs):
lhs, rhs = batched_args
lhs_bdim, rhs_bdim = batch_dims
lhs_spec, rhs_spec, out_spec = dimension_numbers
if lhs_bdim is not None and rhs_bdim is not None:
assert lhs.shape[lhs_bdim] == rhs.shape[rhs_bdim]
new_lhs = _reshape_axis_into(lhs_bdim, lhs_spec[1], lhs)
new_rhs = _reshape_axis_into(rhs_bdim, rhs_spec[0], rhs)
out = conv_general_dilated(
new_lhs, new_rhs, window_strides, padding, lhs_dilation, rhs_dilation,
dimension_numbers,
feature_group_count=lhs.shape[lhs_bdim] * feature_group_count,
precision=precision)
out = _reshape_axis_out_of(out_spec[1], lhs.shape[lhs_bdim], out)
return out, out_spec[1]
elif lhs_bdim is not None:
new_lhs = _reshape_axis_into(lhs_bdim, lhs_spec[0], lhs)
out = conv_general_dilated(new_lhs, rhs, window_strides, padding,
lhs_dilation, rhs_dilation, dimension_numbers,
feature_group_count, precision=precision)
out = _reshape_axis_out_of(out_spec[0], lhs.shape[lhs_bdim], out)
return out, out_spec[0]
elif rhs_bdim is not None:
if feature_group_count == 1:
new_rhs = _reshape_axis_into(rhs_bdim, rhs_spec[0], rhs)
out = conv_general_dilated(lhs, new_rhs, window_strides, padding,
lhs_dilation, rhs_dilation, dimension_numbers,
feature_group_count, precision=precision)
out = _reshape_axis_out_of(out_spec[1], rhs.shape[rhs_bdim], out)
return out, out_spec[1]
else:
# feature_group needs to be outermost, so we need to factor it out of the
# rhs output feature dim, then factor the batch dim into the remaining rhs
# output feature dim, then put feature_group back in. we do something
# similar on the output. an alternative which would require more FLOPs but
# fewer reshapes would be to broadcast lhs.
new_rhs = _reshape_axis_out_of(rhs_spec[0] + int(rhs_bdim <= rhs_spec[0]),
feature_group_count, rhs)
new_rhs = _reshape_axis_into(rhs_bdim + int(rhs_spec[0] < rhs_bdim),
rhs_spec[0] + 1,
new_rhs)
new_rhs = _reshape_axis_into(rhs_spec[0], rhs_spec[0], new_rhs)
out = conv_general_dilated(lhs, new_rhs, window_strides, padding,
lhs_dilation, rhs_dilation, dimension_numbers,
feature_group_count, precision=precision)
out = _reshape_axis_out_of(out_spec[1], feature_group_count, out)
out = _reshape_axis_out_of(out_spec[1] + 1, rhs.shape[rhs_bdim], out)
out = _reshape_axis_into(out_spec[1], out_spec[1] + 1, out)
return out, out_spec[1]
conv_general_dilated_p = standard_primitive(
_conv_general_dilated_shape_rule, _conv_general_dilated_dtype_rule,
'conv_general_dilated', _conv_general_dilated_translation_rule)
ad.defbilinear(conv_general_dilated_p,
_conv_general_dilated_transpose_lhs,
_conv_general_dilated_transpose_rhs)
batching.primitive_batchers[conv_general_dilated_p] = \
_conv_general_dilated_batch_rule
def _reshape_axis_into(src, dst, x):
perm = [i for i in range(x.ndim) if i != src]
perm.insert(dst, src)
new_shape = list(onp.delete(x.shape, src))
new_shape[dst] *= x.shape[src]
return reshape(x, new_shape, perm)
def _reshape_axis_out_of(src, size1, x):
shape = list(x.shape)
size2, ragged = divmod(shape[src], size1)
assert not ragged
shape[src:src+1] = [size1, size2]
return reshape(x, shape)
def _precision_config(precision):
if precision is not None:
config = xla_client.PrecisionConfig()
config.operand_precision.extend((precision, precision))
return config
return None
def _dot_general_shape_rule(lhs, rhs, dimension_numbers, precision):
(lhs_contracting, rhs_contracting), (lhs_batch, rhs_batch) = dimension_numbers
if len(lhs_batch) != len(rhs_batch):
msg = ("dot_general requires equal numbers of lhs_batch and rhs_batch "
"dimensions, got lhs_batch {} and rhs_batch {}.")
raise TypeError(msg.format(lhs_batch, rhs_batch))
if not onp.all(onp.equal(lhs_batch, rhs_batch)):
msg = ("dot_general requires same lhs and rhs batch dimension numbers, "
"got {} and {}.")
raise TypeError(msg.format(lhs_batch, rhs_batch))
lhs_batch_shape = onp.take(lhs.shape, lhs_batch)
rhs_batch_shape = onp.take(rhs.shape, rhs_batch)
if not onp.all(onp.equal(lhs_batch_shape, rhs_batch_shape)):
msg = ("dot_general requires lhs batch dimensions and rhs batch dimensions "
"to have the same shape, got {} and {}.")
raise TypeError(msg.format(lhs_batch_shape, rhs_batch_shape))
if tuple(sorted(lhs_batch)) != tuple(range(len(lhs_batch))):
msg = ("dot_general requires lhs batch dimensions to precede contracting "
"and non-contracting dimensions, got lhs_batch {}.")
raise TypeError(msg.format(lhs_batch))
if tuple(sorted(rhs_batch)) != tuple(range(len(rhs_batch))):
msg = ("dot_general requires rhs batch dimensions to precede contracting "
"and non-contracting dimensions, got rhs_batch {}.")
raise TypeError(msg.format(rhs_batch))
lhs_contracting_shape = onp.take(lhs.shape, lhs_contracting)
rhs_contracting_shape = onp.take(rhs.shape, rhs_contracting)
if not onp.all(onp.equal(lhs_contracting_shape, rhs_contracting_shape)):
msg = ("dot_general requires contracting dimensions to have the same "
"shape, got {} and {}.")
raise TypeError(msg.format(lhs_contracting_shape, rhs_contracting_shape))
batch_shape = tuple(onp.take(lhs.shape, lhs_batch))
lhs_contract_or_batch = tuple(lhs_contracting) + tuple(lhs_batch)
lhs_tensored_shape = tuple(onp.delete(lhs.shape, lhs_contract_or_batch))
rhs_contract_or_batch = tuple(rhs_contracting) + tuple(rhs_batch)
rhs_tensored_shape = tuple(onp.delete(rhs.shape, rhs_contract_or_batch))
return batch_shape + lhs_tensored_shape + rhs_tensored_shape
def _dot_general_dtype_rule(lhs, rhs, dimension_numbers, precision):
return binop_dtype_rule(_input_dtype, [_num, _num], 'dot_general', lhs, rhs)
def _dot_general_transpose_lhs(g, y, dimension_numbers, precision,
swap_ans=False):
(x_contract, y_contract), (x_batch, y_batch) = dimension_numbers
x_ndim = g.ndim - y.ndim + len(x_batch) + 2 * len(x_contract)
x_kept = remaining(range(x_ndim), x_contract, x_batch)
y_kept = remaining(range(y.ndim), y_contract, y_batch)
if swap_ans:
ans_batch, ans_y, _ = ranges_like(x_batch, y_kept, x_kept)
else:
ans_batch, _, ans_y = ranges_like(x_batch, x_kept, y_kept)
dims = ((ans_y, y_kept), (ans_batch, y_batch))
x_contract_sorted_by_y = list(onp.take(x_contract, onp.argsort(y_contract)))
out_axes = onp.argsort(list(x_batch) + x_kept + x_contract_sorted_by_y)
return transpose(dot_general(g, y, dims, precision=precision),
tuple(out_axes))
def _dot_general_transpose_rhs(g, x, dimension_numbers, precision):
(x_contract, y_contract), (x_batch, y_batch) = dimension_numbers
swapped_dimension_numbers = ((y_contract, x_contract), (y_batch, x_batch))
return _dot_general_transpose_lhs(g, x, swapped_dimension_numbers,
precision, swap_ans=True)
def _dot_general_batch_rule(batched_args, batch_dims, dimension_numbers,
precision):
# there are three kinds of dimensions in a dot_general:
# - contraction dimensions appear in lhs and rhs but not the result
# - batch dimensions appear in lhs, rhs, and result
# - tensor product dimensions appear in the result and one of lhs or rhs
(lhs_contract, rhs_contract), (lhs_batch, rhs_batch) = dimension_numbers
lhs, rhs = batched_args
lbd, rbd = batch_dims
assert lbd is not None or rbd is not None
if lbd is not None and rbd is not None:
# adding a batch dimension
if lbd != 0:
lhs = batching.moveaxis(lhs, lbd, 0)
if rbd != 0:
rhs = batching.moveaxis(rhs, rbd, 0)
lhs_batch = (0,) + tuple(onp.add(1, lhs_batch))
rhs_batch = (0,) + tuple(onp.add(1, rhs_batch))
lhs_contract = tuple(onp.add(1, lhs_contract))
rhs_contract = tuple(onp.add(1, rhs_contract))
result_batch_dim = 0
else:
# adding a tensor product dimension
if lbd is not None:
if lhs_batch == () or lbd > onp.max(lhs_batch):
# can avoid transposes
bump_lhs_contract = onp.greater_equal(lhs_contract, lbd)
lhs_contract = tuple(onp.add(lhs_contract, bump_lhs_contract))
result_batch_dim = lbd - len(lhs_contract) + sum(bump_lhs_contract)
else:
# move the new dimension to the end of lhs to avoid changing batch dims
lhs = batching.moveaxis(lhs, lbd, lhs.ndim - 1)
# lhs tensor product dims in result come after batch dims
result_batch_dim = lhs.ndim - len(lhs_contract) - 1
else:
if rhs_batch == () or rbd > onp.max(rhs_batch):
# can avoid transposes
bump_rhs_contract = onp.greater_equal(rhs_contract, rbd)
rhs_contract = tuple(onp.add(rhs_contract, bump_rhs_contract))
result_batch_dim = (rbd + (lhs.ndim - len(lhs_contract) - len(lhs_batch))
- (len(rhs_contract) - sum(bump_rhs_contract)))
else:
# move the new dimension to the end of rhs to avoid changing batch dims
rhs = batching.moveaxis(rhs, rbd, rhs.ndim - 1)
# rhs tensor product dims in result come after batch dims + lhs tensor
# product dims
result_batch_dim = (lhs.ndim - len(lhs_contract) - len(lhs_batch) +
rhs.ndim - len(rhs_contract) - 1)
new_dimension_numbers = [(lhs_contract, rhs_contract), (lhs_batch, rhs_batch)]
batched_out = dot_general(lhs, rhs, new_dimension_numbers,
precision=precision)
return batched_out, int(result_batch_dim)
def _dot_general_translation_rule(c, lhs, rhs, dimension_numbers, precision):
return c.DotGeneral(lhs, rhs, dimension_numbers,
precision_config=_precision_config(precision))
def _dot_general_polymorphic_shape_rule(shape_exprs, dimension_numbers,
precision):
del precision # Unused.
lhs_shape, rhs_shape = shape_exprs
lhs_ndim, rhs_ndim = len(lhs_shape), len(rhs_shape)
(lhs_contract, rhs_contract), (lhs_batch, rhs_batch) = dimension_numbers
lhs_batch_shape = [lhs_shape[d] for d in lhs_batch]
rhs_batch_shape = [rhs_shape[d] for d in rhs_batch]
if lhs_batch_shape != rhs_batch_shape: raise ShapeError
lhs_contract_shape = [lhs_shape[d] for d in lhs_contract]
rhs_contract_shape = [rhs_shape[d] for d in rhs_contract]
if lhs_contract_shape != rhs_contract_shape: raise ShapeError
lhs_tensorprod_shape = [lhs_shape[d] for d in range(lhs_ndim)
if d not in lhs_batch and d not in lhs_contract]
rhs_tensorprod_shape = [rhs_shape[d] for d in range(rhs_ndim)
if d not in rhs_batch and d not in rhs_contract]
return ShapeExpr(
lhs_batch_shape + lhs_tensorprod_shape + rhs_tensorprod_shape)
def _dot_general_masking_rule(padded_vals, logical_shapes, dimension_numbers,
precision):
lhs, rhs = padded_vals
lhs_shape, rhs_shape = logical_shapes
lhs_ndim, rhs_ndim = len(lhs_shape), len(rhs_shape)
(lhs_contract, rhs_contract), (lhs_batch, rhs_batch) = dimension_numbers
# we need only mask the lhs contraction dimensions
if len(lhs_contract) == 0:
return dot_general(lhs, rhs, dimension_numbers, precision=precision)
else:
masks = [broadcasted_iota(onp.int32, lhs.shape, d) < lhs_shape[d]
for d in lhs_contract]
mask_intersection = masks[0]
for mask in masks[1:]:
mask_intersection &= mask
masked_lhs = select(mask_intersection, lhs, zeros_like_array(lhs))
return dot_general(masked_lhs, rhs, dimension_numbers, precision=precision)
dot_general_p = standard_primitive(_dot_general_shape_rule,
_dot_general_dtype_rule, 'dot_general',
_dot_general_translation_rule)
ad.defbilinear(dot_general_p,
_dot_general_transpose_lhs, _dot_general_transpose_rhs)
batching.primitive_batchers[dot_general_p] = _dot_general_batch_rule
masking.shape_rules[dot_general_p] = _dot_general_polymorphic_shape_rule
masking.masking_rules[dot_general_p] = _dot_general_masking_rule
def _broadcast_shape_rule(operand, sizes):
_check_shapelike('broadcast', 'sizes', sizes)
return tuple(sizes) + operand.shape
def _broadcast_batch_rule(batched_args, batch_dims, sizes):
operand, = batched_args
bdim, = batch_dims
new_bdim = None if bdim is None else bdim + len(sizes)
return broadcast(operand, sizes), new_bdim
broadcast_p = standard_primitive(
_broadcast_shape_rule, _input_dtype, 'broadcast')
ad.deflinear(broadcast_p, lambda t, sizes: [_reduce_sum(t, range(len(sizes)))])
batching.primitive_batchers[broadcast_p] = _broadcast_batch_rule
def _broadcast_in_dim_shape_rule(operand, shape, broadcast_dimensions):
_check_shapelike('broadcast_in_dim', 'shape', shape)
_check_shapelike('broadcast_in_dim', 'broadcast_dimensions',
broadcast_dimensions)
if operand.ndim != len(broadcast_dimensions):
msg = ('broadcast_in_dim broadcast_dimensions must have length equal to '
'operand ndim, got broadcast_dimensions {} for operand ndim {}.')
raise TypeError(msg.format(broadcast_dimensions, operand.ndim))
if not set(broadcast_dimensions).issubset(set(range(len(shape)))):
msg = ('broadcast_in_dim broadcast_dimensions must be a subset of output '
'dimensions, got {} for operand ndim {} and shape {}.')
raise TypeError(msg.format(broadcast_dimensions, operand.ndim, shape))
return shape
def _broadcast_in_dim_transpose_rule(t, shape, broadcast_dimensions):
axes = tuple(onp.delete(range(len(shape)), broadcast_dimensions))
return [_reduce_sum(t, axes)]
def _broadcast_in_dim_batch_rule(batched_args, batch_dims, shape,
broadcast_dimensions):
operand, = batched_args
bdim, = batch_dims
new_operand = batching.moveaxis(operand, bdim, 0)
new_shape = (operand.shape[bdim],) + shape
new_broadcast_dimensions = (0,) + tuple(onp.add(1, broadcast_dimensions))
return broadcast_in_dim(new_operand, new_shape, new_broadcast_dimensions), 0
broadcast_in_dim_p = standard_primitive(
_broadcast_in_dim_shape_rule, _input_dtype, 'broadcast_in_dim')
ad.deflinear(broadcast_in_dim_p, _broadcast_in_dim_transpose_rule)
batching.primitive_batchers[broadcast_in_dim_p] = _broadcast_in_dim_batch_rule
def _clamp_shape_rule(min, operand, max):
if min.shape and min.shape != operand.shape:
m = "clamp requires min.shape == operand.shape or min.shape == (), got {}."
raise TypeError(m.format(min.shape))
if max.shape and max.shape != operand.shape:
m = "clamp requires max.shape == operand.shape or max.shape == (), got {}."
raise TypeError(m.format(max.shape))
return operand.shape
_clamp_dtype_rule = partial(binop_dtype_rule, _input_dtype, [_any, _any, _any],
'clamp')
clamp_p = standard_primitive(_clamp_shape_rule, _clamp_dtype_rule, 'clamp')
ad.defjvp(clamp_p,
lambda g, min, operand, max:
select(bitwise_and(gt(min, operand), lt(min, max)),
_brcast(g, operand), _zeros(operand)),
lambda g, min, operand, max:
select(bitwise_and(gt(operand, min), lt(operand, max)),
g, _zeros(operand)),
lambda g, min, operand, max:
select(lt(max, operand), _brcast(g, operand), _zeros(operand)))
def _concatenate_shape_rule(*operands, **kwargs):
dimension = kwargs.pop('dimension')
if not operands:
msg = "concatenate expects at least one operand, got 0."
raise TypeError(msg)
if not all(isinstance(operand, UnshapedArray) for operand in operands):
msg = "All objects to concatenate must be arrays, got {}."
op = next(op for op in operands if not isinstance(op, UnshapedArray))
raise TypeError(msg.format(type(op)))
if len(set(operand.ndim for operand in operands)) != 1:
msg = "Cannot concatenate arrays with different ranks, got {}."
raise TypeError(msg.format(", ".join(str(o.ndim) for o in operands)))
shapes = onp.array([operand.shape for operand in operands])
if not 0 <= dimension < shapes.shape[1]:
msg = "concatenate dimension out of bounds: dimension {} for shapes {}."
raise TypeError(msg.format(dimension, ", ".join(map(str, shapes))))
if not onp.all(onp.delete(shapes[0] == shapes, dimension, axis=1)):
msg = ("Cannot concatenate arrays with shapes that differ in dimensions "
"other than the one being concatenated: dimension {} for shapes {}.")
raise TypeError(msg.format(dimension, ", ".join(map(str, shapes))))
concat_size = sum(o.shape[dimension] for o in operands)
ex_shape = operands[0].shape
return ex_shape[:dimension] + (concat_size,) + ex_shape[dimension+1:]
def _concatenate_dtype_rule(*operands, **kwargs):
_check_same_dtypes('concatenate', False, *(o.dtype for o in operands))
return operands[0].dtype
def _concatenate_translation_rule(c, *operands, **kwargs):
dimension = kwargs.pop('dimension')
return c.Concatenate(operands, dimension=dimension)
def _concatenate_transpose_rule(t, *operands, **kwargs):
dimension = kwargs.pop('dimension')
operand_shapes = kwargs.pop('operand_shapes')
if t is ad_util.zero:
return [ad_util.zero if o is ad.undefined_primal else None for o in operands]
else:
limit_points = onp.cumsum([shape[dimension] for shape in operand_shapes])
starts = onp.zeros((len(operands), t.ndim), dtype=int)
starts[1:, dimension] = limit_points[:-1]
limits = onp.tile(t.shape, (len(operands), 1))
limits[:, dimension] = limit_points
return [slice(t, start, limit) if o is ad.undefined_primal else None
for o, start, limit in zip(operands, starts, limits)]
def _concatenate_batch_rule(batched_args, batch_dims, dimension, operand_shapes):
size = next(op.shape[bdim] for op, bdim in zip(batched_args, batch_dims)
if bdim is not None)
operands = [batching.moveaxis(op, bdim, 0) if bdim is not None
else broadcast(op, (size,))
for op, bdim in zip(batched_args, batch_dims)]
return concatenate(operands, dimension + 1), 0
def _concat_polymorphic_shape_rule(shape_exprs, dimension, operand_shapes):
out_shape = list(shape_exprs[0])
out_shape[dimension] = _reduce(operator.add, [e[dimension] for e in shape_exprs])
return ShapeExpr(out_shape)
# The concatenate_p masking rule requires use of a while-loop construct and so
# is defined in lax_control_flow.py
concatenate_p = standard_primitive(
_concatenate_shape_rule, _concatenate_dtype_rule, 'concatenate',
_concatenate_translation_rule)
ad.deflinear(concatenate_p, _concatenate_transpose_rule)
ad.primitive_transposes[concatenate_p] = _concatenate_transpose_rule
batching.primitive_batchers[concatenate_p] = _concatenate_batch_rule
masking.shape_rules[concatenate_p] = _concat_polymorphic_shape_rule
def _pad_shape_rule(operand, padding_value, padding_config):
if operand.dtype != padding_value.dtype:
msg = "pad operand and padding_value must be same dtype: got {} and {}."
raise TypeError(msg.format(operand.dtype, padding_value.dtype))
lo, hi, interior = zip(*padding_config)
out_shape = onp.add(onp.add(onp.add(lo, hi), operand.shape),
onp.multiply(interior, onp.subtract(operand.shape, 1)))
return tuple(out_shape)
def _pad_transpose(t, operand, padding_value, padding_config):
if t is ad_util.zero:
return [ad_util.zero if operand is ad.undefined_primal else None,
ad_util.zero if padding_value is ad.undefined_primal else None]
lo, hi, interior = zip(*padding_config)
total = lambda x: _reduce_sum(x, list(range(t.ndim)))
def t_op():
unpad_config = zip(onp.negative(lo), onp.negative(hi), onp.zeros_like(interior))
unpadded = pad(t, onp.array(0., t.dtype), unpad_config)
return slice(unpadded, onp.zeros_like(lo), unpadded.shape, onp.add(interior, 1))
t_operand = t_op() if operand is ad.undefined_primal else None
t_padv = sub(total(t), total(t_operand)) if padding_value is ad.undefined_primal else None
return [t_operand, t_padv]
def _pad_batch_rule(batched_args, batch_dims, padding_config):
operand, padding_value = batched_args
operand_bdim, padding_value_bdim = batch_dims
if padding_value_bdim is None:
assert operand_bdim is not None
padding_config = list(padding_config)
padding_config.insert(operand_bdim, (0, 0, 0))
return pad(operand, padding_value, padding_config), operand_bdim
else:
raise NotImplementedError # loop and stack
pad_p = standard_primitive(_pad_shape_rule, _input_dtype, 'pad')
ad.deflinear(pad_p, _pad_transpose)
ad.primitive_transposes[pad_p] = _pad_transpose
batching.primitive_batchers[pad_p] = _pad_batch_rule
# We have a nonstandard reshape impl so that we can be lazy about data movement
# for specific types, particularly ShardedDeviceArrays / ChunkedDeviceArrays
def _reshape_impl(operand, new_sizes, dimensions, old_sizes):
if (type(operand) is pxla.ShardedDeviceArray and dimensions is None
and _is_axis_merge(old_sizes, new_sizes)):
aval = ShapedArray(new_sizes, operand.dtype)
return pxla.ChunkedDeviceArray(old_sizes[0], aval, operand.device_buffers)
elif (type(operand) is pxla.ChunkedDeviceArray and dimensions is None
and _is_axis_split(old_sizes, new_sizes)
and operand.axis_size == new_sizes[0]):
aval = ShapedArray(new_sizes, operand.dtype)
return pxla.ShardedDeviceArray(aval, operand.device_buffers)
else:
return xla.apply_primitive(reshape_p, operand, new_sizes=new_sizes,
dimensions=dimensions, old_sizes=old_sizes)
def _is_axis_merge(s1, s2):
return s1[2:] == s2[1:] and s1[0] * s1[1] == s2[0]
def _is_axis_split(s1, s2):
return _is_axis_merge(s2, s1)
def _reshape_shape_rule(operand, new_sizes, dimensions, **unused_kwargs):
if not onp.all(onp.greater_equal(new_sizes, 0)):
msg = 'reshape new_sizes must all be positive, got {}.'
raise TypeError(msg.format(new_sizes))
if prod(onp.shape(operand)) != prod(new_sizes):
msg = 'reshape total size must be unchanged, got new_sizes {} for shape {}.'
raise TypeError(msg.format(new_sizes, onp.shape(operand)))
if dimensions is not None:
if set(dimensions) != set(range(onp.ndim(operand))):
msg = ('reshape dimensions must be a permutation of operand dimensions, '
'got dimensions {} for shape {}.')
raise TypeError(msg.format(dimensions, onp.shape(operand)))
return tuple(new_sizes)
def _reshape_dtype_rule(operand, new_sizes, dimensions, **unused_kwargs):
return operand.dtype
def _reshape_translation_rule(c, operand, new_sizes, dimensions, old_sizes):
del old_sizes # Unused.
return c.Reshape(operand, new_sizes=new_sizes, dimensions=dimensions)
def _reshape_transpose_rule(t, new_sizes, dimensions, old_sizes):
if dimensions is None:
return [reshape(t, old_sizes)]
else:
return [transpose(reshape(t, onp.take(old_sizes, dimensions)),
onp.argsort(dimensions))]
def _reshape_batch_rule(batched_args, batch_dims, new_sizes, dimensions, **unused):
operand, = batched_args
bdim, = batch_dims
operand = batching.moveaxis(operand, bdim, 0)
if dimensions is not None:
dimensions = (0,) + tuple(onp.add(1, dimensions))
return reshape(operand, operand.shape[:1] + new_sizes, dimensions), 0
def _reshape_polymorphic_shape_rule(shape_exprs, new_sizes, dimensions, old_sizes):
if dimensions is not None: raise NotImplementedError
shape_expr, = shape_exprs
if masking.prod(shape_expr) != masking.prod(new_sizes): raise ShapeError
return new_sizes
reshape_p = standard_primitive(_reshape_shape_rule, _reshape_dtype_rule,
'reshape', _reshape_translation_rule)
reshape_p.def_impl(_reshape_impl)
ad.deflinear(reshape_p, _reshape_transpose_rule)
batching.primitive_batchers[reshape_p] = _reshape_batch_rule
masking.shape_rules[reshape_p] = _reshape_polymorphic_shape_rule
def _rev_shape_rule(operand, dimensions):
_check_shapelike('rev', 'dimensions', dimensions)
if len(set(dimensions)) != len(dimensions):
msg = 'rev dimensions must be unique, got {}.'
raise TypeError(msg.format(dimensions))
if not _max(dimensions) < operand.ndim:
msg = ('rev dimensions must all be less than operand ndim, got dimensions '
'{} for operand ndim {}.')
raise TypeError(msg.format(dimensions, operand.ndim))
return operand.shape
def _rev_batch_rule(batched_args, batch_dims, dimensions):
operand, = batched_args
bdim, = batch_dims
new_dimensions = [i + 1 if i >= bdim else i for i in dimensions]
return rev(operand, new_dimensions), bdim
rev_p = standard_primitive(_rev_shape_rule, _input_dtype, 'rev')
ad.deflinear(rev_p, lambda t, dimensions: [rev(t, dimensions)])
batching.primitive_batchers[rev_p] = _rev_batch_rule
def _transpose_shape_rule(operand, permutation):
if not isinstance(permutation, (tuple, list, onp.ndarray)):
msg = "transpose permutation must be a tuple/list/ndarray, got {}."
raise TypeError(msg.format(type(permutation)))
if tuple(sorted(permutation)) != tuple(range(operand.ndim)):
msg = ("transpose permutation isn't a permutation of operand dimensions, "
"got permutation {} for operand shape {}.")
raise TypeError(msg.format(permutation, operand.shape))
return tuple(onp.take(operand.shape, permutation))
def _transpose_batch_rule(batched_args, batch_dims, permutation):
operand, = batched_args
bdim, = batch_dims
perm = (bdim,) + tuple(i if i < bdim else i+1 for i in permutation)
return transpose(operand, perm), 0
transpose_p = standard_primitive(_transpose_shape_rule, _input_dtype,
'transpose')
ad.deflinear(transpose_p,
lambda t, permutation: [transpose(t, onp.argsort(permutation))])
batching.primitive_batchers[transpose_p] = _transpose_batch_rule
def _select_shape_rule(pred, on_true, on_false):
if on_true.shape != on_false.shape:
msg = "select on_true and on_false must have the same shape, got {} and {}."
raise TypeError(msg.format(on_true.shape, on_false.shape))
if pred.shape and pred.shape != on_true.shape:
msg = ("select pred must be scalar or have the same shape as on_true and "
"on_false, got pred shape {} for on_true and on_false of shape {}.")
raise TypeError(msg.format(pred.shape, on_true.shape))
return on_true.shape
def _select_dtype_rule(pred, on_true, on_false):
_check_same_dtypes("select", False, on_true.dtype, on_false.dtype)
if not dtypes.issubdtype(pred.dtype, onp.bool_):
msg = "select pred must be boolean type, got {}."
raise TypeError(msg.format(pred.dtype))
return on_true.dtype
def _select_transpose_rule(t, pred, on_true, on_false):
assert pred is not ad.undefined_primal
if t is ad_util.zero:
return [None,
ad_util.zero if on_true is ad.undefined_primal else None,
ad_util.zero if on_false is ad.undefined_primal else None]
else:
zeros = full_like(t, 0)
return [None,
select(pred, t, zeros) if on_true is ad.undefined_primal else None,
select(pred, zeros, t) if on_false is ad.undefined_primal else None]
def _select_batch_rule(batched_args, batch_dims, **unused_kwargs):
pred, on_true, on_false, = batched_args
pred_bdim, ot_bdim, of_bdim = batch_dims
size = next(x.shape[i] for x, i in zip(batched_args, batch_dims)
if i is not None)
# avoid transposes and some broadcasts in special cases
if pred_bdim == ot_bdim == of_bdim:
if onp.shape(pred) == onp.shape(on_true):
return select(pred, on_true, on_false), pred_bdim
else:
# vmapped function had a scalar pred with nonscalar args
assert onp.ndim(pred) == 1
pred = broadcast_in_dim(pred, on_true.shape, [pred_bdim])
return select(pred, on_true, on_false), pred_bdim
elif onp.ndim(pred) == 0 and ot_bdim is not None and of_bdim is not None:
if ot_bdim == of_bdim:
return select(pred, on_true, on_false), ot_bdim
elif onp.shape(on_true) == onp.shape(on_false):
on_false = batching.moveaxis(on_false, of_bdim, ot_bdim)
return select(pred, on_true, on_false), ot_bdim
pred = batching.bdim_at_front(pred, pred_bdim, size) if onp.shape(pred) else pred
if not onp.shape(on_true) == onp.shape(on_false) == ():
on_true = batching.bdim_at_front(on_true, ot_bdim, size)
on_false = batching.bdim_at_front(on_false, of_bdim, size)
assert onp.shape(on_true) == onp.shape(on_false)
if 0 < onp.ndim(pred) < onp.ndim(on_true):
# vmapped function had a scalar pred with nonscalar args
assert onp.ndim(pred) == 1
pred = broadcast_in_dim(pred, on_true.shape, [0])
if onp.ndim(pred) > onp.ndim(on_true):
assert onp.ndim(on_true) == 0
on_true = broadcast(on_true, pred.shape)
on_false = broadcast(on_false, pred.shape)
return select(pred, on_true, on_false), 0
select_p = standard_primitive(_select_shape_rule, _select_dtype_rule, 'select')
ad.defjvp(select_p,
None,
lambda g, b, x, y: select(b, g, _zeros(g)),
lambda g, b, x, y: select(b, _zeros(g), g))
ad.primitive_transposes[select_p] = _select_transpose_rule
batching.primitive_batchers[select_p] = _select_batch_rule
def _slice_shape_rule(operand, start_indices, limit_indices, strides,
operand_shape):
_check_shapelike("slice", "start_indices", start_indices)
_check_shapelike("slice", "limit_indices", limit_indices)
if operand.ndim != len(start_indices):
msg = ("slice start_indices must have length equal to the number of "
"dimensions of the operand, got indices {} for operand shape {}.")
raise TypeError(msg.format(start_indices, operand.shape))
if len(start_indices) != len(limit_indices):
msg = ("slice limit_indices must have the same length as start_indices, "
"got start_inidices {} and limit_indices {}.")
raise TypeError(msg.format(start_indices, limit_indices))
if not onp.all(onp.less_equal(limit_indices, operand.shape)):
msg = ("slice limit_indices must be less than or equal to operand shape, "
"got limit_indices {} for operand shape {}.")
raise TypeError(msg.format(limit_indices, operand.shape))
if not onp.all(onp.greater_equal(start_indices, 0)):
msg = ("slice start_indices must be greater than or equal to zero, "
"got start_indices of {}.")
raise TypeError(msg.format(start_indices))
if not onp.all(onp.greater_equal(limit_indices, start_indices)):
msg = ("slice limit_indices must be greater than or equal to start_indices,"
" got start_indices {} and limit_indices {}.")
raise TypeError(msg.format(start_indices, limit_indices))
if strides is None:
strides = onp.ones(operand.ndim, onp.int32)
else:
_check_shapelike("slice", "strides", strides)
if len(strides) != operand.ndim:
msg = ("slice strides must have length equal to the number of dimensions "
"of the operand, got strides {} for operand shape {}.")
raise TypeError(msg.format(strides, operand.shape))
if not onp.all(onp.greater(strides, 0)):
msg = "slice strides must be positive, got {}"
raise TypeError(msg.format(strides))
result_shape = onp.floor_divide(
onp.add(onp.subtract(limit_indices, start_indices), strides) - 1, strides)
return tuple(result_shape)
def _slice_translation_rule(c, operand, start_indices, limit_indices, strides,
operand_shape):
return c.Slice(operand, start_indices, limit_indices, strides)
def _slice_transpose_rule(t, start_indices, limit_indices, strides,
operand_shape):
if strides is None or onp.all(onp.equal(strides, 1)):
pads = zip(start_indices, onp.subtract(operand_shape, limit_indices),
(0,) * len(start_indices))
else:
real_limits = onp.add(onp.add(start_indices, 1),
onp.multiply(onp.subtract(t.shape, 1), strides))
pads = zip(start_indices, onp.subtract(operand_shape, real_limits),
onp.subtract(strides, 1))
result = pad(t, _const(t, 0), pads)
assert result.shape == operand_shape
return [result]
def _slice_batching_rule(batched_args, batch_dims, start_indices, limit_indices,
strides, **unused_kwargs):
operand, = batched_args
bdim, = batch_dims
new_start_indices = list(start_indices)
new_start_indices.insert(bdim, 0)
new_limit_indices = list(limit_indices)
new_limit_indices.insert(bdim, operand.shape[bdim])
if strides is None:
new_strides = None
else:
new_strides = list(strides)
new_strides.insert(bdim, 1)
out = slice(operand, new_start_indices, new_limit_indices, new_strides)
return out, bdim
slice_p = standard_primitive(_slice_shape_rule, _input_dtype, 'slice',
_slice_translation_rule)
ad.deflinear(slice_p, _slice_transpose_rule)
batching.primitive_batchers[slice_p] = _slice_batching_rule
def _dynamic_slice_shape_rule(operand, *start_indices, **kwargs):
slice_sizes = kwargs["slice_sizes"]
if operand.ndim != len(start_indices):
msg = ("dynamic_slice start_indices must have length equal to the number "
"of dimensions of the operand, got indices {} for operand shape {}.")
raise TypeError(msg.format(start_indices, operand.shape))
if len(start_indices) != len(slice_sizes):
msg = ("dynamic_slice slice_sizes must have the same length as "
"start_indices, got start_inidices length {} and slice_sizes {}.")
raise TypeError(msg.format(len(start_indices), slice_sizes))
if not onp.all(onp.less_equal(slice_sizes, operand.shape)):
msg = ("slice slice_sizes must be less than or equal to operand shape, "
"got slice_sizes {} for operand shape {}.")
raise TypeError(msg.format(slice_sizes, operand.shape))
if not onp.all(onp.greater_equal(slice_sizes, 0)):
msg = ("slice slice_sizes must be greater than or equal to zero, "
"got slice_sizes of {}.")
raise TypeError(msg.format(slice_sizes))
return tuple(slice_sizes)
def _dynamic_slice_dtype_rule(operand, *start_indices, **kw):
if any(i.dtype != start_indices[0].dtype or
not dtypes.issubdtype(i.dtype, onp.integer) for i in start_indices):
msg = ("index arguments to dynamic_slice must be integers of the same "
"type, got: {}")
raise TypeError(msg.format(", ".join(i.dtype.name for i in start_indices)))
return operand.dtype
def _dynamic_slice_translation_rule(c, operand, *start_indices, **kwargs):
slice_sizes = kwargs["slice_sizes"]
return c.DynamicSlice(operand, start_indices, slice_sizes)
def _dynamic_slice_jvp(primals, tangents, slice_sizes, operand_shape):
tangent_out = ad_util.zero
if tangents[0] is not ad_util.zero:
tangent_out = dynamic_slice(tangents[0], primals[1:], slice_sizes)
return dynamic_slice(primals[0], primals[1:], slice_sizes), tangent_out
def _dynamic_slice_transpose_rule(t, operand, *start_indices, **kwargs):
operand_shape = kwargs["operand_shape"]
assert operand is ad.undefined_primal
assert all(s is not ad.undefined_primal for s in start_indices)
zeros = full(operand_shape, tie_in(t, _zero(t)))
return ([dynamic_update_slice(zeros, t, start_indices)] +
[None] * len(start_indices))
def _batch_dynamic_slice_indices(indices, bdims):
size = next((x.shape[i] for x, i in zip(indices, bdims) if i is not None), -1)
if size < 0:
return concatenate([reshape(i, [1]) for i in indices], 0), None
indices = concatenate(
[broadcast_in_dim(x, (size, 1),
broadcast_dimensions=((0,) if i is not None else ()))
for x, i in zip(indices, bdims)],
dimension=1)
return indices, 0
def _dynamic_slice_batching_rule(batched_args, batch_dims, slice_sizes,
operand_shape):
# A dynamic slice is a special case of gather; we can delegate to the gather
# batching rule.
# TODO(phawkins): consider removing dynamic_slice entirely and using gather
# always.
dims = tuple(range(len(operand_shape)))
dnums = GatherDimensionNumbers(offset_dims=dims, collapsed_slice_dims=(),
start_index_map=dims)
index, index_bdim = _batch_dynamic_slice_indices(batched_args[1:],
batch_dims[1:])
return _gather_batching_rule(
[batched_args[0], index], [batch_dims[0], index_bdim], dnums, slice_sizes,
operand_shape)
dynamic_slice_p = standard_primitive(
_dynamic_slice_shape_rule, _dynamic_slice_dtype_rule, 'dynamic_slice',
_dynamic_slice_translation_rule)
ad.primitive_jvps[dynamic_slice_p] = _dynamic_slice_jvp
ad.primitive_transposes[dynamic_slice_p] = _dynamic_slice_transpose_rule
batching.primitive_batchers[dynamic_slice_p] = _dynamic_slice_batching_rule
def _dynamic_update_slice_shape_rule(operand, update, *start_indices, **kwargs):
if operand.ndim != update.ndim:
msg = ("dynamic_update_slice update must have the same rank as operand, "
"got update shape {} for operand shape {}.")
raise TypeError(msg.format(update.shape, operand.shape))
if operand.ndim != len(start_indices):
msg = ("dynamic_update_slice start_indices must have length equal to the "
"rank of operand, got indices {} for operand shape {}.")
raise TypeError(msg.format(start_indices, operand.shape))
if not onp.all(onp.less_equal(update.shape, operand.shape)):
msg = ("dynamic_update_slice update shape must be smaller than operand "
"shape, got update shape {} for operand shape {}.")
raise TypeError(msg.format(update.shape, operand.shape))
return operand.shape
def _dynamic_update_slice_dtype_rule(operand, update, *start_indices, **kwargs):
_check_same_dtypes("dynamic_update_slice", False, operand.dtype, update.dtype)
if any(i.dtype != start_indices[0].dtype or
not dtypes.issubdtype(i.dtype, onp.integer) for i in start_indices):
msg = ("index arguments to dynamic_update_slice must be integers of the "
"same type, got {}")
raise TypeError(msg.format(", ".join(i.dtype.name for i in start_indices)))
return operand.dtype
def _dynamic_update_slice_jvp(primals, tangents, update_shape):
operand, update = primals[:2]
start_indices = primals[2:]
g_operand, g_update = tangents[:2]
val_out = dynamic_update_slice(operand, update, start_indices)
if g_operand is ad_util.zero and g_update is ad_util.zero:
tangent_out = ad_util.zero
else:
g_operand = ad.instantiate_zeros(operand, g_operand)
g_update = ad.instantiate_zeros(update, g_update)
tangent_out = dynamic_update_slice(g_operand, g_update, start_indices)
return val_out, tangent_out
def _dynamic_update_slice_transpose_rule(t, operand, update, *start_indices,
**kwargs):
update_shape = kwargs["update_shape"]
assert all(x is not ad.undefined_primal for x in start_indices)
dus = dynamic_update_slice
ds = dynamic_slice
zeros = _zeros(t, shape=update_shape)
operand_t = dus(t, zeros, start_indices) if operand is ad.undefined_primal else None
update_t = ds(t, start_indices, update_shape) if update is ad.undefined_primal else None
return [operand_t, update_t] + [None] * len(start_indices)
def _dynamic_update_slice_translation_rule(c, operand, update, *start_indices,
**kwargs):
return c.DynamicUpdateSlice(operand, update, start_indices)
def _dynamic_update_slice_batching_rule(batched_args, batch_dims, update_shape):
# A dynamic update slice is a special case of scatter; we can delegate to the
# scatter batching rule.
# TODO(phawkins): consider removing dynamic_update_slice entirely and using
# scatter always.
operand, update = batched_args[:2]
operand_bdims, update_bdims = batch_dims[:2]
dims = tuple(range(len(update_shape)))
dnums = ScatterDimensionNumbers(update_window_dims=dims,
inserted_window_dims=(),
scatter_dims_to_operand_dims=dims)
index, index_bdim = _batch_dynamic_slice_indices(batched_args[2:],
batch_dims[2:])
return _scatter_batching_rule(
scatter,
(operand, index, update), (operand_bdims, index_bdim, update_bdims),
None, None, dnums, update_shape)
dynamic_update_slice_p = standard_primitive(
_dynamic_update_slice_shape_rule, _dynamic_update_slice_dtype_rule,
'dynamic_update_slice', _dynamic_update_slice_translation_rule)
ad.primitive_jvps[dynamic_update_slice_p] = _dynamic_update_slice_jvp
ad.primitive_transposes[dynamic_update_slice_p] = \
_dynamic_update_slice_transpose_rule
batching.primitive_batchers[dynamic_update_slice_p] = \
_dynamic_update_slice_batching_rule
class GatherDimensionNumbers(collections.namedtuple(
"GatherDimensionNumbers",
["offset_dims", "collapsed_slice_dims", "start_index_map"])):
"""
Describes the dimension number arguments to an `XLA's Gather operator
<https://www.tensorflow.org/xla/operation_semantics#gather>`_. See the XLA
documentation for more details of what the dimension numbers mean.
Args:
offset_dims: the set of dimensions in the `gather` output that offset into
an array sliced from `operand`. Must be a tuple of integers in ascending
order, each representing a dimension number of the output.
collapsed_slice_dims: the set of dimensions `i` in `operand` that have
`slice_sizes[i] == 1` and that should not have a corresponding dimension
in the output of the gather. Must be a tuple of integers in ascending
order.
start_index_map: for each dimension in `start_indices`, gives the
corresponding dimension in `operand` that is to be sliced. Must be a
tuple of integers with size equal to `start_indices.shape[-1]`.
Unlike XLA's `GatherDimensionNumbers` structure, `index_vector_dim` is
implicit; there is always an index vector dimension and it must always be the
last dimension. To gather scalar indices, add a trailing dimension of size 1.
"""
def _gather_dimensions_proto(indices_shape, dimension_numbers):
assert type(dimension_numbers) is GatherDimensionNumbers
proto = xla_client.GatherDimensionNumbers()
proto.offset_dims.extend(dimension_numbers.offset_dims)
proto.collapsed_slice_dims.extend(dimension_numbers.collapsed_slice_dims)
proto.start_index_map.extend(dimension_numbers.start_index_map)
assert indices_shape.rank() > 0
proto.index_vector_dim = indices_shape.rank() - 1
return proto
def _gather_dtype_rule(operand, start_indices, **kwargs):
if not dtypes.issubdtype(start_indices.dtype, onp.integer):
raise ValueError("start_indices must have an integer type")
return dtypes.canonicalize_dtype(operand.dtype)
def _gather_shape_rule(operand, start_indices, dimension_numbers, slice_sizes,
operand_shape):
assert operand.shape == operand_shape
if len(operand_shape) != len(slice_sizes):
msg = ("slice_sizes must have rank equal to the gather operand; "
"operand.shape={}, slice_sizes={}".format(operand_shape, slice_sizes))
raise ValueError(msg)
result_rank = len(dimension_numbers.offset_dims) + start_indices.ndim - 1
start_indices_shape = iter(start_indices.shape[:-1])
slice_sizes = iter(onp.delete(slice_sizes, dimension_numbers.collapsed_slice_dims))
return tuple(next(slice_sizes) if i in dimension_numbers.offset_dims
else next(start_indices_shape) for i in range(result_rank))
def _gather_translation_rule(c, operand, start_indices, dimension_numbers,
slice_sizes, operand_shape):
indices_shape = c.GetShape(start_indices)
return c.Gather(
operand, start_indices,
_gather_dimensions_proto(indices_shape, dimension_numbers), slice_sizes)
def _gather_jvp_rule(g, operand, start_indices, dimension_numbers, slice_sizes,
operand_shape):
return gather(g, start_indices, dimension_numbers, slice_sizes)
def _gather_transpose_rule(t, operand, start_indices, dimension_numbers,
slice_sizes, operand_shape):
assert operand is ad.undefined_primal
if t is ad_util.zero:
return [ad_util.zero, ad_util.zero]
zeros = full(operand_shape, tie_in(t, _zero(t)))
scatter_dnums = ScatterDimensionNumbers(
update_window_dims=dimension_numbers.offset_dims,
inserted_window_dims=dimension_numbers.collapsed_slice_dims,
scatter_dims_to_operand_dims=dimension_numbers.start_index_map)
return [scatter_add(zeros, start_indices, t, scatter_dnums), ad_util.zero]
def _gather_batching_rule(batched_args, batch_dims, dimension_numbers,
slice_sizes, operand_shape):
operand, start_indices = batched_args
operand_bdim, start_indices_bdim = batch_dims
if operand_bdim is not None and start_indices_bdim is None:
operand = batching.moveaxis(operand, operand_bdim, 0)
slice_sizes = (operand.shape[0],) + slice_sizes
offset_dims = (0,) + tuple(onp.add(1, dimension_numbers.offset_dims))
collapsed_slice_dims = tuple(onp.add(1, dimension_numbers.collapsed_slice_dims))
start_index_map = tuple(onp.add(1, dimension_numbers.start_index_map))
dnums = GatherDimensionNumbers(
offset_dims=offset_dims,
collapsed_slice_dims=collapsed_slice_dims,
start_index_map=start_index_map)
return gather(operand, start_indices, dimension_numbers=dnums,
slice_sizes=slice_sizes), 0
elif operand_bdim is None and start_indices_bdim is not None:
start_indices = batching.moveaxis(start_indices, start_indices_bdim, 0)
offset_dims = tuple(onp.add(1, dimension_numbers.offset_dims))
dnums = GatherDimensionNumbers(
offset_dims=offset_dims,
collapsed_slice_dims=dimension_numbers.collapsed_slice_dims,
start_index_map=dimension_numbers.start_index_map)
return gather(operand, start_indices, dimension_numbers=dnums,
slice_sizes=slice_sizes), 0
else:
# move our batch dimensions to the front to preserve sanity
operand = batching.moveaxis(operand, operand_bdim, 0)
start_indices = batching.moveaxis(start_indices, start_indices_bdim, 0)
# Example: user code had start_indices shape (3, 4, 5), and we have to deal
# with start_indices shape (7, 3, 4, 5). We transform that to a
# start_indices of shape (7, 3, 4, 6) where we concatenated an iota that
# counts along our batch dimension to the front of the ndindex.
count_shape = list(start_indices.shape)
count_shape[-1] = 1
counts = broadcasted_iota(start_indices.dtype, tuple(count_shape), 0)
start_indices = concatenate([counts, start_indices], len(count_shape) - 1)
slice_sizes = (1,) + slice_sizes
collapsed_slice_dims = (0,) + tuple(onp.add(1, dimension_numbers.collapsed_slice_dims))
offset_dims = tuple(onp.add(1, dimension_numbers.offset_dims))
start_index_map = (0,) + tuple(onp.add(1, dimension_numbers.start_index_map))
dnums = GatherDimensionNumbers(
offset_dims=offset_dims,
collapsed_slice_dims=collapsed_slice_dims,
start_index_map=start_index_map)
return gather(operand, start_indices, dimension_numbers=dnums,
slice_sizes=slice_sizes), 0
gather_p = standard_primitive(
_gather_shape_rule, _gather_dtype_rule, 'gather',
_gather_translation_rule)
ad.defjvp(gather_p, _gather_jvp_rule, None)
ad.primitive_transposes[gather_p] = _gather_transpose_rule
batching.primitive_batchers[gather_p] = _gather_batching_rule
class ScatterDimensionNumbers(collections.namedtuple(
"ScatterDimensionNumbers",
["update_window_dims", "inserted_window_dims",
"scatter_dims_to_operand_dims"])):
"""
Describes the dimension number arguments to an `XLA's Scatter operator
<https://www.tensorflow.org/xla/operation_semantics#scatter>`_. See the XLA
documentation for more details of what the dimension numbers mean.
Args:
update_window_dims: the set of dimensions in the `updates` that are window
dimensions. Must be a tuple of integers in ascending
order, each representing a dimension number.
inserted_window_dims: the set of size 1 window dimensions that must be inserted
into the shape of `updates`. Must be a tuple of integers in ascending
order, each representing a dimension number of the output. These are the
mirror image of `collapsed_slice_dims` in the case of `gather`.
scatter_dims_to_operand_dims: for each dimension in `scatter_indices`, gives
the corresponding dimension in `operand`. Must be a sequence of integers
with size equal to indices.shape[-1].
Unlike XLA's `ScatterDimensionNumbers` structure, `index_vector_dim` is
implicit; there is always an index vector dimension and it must always be the
last dimension. To scatter scalar indices, add a trailing dimension of size 1.
"""
def _scatter_dimensions_proto(indices_shape, dimension_numbers):
assert type(dimension_numbers) is ScatterDimensionNumbers
proto = xla_client.ScatterDimensionNumbers()
proto.update_window_dims.extend(dimension_numbers.update_window_dims)
proto.inserted_window_dims.extend(dimension_numbers.inserted_window_dims)
proto.scatter_dims_to_operand_dims.extend(
dimension_numbers.scatter_dims_to_operand_dims)
assert indices_shape.rank() > 0
proto.index_vector_dim = indices_shape.rank() - 1
return proto
def _scatter_dtype_rule(operand, scatter_indices, updates, **kwargs):
if not dtypes.issubdtype(scatter_indices.dtype, onp.integer):
raise ValueError("scatter_indices must have an integer type")
_check_same_dtypes("scatter", False, operand.dtype, updates.dtype)
return dtypes.canonicalize_dtype(operand.dtype)
def _scatter_shape_rule(operand, scatter_indices, updates, **kwargs):
return operand.shape
def _scatter_translation_rule(c, operand, scatter_indices, updates,
update_jaxpr, update_consts, dimension_numbers,
updates_shape):
dtype = c.GetShape(operand).numpy_dtype()
init_value = c.Constant(onp.array(0, dtype))
update_computation = _reduction_computation(
c, update_jaxpr, update_consts, init_value)
indices_shape = c.GetShape(scatter_indices)
return c.Scatter(operand, scatter_indices, updates, update_computation,
_scatter_dimensions_proto(indices_shape, dimension_numbers))
def _scatter_add_jvp(primals, tangents, update_jaxpr, update_consts,
dimension_numbers, updates_shape):
operand, scatter_indices, updates = primals
g_operand, g_scatter_indices, g_updates = tangents
val_out = scatter_add_p.bind(
operand, scatter_indices, updates, update_jaxpr=update_jaxpr,
update_consts=update_consts, dimension_numbers=dimension_numbers,
updates_shape=updates_shape)
if g_operand is ad_util.zero and g_updates is ad_util.zero:
tangent_out = ad_util.zero
else:
g_operand = ad.instantiate_zeros(operand, g_operand)
g_updates = ad.instantiate_zeros(updates, g_updates)
tangent_out = scatter_add_p.bind(
g_operand, scatter_indices, g_updates, update_jaxpr=update_jaxpr,
update_consts=update_consts, dimension_numbers=dimension_numbers,
updates_shape=updates_shape)
return val_out, tangent_out
def _scatter_add_transpose_rule(t, operand, scatter_indices, updates,
update_jaxpr, update_consts, dimension_numbers,
updates_shape):
assert scatter_indices is not ad.undefined_primal
if t is ad_util.zero:
return [ad_util.zero, None, ad_util.zero]
operand_t = update_t = None
if operand is ad.undefined_primal:
operand_t = t
if updates is ad.undefined_primal:
gather_dnums = GatherDimensionNumbers(
offset_dims=dimension_numbers.update_window_dims,
collapsed_slice_dims=dimension_numbers.inserted_window_dims,
start_index_map=dimension_numbers.scatter_dims_to_operand_dims)
slice_sizes = []
pos = 0
for i in xrange(len(t.shape)):
if i in dimension_numbers.inserted_window_dims:
slice_sizes.append(1)
else:
slice_sizes.append(updates_shape[dimension_numbers.update_window_dims[pos]])
pos += 1
update_t = gather(t, scatter_indices, dimension_numbers=gather_dnums,
slice_sizes=slice_sizes)
return [operand_t, None, update_t]
def _scatter_batching_rule(
scatter_op, batched_args, batch_dims, update_jaxpr, update_consts,
dimension_numbers, updates_shape):
operand, scatter_indices, updates = batched_args
operand_bdim, scatter_indices_bdim, updates_bdim = batch_dims
del update_jaxpr, update_consts, updates_shape # Unused.
# move the operand batch dim to the front if it is not None, otherwise create
# it at the front (so that we can scatter into it)
size = next(x.shape[ax] for x, ax in zip(batched_args, batch_dims)
if ax is not None)
operand = batching.bdim_at_front(operand, operand_bdim, size)
operand_bdim = 0
updates = batching.bdim_at_front(updates, updates_bdim, size)
if scatter_indices_bdim is None:
inserted_window_dims = tuple(onp.add(1, dimension_numbers.inserted_window_dims))
update_window_dims = (0,) + tuple(onp.add(1, dimension_numbers.update_window_dims))
scatter_dims_to_operand_dims = tuple(onp.add(1, dimension_numbers.scatter_dims_to_operand_dims))
dnums = ScatterDimensionNumbers(
update_window_dims=update_window_dims,
inserted_window_dims=inserted_window_dims,
scatter_dims_to_operand_dims=scatter_dims_to_operand_dims)
return scatter_op(operand, scatter_indices, updates, dnums), 0
# see the third case in _gather_batching_rule for comparison and comments
scatter_indices = batching.bdim_at_front(
scatter_indices, scatter_indices_bdim, size)
count_shape = list(scatter_indices.shape)
count_shape[-1] = 1
counts = broadcasted_iota(scatter_indices.dtype, tuple(count_shape), 0)
scatter_indices = concatenate([counts, scatter_indices],
len(count_shape) - 1)
update_window_dims = tuple(onp.add(1, dimension_numbers.update_window_dims))
inserted_window_dims = (0,) + tuple(onp.add(1, dimension_numbers.inserted_window_dims))
scatter_dims_to_operand_dims = (0,) + tuple(onp.add(1, dimension_numbers.scatter_dims_to_operand_dims))
dnums = ScatterDimensionNumbers(
update_window_dims=update_window_dims,
inserted_window_dims=inserted_window_dims,
scatter_dims_to_operand_dims=scatter_dims_to_operand_dims)
return scatter_op(operand, scatter_indices, updates, dnums), 0
scatter_add_p = standard_primitive(
_scatter_shape_rule, _scatter_dtype_rule, 'scatter-add',
_scatter_translation_rule)
ad.primitive_jvps[scatter_add_p] = _scatter_add_jvp
ad.primitive_transposes[scatter_add_p] = _scatter_add_transpose_rule
batching.primitive_batchers[scatter_add_p] = (
partial(_scatter_batching_rule, scatter_add))
# TODO(jlebar): Add derivatives.
scatter_min_p = standard_primitive(
_scatter_shape_rule, _scatter_dtype_rule, 'scatter-min',
_scatter_translation_rule)
batching.primitive_batchers[scatter_min_p] = (
partial(_scatter_batching_rule, scatter_min))
# TODO(jlebar): Add derivatives.
scatter_max_p = standard_primitive(
_scatter_shape_rule, _scatter_dtype_rule, 'scatter-max',
_scatter_translation_rule)
batching.primitive_batchers[scatter_max_p] = (
partial(_scatter_batching_rule, scatter_max))
def _scatter_jvp(primals, tangents, update_jaxpr, update_consts,
dimension_numbers, updates_shape):
operand, scatter_indices, updates = primals
g_operand, g_scatter_indices, g_updates = tangents
dnums = dimension_numbers
if g_operand is ad_util.zero and g_updates is ad_util.zero:
val_out = scatter_p.bind(
operand, scatter_indices, updates, update_jaxpr=update_jaxpr,
update_consts=update_consts, dimension_numbers=dnums,
updates_shape=updates_shape)
tangent_out = ad_util.zero
return val_out, tangent_out
g_operand = ad.instantiate_zeros(operand, g_operand)
g_updates = ad.instantiate_zeros(updates, g_updates)
# If there are overlapping indices in the scatter, it is unspecified which
# update "wins". So we use the following perhaps surprising scheme:
# a) attach a positive ID to each update in updates, forming (value, id) pairs
# (using a new array dimension because scatter doesn't actually support
# pairs).
# b) perform the scatter, yielding (value, id) updates, which we split apart.
# c) perform the inverse gather on the ids (similar to
# _scatter_add_transpose), and use it to build a mask for the tangent of
# `updates`.
# d) perform a scatter-add on the masked JVP values. A benefit of using
# scatter-add here is that we don't need a `scatter` transpose rule.
# a) add unique positive IDs (iotas) to the updates, and zeros to the operand.
operand_shape = operand.shape
updates_shape = updates.shape
updates_dtype = _dtype(updates)
new_operand = reshape(operand, (1,) + operand_shape)
new_operand = pad(new_operand, _zero(operand),
((0, 1, 0),) + tuple((0, 0, 0) for _ in operand_shape))
ids_shape = onp.array(updates_shape)
ids_shape[dnums.update_window_dims,] = 1
num_ids = onp.prod(ids_shape)
update_ids = add(reshape(iota(updates_dtype, num_ids), ids_shape),
_ones(updates))
# TODO(phawkins): there is a potential bug here if the number of updates
# is large enough to overflow the number of mantissa bits in a float so IDs
# end up colliding. We could also utilize the exponent and sign bits, with a
# little more work.
assert num_ids < (2 ** dtypes.finfo(updates_dtype).nmant)
updates = reshape(updates, (1,) + updates_shape)
reshaped_update_ids = reshape(update_ids, (1,) + updates_shape)
updates_and_ids = concatenate((updates, reshaped_update_ids), 0)
new_dnums = ScatterDimensionNumbers(
update_window_dims=(0,) + tuple(d + 1 for d in dnums.update_window_dims),
inserted_window_dims=tuple(d + 1 for d in dnums.inserted_window_dims),
scatter_dims_to_operand_dims=tuple(d + 1 for d in dnums.scatter_dims_to_operand_dims))
outputs = scatter_p.bind(
new_operand, scatter_indices, updates_and_ids, update_jaxpr=update_jaxpr,
update_consts=update_consts, dimension_numbers=new_dnums,
updates_shape=updates_shape)
val_out = index_in_dim(outputs, 0, keepdims=False)
scattered_ids = index_in_dim(outputs, 1, keepdims=False)
# b) compute the inverse gather that "undoes" the scatter on the id values.
gather_dnums = GatherDimensionNumbers(
offset_dims=dnums.update_window_dims,
collapsed_slice_dims=dnums.inserted_window_dims,
start_index_map=dnums.scatter_dims_to_operand_dims)
slice_sizes = []
pos = 0
for i in xrange(len(scattered_ids.shape)):
if i in dnums.inserted_window_dims:
slice_sizes.append(1)
else:
slice_sizes.append(updates_shape[dnums.update_window_dims[pos]])
pos += 1
gathered_update_ids = gather(scattered_ids, scatter_indices,
dimension_numbers=gather_dnums,
slice_sizes=slice_sizes)
# c) mask off input JVP elements that do not correspond to a primal output.
masked_g_operand = select(eq(scattered_ids, _zeros(scattered_ids)),
g_operand, _zeros(g_operand))
masked_g_updates = select(eq(update_ids, gathered_update_ids),
g_updates, _zeros(g_updates))
# d) perform a scatter-add to compute the tangent output.
tangent_out = scatter_add(masked_g_operand, scatter_indices, masked_g_updates,
dimension_numbers=dnums)
return val_out, tangent_out
scatter_p = standard_primitive(
_scatter_shape_rule, _scatter_dtype_rule, 'scatter',
_scatter_translation_rule)
ad.primitive_jvps[scatter_p] = _scatter_jvp
batching.primitive_batchers[scatter_p] = (
partial(_scatter_batching_rule, scatter))
def _reduce_shape_rule(operand, init_value, computation, jaxpr, consts, dimensions):
return tuple(onp.delete(operand.shape, dimensions))
def _reduce_translation_rule(c, operand, init_value, computation, jaxpr, consts, dimensions):
xla_computation = _reduction_computation(c, jaxpr, consts, init_value)
return c.Reduce(operand, init_value, xla_computation, dimensions)
def _reduce_batch_rule(batched_args, batch_dims, computation, jaxpr, consts, dimensions):
operand, init_value = batched_args
operand_bdim, init_value_bdim = batch_dims
if init_value_bdim is None:
assert operand_bdim is not None
new_dimensions = [d + bool(d >= operand_bdim) for d in dimensions]
new_operand_bdim = operand_bdim - int(onp.sum(onp.less(dimensions, operand_bdim)))
return reduce(operand, init_value, computation, new_dimensions), new_operand_bdim
else:
raise NotImplementedError # loop and stack
def _reduction_computation(c, jaxpr, consts, init_value):
shape = c.GetShape(init_value)
axis_env = xla.AxisEnv() # no parallel primitives inside reductions
subc = xla_bridge.make_computation_builder("reduction_computation")
consts = [subc.ParameterWithShape(const) for const in consts]
args = [subc.ParameterWithShape(shape), subc.ParameterWithShape(shape)]
out, = xla.jaxpr_subcomp(subc, jaxpr, None, axis_env, consts, (), *args)
return subc.Build(out)
def _masking_defreducer(prim, identity):
masking.shape_rules[prim] = _reducer_polymorphic_shape_rule
masking.masking_rules[prim] = partial(_reducer_masking_rule, prim, identity)
def _reducer_polymorphic_shape_rule(shape_exprs, axes, **unused_params):
shape_expr, = shape_exprs
return ShapeExpr([d for i, d in enumerate(shape_expr) if i not in axes])
def _reducer_masking_rule(prim, identity, padded_vals, logical_shapes,
axes, input_shape):
del input_shape # Unused.
(padded_val,), (logical_shape,) = padded_vals, logical_shapes
padded_shape = masking.padded_shape_as_value(padded_val.shape)
masks = [broadcasted_iota(onp.int32, padded_shape, i) < d
for i, d in enumerate(logical_shape) if i in axes]
mask = _reduce(operator.and_, masks)
masked_val = select(mask, padded_val, identity(padded_shape, padded_val.dtype))
return prim.bind(masked_val, axes=axes, input_shape=padded_shape)
reduce_p = standard_primitive(_reduce_shape_rule, _input_dtype, 'reduce',
_reduce_translation_rule)
batching.primitive_batchers[reduce_p] = _reduce_batch_rule
def _reduce_number_dtype_rule(name, operand, *args, **kw):
if not dtypes.issubdtype(operand.dtype, onp.number):
raise TypeError("{} does not accept dtype {}. Accepted dtypes are subtypes "
"of number.".format(name, onp.dtype(operand.dtype).name))
return dtypes.canonicalize_dtype(operand.dtype)
def _reduce_sum_shape_rule(operand, axes, input_shape):
assert operand.shape == input_shape, ('{} != {}'
.format(operand.shape, input_shape))
return tuple(onp.delete(operand.shape, axes))
def _reduce_sum_translation_rule(c, operand, axes, input_shape):
dtype = c.GetShape(operand).numpy_dtype()
scalar = ShapedArray((), dtype)
return c.Reduce(operand, c.Constant(onp.array(0, dtype)),
xla.primitive_subcomputation(add_p, scalar, scalar),
axes)
def _reduce_sum_transpose_rule(cotangent, input_shape, axes):
broadcast_dimensions = tuple(onp.delete(onp.arange(len(input_shape)), axes))
result = broadcast_in_dim(cotangent, input_shape, broadcast_dimensions)
assert result.shape == input_shape
return [result]
reduce_sum_p = standard_primitive(
_reduce_sum_shape_rule, partial(_reduce_number_dtype_rule, 'reduce_sum'),
'reduce_sum', _reduce_sum_translation_rule)
ad.deflinear(reduce_sum_p, _reduce_sum_transpose_rule)
batching.defreducer(reduce_sum_p)
_masking_defreducer(reduce_sum_p,
lambda shape, dtype: onp.broadcast_to(onp.array(0, dtype), shape))
def _reduce_prod_shape_rule(operand, axes):
return tuple(onp.delete(operand.shape, axes))
def _reduce_prod_translation_rule(c, operand, axes):
dtype = c.GetShape(operand).numpy_dtype()
scalar = ShapedArray((), dtype)
return c.Reduce(operand, c.Constant(onp.array(1, dtype)),
xla.primitive_subcomputation(mul_p, scalar, scalar), axes)
def _reduce_prod_jvp_rule(tangent, operand, axes):
input_shape = onp.array(operand.shape)
n = onp.prod(input_shape[list(axes)])
non_axes = onp.delete(onp.arange(len(input_shape)), axes)
# Move the reduced axes to the front, and flatten them to 1D.
permutation = axes + tuple(non_axes)
new_shape = (n,) + tuple(input_shape[non_axes])
operand = reshape(operand, new_shape, permutation)
tangent = reshape(tangent, new_shape, permutation)
one = _const(operand, 1)
window_dims = [n] + [1] * len(non_axes)
window_strides = [1] * (len(non_axes) + 1)
# Form the partial products of all elements to the left and right of each
# element.
left_padding = [(n, -1, 0)] + [(0, 0, 0)] * len(non_axes)
right_padding = [(-1, n, 0)] + [(0, 0, 0)] * len(non_axes)
left_products = _reduce_window_prod(pad(operand, one, left_padding),
window_dims, window_strides,
xla_client.PaddingType.VALID)
right_products = _reduce_window_prod(pad(operand, one, right_padding),
window_dims, window_strides,
xla_client.PaddingType.VALID)
# Multiply partial products with the tangents and sum.
return _reduce_sum(mul(tangent, mul(left_products, right_products)), (0,))
reduce_prod_p = standard_primitive(
_reduce_prod_shape_rule, partial(_reduce_number_dtype_rule, 'reduce_prod'),
'reduce_prod', _reduce_prod_translation_rule)
ad.defjvp(reduce_prod_p, _reduce_prod_jvp_rule)
batching.defreducer(reduce_prod_p)
def _reduce_chooser_shape_rule(operand, axes):
return tuple(onp.delete(operand.shape, axes))
def _reduce_chooser_translation_rule(prim, identity, c, operand, axes):
dtype = c.GetShape(operand).numpy_dtype()
scalar = ShapedArray((), dtype)
return c.Reduce(operand, c.Constant(identity(dtype)),
xla.primitive_subcomputation(prim, scalar, scalar), axes)
def _reduce_chooser_jvp_rule(g, ans, operand, axes):
# TODO(mattjj): an alternative is to use variadic reduce to compute the chosen
# locations in a single pass (rather than comparing equality) and use a
# gather, and/or even push along the chosen elements of g (b/112040122)
shape = [1 if i in axes else d for i, d in enumerate(operand.shape)]
location_indicators = convert_element_type(
_eq_meet(operand, reshape(ans, shape)), g.dtype)
counts = _reduce_sum(location_indicators, axes)
return div(_reduce_sum(mul(g, location_indicators), axes), counts)
_reduce_max_translation_rule = partial(_reduce_chooser_translation_rule, max_p,
_get_max_identity)
reduce_max_p = standard_primitive(_reduce_chooser_shape_rule, _input_dtype,
'reduce_max', _reduce_max_translation_rule)
ad.defjvp2(reduce_max_p, _reduce_chooser_jvp_rule)
batching.defreducer(reduce_max_p)
_reduce_min_translation_rule = partial(
_reduce_chooser_translation_rule, min_p, _get_min_identity)
reduce_min_p = standard_primitive(_reduce_chooser_shape_rule, _input_dtype,
'reduce_min', _reduce_min_translation_rule)
ad.defjvp2(reduce_min_p, _reduce_chooser_jvp_rule)
batching.defreducer(reduce_min_p)
def _reduce_logical_shape_rule(operand, axes):
if operand.dtype != onp.bool_:
msg = "logical reduction requires operand dtype bool, got {}."
raise TypeError(msg.format(operand.dtype))
return tuple(onp.delete(operand.shape, axes))
def _reduce_logical_translation_rule(prim, identity, c, operand, axes):
scalar = ShapedArray((), onp.bool_)
return c.Reduce(operand, c.Constant(identity(onp.bool_)),
xla.primitive_subcomputation(prim, scalar, scalar), axes)
_reduce_or_translation_rule = partial(_reduce_logical_translation_rule,
or_p, _get_max_identity)
reduce_or_p = standard_primitive(_reduce_logical_shape_rule, _fixed_dtype(onp.bool_),
'reduce_or', _reduce_or_translation_rule)
batching.defreducer(reduce_or_p)
_reduce_and_translation_rule = partial(_reduce_logical_translation_rule,
and_p, _get_min_identity)
reduce_and_p = standard_primitive(_reduce_logical_shape_rule, _fixed_dtype(onp.bool_),
'reduce_and', _reduce_and_translation_rule)
batching.defreducer(reduce_and_p)
def _reduce_window_shape_rule(operand, init_value, jaxpr, consts,
window_dimensions, window_strides, padding):
if operand.dtype != init_value.dtype:
msg = ("reduce_window got inconsistent dtypes for operand and init_value: "
" got operand dtype {} and init_value dtype {}.")
raise TypeError(msg.format(operand.dtype, init_value.dtype))
return _common_reduce_window_shape_rule(operand, window_dimensions,
window_strides, padding)
def _reduce_window_translation_rule(c, operand, init_value, jaxpr, consts,
window_dimensions, window_strides, padding):
xla_computation = _reduction_computation(c, jaxpr, consts, init_value)
return c.ReduceWindow(operand, init_value, xla_computation, window_dimensions,
window_strides, padding)
def _generic_reduce_window_batch_rule(
batched_args, batch_dims, jaxpr, consts, window_dimensions, window_strides,
padding):
operand, init = batched_args
bdim, init_bdim = batch_dims
if init_bdim is not None:
raise NotImplementedError("reduce_window batching is not implemented for "
"initial values")
def reduce_window(x, window_dimensions, window_strides, padding):
return reduce_window_p.bind(
x, init, jaxpr=jaxpr, consts=consts, window_dimensions=window_dimensions,
window_strides=window_strides, padding=padding)
return _reduce_window_batch_rule(reduce_window, (operand,), (bdim,),
window_dimensions, window_strides, padding)
reduce_window_p = standard_primitive(
_reduce_window_shape_rule, _input_dtype, 'reduce_window',
_reduce_window_translation_rule)
batching.primitive_batchers[reduce_window_p] = _generic_reduce_window_batch_rule
def _reduce_window_sum_shape_rule(operand, window_dimensions, window_strides,
padding, input_shape):
return _common_reduce_window_shape_rule(operand, window_dimensions,
window_strides, padding)
def _reduce_window_sum_translation_rule(c, operand, window_dimensions,
window_strides, padding, input_shape):
dtype = c.GetShape(operand).numpy_dtype()
scalar = ShapedArray((), dtype)
return c.ReduceWindow(operand, c.Constant(onp.array(0, dtype)),
xla.primitive_subcomputation(add_p, scalar, scalar),
window_dimensions, window_strides, padding)
def _reduce_window_sum_transpose_rule(cotangent, window_dimensions,
window_strides, padding, input_shape):
in_pads = padtype_to_pads(input_shape, window_dimensions, window_strides,
padding)
ones = [1] * len(input_shape)
pads = _conv_general_vjp_lhs_padding(
input_shape, window_dimensions, window_strides, cotangent.shape, in_pads,
ones, ones)
padding_config = [(lo, hi, stride - 1)
for (lo, hi), stride in zip(pads, window_strides)]
pad_cotangent = pad(cotangent, _zero(cotangent), padding_config)
result = _reduce_window_sum(pad_cotangent, window_dimensions, ones,
xla_client.PaddingType.VALID)
assert result.shape == input_shape
return [result]
def _reduce_window_batch_rule(
reduce_window, batched_args, bdims, window_dimensions, window_strides,
padding, input_shape=None):
operand, = batched_args
bdim, = bdims
if bdim is not None:
window_dimensions = \
window_dimensions[:bdim] + (1,) + window_dimensions[bdim:]
window_strides = window_strides[:bdim] + (1,) + window_strides[bdim:]
operand = reduce_window(
operand, window_dimensions, window_strides, padding)
return operand, bdim
reduce_window_sum_p = standard_primitive(
_reduce_window_sum_shape_rule, _input_dtype, 'reduce_window_sum',
_reduce_window_sum_translation_rule)
ad.deflinear(reduce_window_sum_p, _reduce_window_sum_transpose_rule)
batching.primitive_batchers[reduce_window_sum_p] = partial(
_reduce_window_batch_rule, _reduce_window_sum)
def _reduce_window_chooser_translation_rule(
prim, identity, c, operand, window_dimensions, window_strides, padding):
dtype = c.GetShape(operand).numpy_dtype()
scalar = ShapedArray((), dtype)
return c.ReduceWindow(operand, c.Constant(identity(dtype)),
xla.primitive_subcomputation(prim, scalar, scalar),
window_dimensions, window_strides, padding)
def _reduce_window_chooser_jvp_rule(prim, g, operand, window_dimensions,
window_strides, padding):
assert prim is max_p or prim is min_p
select_prim = ge_p if prim is max_p else le_p
return _select_and_gather_add(g, operand, select_prim, window_dimensions,
window_strides, padding)
def _common_reduce_window_shape_rule(operand, window_dimensions, window_strides,
padding):
_check_shapelike("reduce_window", "window_dimensions", window_dimensions)
_check_shapelike("reduce_window", "window_strides", window_strides)
if operand.ndim != len(window_dimensions):
msg = ("reduce_window got the wrong number of window_dimensions for "
"operand: got operand shape {} with window_dimensions {}.")
raise TypeError(msg.format(operand.shape, window_dimensions))
if len(window_strides) != len(window_dimensions):
msg = ("reduce_window got inconsistent window_strides and "
"window_dimensions: got window_strides {} and window_dimensions {}.")
raise TypeError(msg.format(window_strides, window_dimensions))
return reduce_window_shape_tuple(operand.shape, window_dimensions,
window_strides, padding)
def reduce_window_shape_tuple(operand_shape, window_dimensions, window_strides,
padding):
pads = padtype_to_pads(operand_shape, window_dimensions, window_strides, padding)
operand_padded = onp.add(operand_shape, onp.add(*zip(*pads)))
t = onp.floor_divide(
onp.subtract(operand_padded, window_dimensions), window_strides) + 1
return tuple(t)
_reduce_window_max_translation_rule = partial(
_reduce_window_chooser_translation_rule, max_p, _get_max_identity)
reduce_window_max_p = standard_primitive(
_common_reduce_window_shape_rule, _input_dtype, 'reduce_window_max',
_reduce_window_max_translation_rule)
ad.defjvp(reduce_window_max_p, partial(_reduce_window_chooser_jvp_rule, max_p))
batching.primitive_batchers[reduce_window_max_p] = partial(
_reduce_window_batch_rule, _reduce_window_max)
_reduce_window_min_translation_rule = partial(
_reduce_window_chooser_translation_rule, min_p, _get_min_identity)
reduce_window_min_p = standard_primitive(
_common_reduce_window_shape_rule, _input_dtype, 'reduce_window_min',
_reduce_window_min_translation_rule)
ad.defjvp(reduce_window_min_p, partial(_reduce_window_chooser_jvp_rule, min_p))
_reduce_window_min_batch_rule = partial(_reduce_window_batch_rule,
_reduce_window_min)
batching.primitive_batchers[reduce_window_min_p] = partial(
_reduce_window_batch_rule, _reduce_window_min)
def _select_and_scatter_shape_rule(
operand, source, init_value, select_jaxpr, select_consts, scatter_jaxpr,
scatter_consts, window_dimensions, window_strides, padding):
_check_shapelike("select_and_scatter", "window_dimensions", window_dimensions)
_check_shapelike("select_and_scatter", "window_strides", window_strides)
if len(window_dimensions) != len(window_strides):
msg = ("select_and_scatter got inconsistent window_strides and "
"window_dimensions: got window_strides {} and window_dimensions {}.")
raise TypeError(msg.format(window_strides, window_dimensions))
return operand.shape
def _select_and_scatter_translation(
c, operand, source, init_value, select_jaxpr, select_consts, scatter_jaxpr,
scatter_consts, window_dimensions, window_strides, padding):
select = _reduction_computation(c, select_jaxpr, select_consts, init_value)
scatter = _reduction_computation(c, scatter_jaxpr, scatter_consts, init_value)
return c.SelectAndScatter(operand, select, window_dimensions, window_strides,
padding, source, init_value, scatter)
select_and_scatter_p = standard_primitive(
_select_and_scatter_shape_rule, _input_dtype, 'select_and_scatter',
_select_and_scatter_translation)
def _select_and_scatter_add_shape_rule(
source, operand, select_prim, window_dimensions, window_strides, padding):
return operand.shape
def _select_and_scatter_add_translation(
c, source, operand, select_prim, window_dimensions, window_strides,
padding):
dtype = c.GetShape(operand).numpy_dtype()
scalar = ShapedArray((), dtype)
select = xla.primitive_subcomputation(select_prim, scalar, scalar)
scatter = xla.primitive_subcomputation(add_p, scalar, scalar)
zero = c.Constant(onp.array(0, dtype))
return c.SelectAndScatter(operand, select, window_dimensions, window_strides,
padding, source, zero, scatter)
def _select_and_scatter_add_jvp(
primals, tangents, select_prim, window_dimensions, window_strides,
padding):
source, operand = primals
g_source, g_operand = tangents
val_out = _select_and_scatter_add(
source, operand, select_prim, window_dimensions, window_strides,
padding)
del g_operand
if g_source is ad_util.zero:
tangent_out = ad_util.zero
else:
tangent_out = _select_and_scatter_add(
g_source, operand, select_prim, window_dimensions,
window_strides, padding)
return val_out, tangent_out
def _select_and_scatter_add_transpose(
t, source, operand, select_prim, window_dimensions, window_strides,
padding):
assert source is ad.undefined_primal and operand is not ad.undefined_primal
source_t = _select_and_gather_add(t, operand, select_prim, window_dimensions,
window_strides, padding)
return [source_t, None]
def _select_and_scatter_add_batch_rule(batched_args, batch_dims, **kwargs):
source, operand = batched_args
s_bdims, o_bdims = batch_dims
if s_bdims is not None and o_bdims is not None:
#TODO(#212): use a map construct instead of unrolling.
source = batching.moveaxis(source, s_bdims, 0)
operand = batching.moveaxis(operand, o_bdims, 0)
outputs = [
_select_and_scatter_add(s, o, **kwargs) for s, o in zip(source, operand)]
outputs = [reshape(out, (1,) + out.shape) for out in outputs]
outputs = concatenate(outputs, 0)
return outputs, 0
elif s_bdims is not None:
#TODO(#212): use a map construct instead of unrolling.
source = batching.moveaxis(source, s_bdims, 0)
outputs = [
_select_and_scatter_add(s, operand, **kwargs) for s in source]
outputs = [reshape(out, (1,) + out.shape) for out in outputs]
outputs = concatenate(outputs, 0)
return outputs, 0
elif o_bdims is not None:
#TODO(#212): use a map construct instead of unrolling.
operand = batching.moveaxis(operand, o_bdims, 0)
outputs = [
_select_and_scatter_add(source, o, **kwargs) for o in operand]
outputs = [reshape(out, (1,) + out.shape) for out in outputs]
outputs = concatenate(outputs, 0)
return outputs, 0
select_and_scatter_add_p = standard_primitive(
_select_and_scatter_add_shape_rule, _input_dtype, 'select_and_scatter_add',
_select_and_scatter_add_translation)
ad.primitive_transposes[select_and_scatter_add_p] = \
_select_and_scatter_add_transpose
ad.primitive_jvps[select_and_scatter_add_p] = _select_and_scatter_add_jvp
batching.primitive_batchers[select_and_scatter_add_p] = \
_select_and_scatter_add_batch_rule
def _select_and_gather_add_shape_rule(
tangents, operand, select_prim, window_dimensions, window_strides, padding):
if tangents.shape != operand.shape:
msg = ("select_and_gather_add tangents and operand shapes must match, "
"got {} and {}.")
raise TypeError(msg.format(tangents.shape, operand.shape))
return _common_reduce_window_shape_rule(operand, window_dimensions,
window_strides, padding)
_UINT_DTYPES = {
16: onp.uint16,
32: onp.uint32,
64: onp.uint64,
}
def _select_and_gather_add_translation(
c, tangents, operand, select_prim, window_dimensions, window_strides,
padding, max_bits=64):
shape = c.GetShape(operand)
dtype = shape.numpy_dtype()
etype = shape.xla_element_type()
nbits = dtypes.finfo(dtype).bits
assert nbits <= max_bits
double_word_reduction = nbits * 2 <= max_bits
const = lambda c, dtype, x: c.Constant(onp.array(x, dtype=dtype),
canonicalize_types=False)
if double_word_reduction:
# TODO(b/73062247): XLA doesn't yet implement ReduceWindow on tuples, so
# we implement a pair-wise ReduceWindow by packing two k-bit values into
# 2k-bit unsigned integer using bit tricks.
word_dtype = _UINT_DTYPES[nbits]
double_word_dtype = _UINT_DTYPES[nbits * 2]
word_type = xla_client.dtype_to_etype(word_dtype)
double_word_type = xla_client.dtype_to_etype(double_word_dtype)
# Packs two values into a tuple.
def pack(a, b):
a = c.BitcastConvertType(a, word_type)
b = c.BitcastConvertType(b, word_type)
a = c.ConvertElementType(a, double_word_type)
b = c.ConvertElementType(b, double_word_type)
a = c.ShiftLeft(a, const(c, double_word_dtype, nbits))
return c.Or(a, b)
# Unpacks the first element of a tuple.
def fst(c, t):
st = c.ShiftRightLogical(t, const(c, double_word_dtype, nbits))
return c.BitcastConvertType(c.ConvertElementType(st, word_type), etype)
# Unpacks the second element of a tuple.
def snd(t):
return c.BitcastConvertType(c.ConvertElementType(t, word_type), etype)
else:
# The double-word trick above only works if we have a sufficiently large
# type. As an alternative, we can pack two half words into a single word,
# at the cost of precision.
# TODO(b/73062247): add support for tuple reductions and remove this case.
warnings.warn("Using reduced precision for gradient of reduce-window "
"min/max operator to work around missing XLA support for "
"pair-reductions. This is likely from a second or "
"higher derivative of a max-pooling operation.")
r_nbits = nbits // 2
# Drop/round the bottom mantissa bits.
nexp = dtypes.finfo(dtype).nexp
nmant = r_nbits - nexp - 1
double_word_dtype = word_dtype = _UINT_DTYPES[nbits]
word_type = xla_client.dtype_to_etype(word_dtype)
# Packs two values into a tuple.
def pack(a, b):
a = c.ReducePrecision(a, exponent_bits=nexp, mantissa_bits=nmant)
b = c.ReducePrecision(b, exponent_bits=nexp, mantissa_bits=nmant)
a = c.BitcastConvertType(a, word_type)
b = c.BitcastConvertType(b, word_type)
b = c.ShiftRightLogical(b, const(c, word_dtype, r_nbits))
return c.Or(a, b)
# Unpacks the first element of a tuple.
def fst(c, t):
st = c.And(t, const(c, word_dtype, ((1 << r_nbits) - 1) << r_nbits))
return c.BitcastConvertType(st, etype)
# Unpacks the second element of a tuple.
def snd(t):
return c.BitcastConvertType(c.ShiftLeft(t, const(c, word_dtype, r_nbits)),
etype)
def reducer():
c = xla_bridge.make_computation_builder("select_and_gather_pair_reducer")
x = c.ParameterWithShape(
xla_client.Shape.array_shape(onp.dtype(double_word_dtype), ()))
y = c.ParameterWithShape(
xla_client.Shape.array_shape(onp.dtype(double_word_dtype), ()))
assert select_prim is ge_p or select_prim is le_p
which = c.Ge if select_prim is ge_p else c.Le
c.Select(which(fst(c, x), fst(c, y)), x, y)
return c.Build()
assert select_prim is ge_p or select_prim is le_p, select_prim
init = -onp.inf if select_prim is ge_p else onp.inf
out = c.ReduceWindow(pack(operand, tangents),
pack(const(c, dtype, init), const(c, dtype, 0)),
reducer(), window_dimensions, window_strides,
padding)
return snd(out)
def _select_and_gather_add_jvp(
primals, tangents, select_prim, window_dimensions, window_strides,
padding):
source, operand = primals
g_source, g_operand = tangents
val_out = _select_and_gather_add(
source, operand, select_prim, window_dimensions, window_strides,
padding)
del g_operand
if g_source is ad_util.zero:
tangent_out = ad_util.zero
else:
tangent_out = _select_and_gather_add(
g_source, operand, select_prim, window_dimensions,
window_strides, padding)
return val_out, tangent_out
def _select_and_gather_add_transpose(
t, tangents, operand, select_prim, window_dimensions, window_strides,
padding):
assert tangents is ad.undefined_primal and operand is not ad.undefined_primal
result = _select_and_scatter_add(t, operand, select_prim, window_dimensions,
window_strides, padding)
return [result, None]
def _select_and_gather_add_batching_rule(
batched_args, batch_dims, select_prim, window_dimensions, window_strides,
padding):
t, x = batched_args
t_bdim, x_bdim = batch_dims
size = next(a.shape[bdim] for a, bdim in zip(batched_args, batch_dims)
if bdim is not None)
t = batching.bdim_at_front(t, t_bdim, size)
x = batching.bdim_at_front(x, x_bdim, size)
window_dimensions = (1,) + window_dimensions
window_strides = (1,) + window_strides
out = _select_and_gather_add(t, x, select_prim, window_dimensions,
window_strides, padding)
return (out, 0)
select_and_gather_add_p = standard_primitive(
_select_and_gather_add_shape_rule, _input_dtype, 'select_and_gather_add',
_select_and_gather_add_translation)
ad.primitive_jvps[select_and_gather_add_p] = _select_and_gather_add_jvp
ad.primitive_transposes[select_and_gather_add_p] = \
_select_and_gather_add_transpose
batching.primitive_batchers[select_and_gather_add_p] = \
_select_and_gather_add_batching_rule
xla.backend_specific_translations['tpu'][select_and_gather_add_p] = partial(
_select_and_gather_add_translation,
max_bits=32)
sort_shape = lambda operand, dimension: operand.shape
def _sort_jvp_rule(g, operand, dimension):
_, g_out = sort_key_val(operand, g, dimension)
return g_out
def _sort_batch_rule(batched_args, batch_dims, dimension):
operand, = batched_args
bdim, = batch_dims
dimension = dimension % (operand.ndim - 1)
new_dimension = dimension + (bdim <= dimension)
return sort(operand, dimension=new_dimension), bdim
sort_p = standard_primitive(sort_shape, _input_dtype, 'sort')
ad.defjvp(sort_p, _sort_jvp_rule)
batching.primitive_batchers[sort_p] = _sort_batch_rule
def _sort_key_val_abstract_eval(keys, values, dimension):
return raise_to_shaped(keys), raise_to_shaped(values)
def _sort_key_val_jvp(primals, tangents, dimension):
# NOTE(mattjj): this re-sorts three times, but if we had a variadic
# sort_key_val, or if we could apply a fixed permutation efficiently, we could
# implement this jvp rule with a single sort. The apply_permutation primitive
# would make the jvp (and corresponding transpose rule) faster and easier.
# This would also be cleaner if we didn't get the sorted keys out.
# TODO(mattjj): make sort_key_val variadic, no sorted keys out by default
keys, values = primals
keys_tangents, values_tangents = tangents
val_out = sort_key_val(keys, values, dimension)
if keys_tangents is ad_util.zero:
keys_tangents_out = ad_util.zero
else:
keys_tangents_out = _sort_jvp_rule(keys_tangents, keys, dimension)
if values_tangents is ad_util.zero:
values_tangents_out = ad_util.zero
else:
values_tangents_out = _sort_jvp_rule(values_tangents, keys, dimension)
tangents_out = keys_tangents_out, values_tangents_out
return val_out, tangents_out
def _sort_key_val_transpose_rule(t, keys, values, dimension):
t_keys, t_values = t
assert t_keys is ad_util.zero
iota = broadcasted_iota(onp.int32, keys.shape, dimension % keys.ndim)
_, perm = sort_key_val(keys, iota)
keys_result = ad_util.zero if keys is ad.undefined_primal else None
values_result = sort_key_val(perm, t_values)[1] if values is ad.undefined_primal else None
return [keys_result, values_result]
def _sort_key_val_batch_rule(batched_args, batch_dims, dimension):
keys, values = batched_args
keys_bdim, values_bdim = batch_dims
assert keys_bdim is not None or values_bdim is not None
if keys_bdim == values_bdim:
new_dimension = dimension + (keys_bdim <= dimension)
return sort_key_val(keys, values, new_dimension), (keys_bdim, keys_bdim)
elif keys_bdim is not None and values_bdim is not None:
keys_trans = batching.moveaxis(keys, keys_bdim, values_bdim)
new_dimension = dimension + (values_bdim <= dimension)
return sort_key_val(keys_trans, values, new_dimension), (values_bdim, values_bdim)
elif keys_bdim is None:
broadcast_dimensions = onp.delete(onp.arange(values.ndim), values_bdim)
new_keys = broadcast_in_dim(keys, values.shape, broadcast_dimensions)
new_dimension = dimension + (values_bdim <= dimension)
return sort_key_val(new_keys, values, new_dimension), (values_bdim, values_bdim)
elif values_bdim is None:
broadcast_dimensions = onp.delete(onp.arange(keys.ndim), keys_bdim)
new_values = broadcast_in_dim(values, keys.shape, broadcast_dimensions)
new_dimension = dimension + (keys_bdim <= dimension)
return sort_key_val(keys, new_values, new_dimension), (keys_bdim, keys_bdim)
else:
assert False # unreachable
sort_key_val_p = Primitive('sort_key_val')
sort_key_val_p.multiple_results = True
sort_key_val_p.def_impl(partial(xla.apply_primitive, sort_key_val_p))
sort_key_val_p.def_abstract_eval(_sort_key_val_abstract_eval)
xla.translations[sort_key_val_p] = partial(standard_translate, 'sort_key_val')
ad.primitive_jvps[sort_key_val_p] = _sort_key_val_jvp
ad.primitive_transposes[sort_key_val_p] = _sort_key_val_transpose_rule
batching.primitive_batchers[sort_key_val_p] = _sort_key_val_batch_rule
def _tie_in_transpose_rule(t):
return [ad_util.zero, t]
def _tie_in_batch_rule(batched_args, batch_dims):
y = tie_in(*batched_args)
_, bdim_y = batch_dims
return y, bdim_y
tie_in_p = Primitive('tie_in')
tie_in_p.def_impl(lambda x, y: y)
tie_in_p.def_abstract_eval(lambda x, y: raise_to_shaped(y))
xla.translations[tie_in_p] = lambda c, x, y: y
ad.deflinear(tie_in_p, _tie_in_transpose_rule)
batching.primitive_batchers[tie_in_p] = _tie_in_batch_rule
masking.shape_rules[tie_in_p] = lambda shape_exprs: shape_exprs[1]
masking.masking_rules[tie_in_p] = lambda vals, logical_shapes: vals[1]
### constants
class _FilledConstant(xla.DeviceConstant):
__slots__ = ["fill_value"]
def __init__(self, fill_value, shape):
assert type(fill_value) is onp.ndarray
self.aval = ShapedArray(shape, _dtype(fill_value))
self._npy_value = None
self.fill_value = fill_value
@property
def _value(self):
return onp.full(self.shape, self.fill_value)
@staticmethod
def constant_handler(c, filled_const, canonicalize_types=True):
return c.Broadcast(
c.NumpyArrayConstant(filled_const.fill_value, canonicalize_types),
filled_const.shape)
class _IotaConstant(xla.DeviceConstant):
__slots__ = ["axis"]
def __init__(self, dtype, shape, axis):
self.aval = ShapedArray(shape, onp.dtype(dtype))
self._npy_value = None
self.axis = axis
@property
def _value(self):
if self._npy_value is None:
iota = onp.arange(self.shape[self.axis], dtype=self.dtype)
iota = iota.reshape([self.shape[self.axis] if i == self.axis else 1
for i in range(self.ndim)])
self._npy_value = onp.broadcast_to(iota, self.shape)
return self._npy_value
@staticmethod
def constant_handler(c, iota_constant, canonicalize_types=True):
dtype = iota_constant.dtype
if canonicalize_types:
dtype = dtypes.canonicalize_dtype(dtype)
return c.BroadcastedIota(dtype, iota_constant.shape, iota_constant.axis)
class _EyeConstant(xla.DeviceConstant):
__slots__ = ["axes"]
def __init__(self, shape, axes, dtype):
self.aval = ShapedArray(shape, onp.dtype(dtype))
self._npy_value = None
self.axes = axes
@property
def _value(self):
if self._npy_value is None:
ones = [1] * self.ndim
iotas = [onp.arange(self.shape[axis]).reshape(subvals(ones, [(axis, -1)]))
for axis in self.axes]
eyes = [i1 == i2 for i1, i2 in zip(iotas[:-1], iotas[1:])]
result = onp.asarray(_reduce(operator.and_, eyes), self.dtype)
self._npy_value = onp.broadcast_to(result, self.shape)
return self._npy_value
@staticmethod
def constant_handler(c, diag_const, canonicalize_types=True):
if canonicalize_types:
etype = xla_bridge.dtype_to_etype(diag_const.dtype)
else:
etype = xla_client.dtype_to_etype(diag_const.dtype)
etype = xla_bridge.dtype_to_etype(diag_const.dtype)
iotas = [c.BroadcastedIota(onp.uint32, diag_const.shape, axis)
for axis in diag_const.axes]
eyes = [c.Eq(i1, i2) for i1, i2 in zip(iotas[:-1], iotas[1:])]
return c.ConvertElementType(_reduce(c.And, eyes), etype)
for _t in [_FilledConstant, _IotaConstant, _EyeConstant]:
xla_bridge.register_constant_handler(_t, _t.constant_handler)
core.pytype_aval_mappings[_t] = ConcreteArray
xla.pytype_aval_mappings[_t] = make_shaped_array
xla.device_put_handlers[_t] = xla._instantiate_device_constant
pxla.shard_arg_handlers[_t] = pxla._shard_array
xla.canonicalize_dtype_handlers[_t] = _identity
ad_util.jaxval_adders[_t] = add
ad_util.jaxval_zeros_likers[_t] = zeros_like_array
### stop-gradient
def _stop_gradient_jvp_rule(primals, tangents):
# if we don't call stop_gradient here, we'd only peel off one autodiff tracer
x, = primals
return stop_gradient(x), ad_util.zero
def _stop_gradient_batch_rule(batched_args, batch_dims):
x, = batched_args
dim, = batch_dims
return stop_gradient(x), dim
stop_gradient_p = Primitive('stop_gradient')
stop_gradient_p.def_impl(_identity)
stop_gradient_p.def_abstract_eval(_identity)
xla.translations[stop_gradient_p] = lambda c, x: x
ad.primitive_jvps[stop_gradient_p] = _stop_gradient_jvp_rule
batching.primitive_batchers[stop_gradient_p] = _stop_gradient_batch_rule
def create_token(x):
"""Creates an XLA token value with no preconditions for sequencing effects.
Experimental.
Args:
x: a dummy argument used to tie the CreateToken operator into a trace. The
value of `x` is ignored.
"""
# x is a dummy argument used to tie the operator into a trace.
return create_token_p.bind(x)
create_token_p = Primitive("create_token")
create_token_p.def_impl(partial(xla.apply_primitive, create_token_p))
create_token_p.def_abstract_eval(lambda _: abstract_token)
xla.translations[create_token_p] = lambda c, _: c.CreateToken()
def after_all(*operands):
"""Merges one or more XLA token values. Experimental.
Wraps the XLA AfterAll operator."""
return after_all_p.bind(*operands)
def _after_all_abstract_eval(*operands):
if any(x is not abstract_token for x in operands):
raise TypeError("Arguments to after_all must be tokens")
return abstract_token
def _after_all_translation_rule(c, *operands):
return c.AfterAll(operands)
after_all_p = Primitive("after_all")
after_all_p.def_impl(partial(xla.apply_primitive, after_all_p))
after_all_p.def_abstract_eval(_after_all_abstract_eval)
xla.translations[after_all_p] = _after_all_translation_rule
def infeed(token, shape=None):
"""Consumes an infeed value of `shape` from the host. Experimental.
`token` is used to sequence infeed and outfeed effects.
"""
flat_shapes, treedef = pytree.flatten(shape)
for shape in flat_shapes:
if not isinstance(shape, ShapedArray):
raise TypeError("shapes argument to infeed must be a pytree of "
"ShapedArray values, got {}".format(shapes))
xs_and_token = infeed_p.bind(token, shapes=tuple(flat_shapes))
return (treedef.unflatten(xs_and_token[:-1]), xs_and_token[-1])
def _infeed_abstract_eval(token, shapes=None):
if token is not abstract_token:
raise TypeError("First argument to infeed must be a token")
return shapes + (abstract_token,)
def _infeed_translation_rule(c, token, shapes=None):
shape = tuple(map(xla.aval_to_xla_shape, shapes))
xs_and_token = c.Infeed(xla_client.Shape.tuple_shape(shape), token)
xs = c.GetTupleElement(xs_and_token, 0)
token = c.GetTupleElement(xs_and_token, 1)
outs = [c.GetTupleElement(xs, i) for i in range(len(shapes))] + [token]
return c.Tuple(*outs)
infeed_p = Primitive("infeed")
infeed_p.multiple_results = True
infeed_p.def_impl(partial(xla.apply_primitive, infeed_p))
infeed_p.def_abstract_eval(_infeed_abstract_eval)
xla.translations[infeed_p] = _infeed_translation_rule
def outfeed(token, xs):
"""Outfeeds value `xs` to the host. Experimental.
`token` is used to sequence infeed and outfeed effects.
"""
flat_xs, _ = pytree.flatten(xs)
return outfeed_p.bind(token, *flat_xs)
def _outfeed_abstract_eval(token, *xs):
if token is not abstract_token:
raise TypeError("First argument to outfeed must be a token")
return abstract_token
def _outfeed_translation_rule(c, token, *xs):
return c.Outfeed(c.Tuple(*xs), token)
outfeed_p = Primitive("outfeed")
outfeed_p.def_impl(partial(xla.apply_primitive, outfeed_p))
outfeed_p.def_abstract_eval(_outfeed_abstract_eval)
xla.translations[outfeed_p] = _outfeed_translation_rule
### util
_ndim = onp.ndim
def _dilate_shape(shape, dilation):
"""Utility function for computing the shape resulting from a dilation."""
if not onp.all(onp.greater(dilation, 0)):
msg = "All dilations must be positive, got {}."
raise TypeError(msg.format(dilation))
dilation = (1,) * (len(shape) - len(dilation)) + tuple(dilation)
return onp.where(shape == 0, 0,
onp.multiply(dilation, onp.subtract(shape, 1)) + 1)
def padtype_to_pads(in_shape, window_shape, window_strides, padding):
"""Convert padding string to list of pairs of pad values."""
PaddingType = xla_client.PaddingType
if isinstance(padding, str):
mapping = {'VALID': PaddingType.VALID, 'SAME': PaddingType.SAME}
try:
padding = mapping[padding.upper()]
except KeyError:
msg = "Unrecognized padding type: expected 'VALID' or 'SAME', got {}."
raise RuntimeError(msg.format(padding))
if padding == PaddingType.SAME:
out_shape = onp.ceil(onp.true_divide(in_shape, window_strides)).astype(int)
pad_sizes = [_max((out_size - 1) * stride + window_shape - in_size, 0)
for out_size, stride, window_shape, in_size
in zip(out_shape, window_strides, window_shape, in_shape)]
return [(pad_size // 2, pad_size - pad_size // 2) for pad_size in pad_sizes]
elif padding == PaddingType.VALID:
return [(0, 0)] * len(in_shape)
else:
msg = "Unknown padding type: {}."
raise TypeError(msg.format(padding))
def _check_same_dtypes(name, ignore_fp_precision, *ttypes):
"""Check that dtypes agree, possibly ignoring float precision."""
# the `ignore_fp_precision` flag exists because the XLA shape inference logic
# allows mixed floating point precision, but the HLO verifier often rejects it
types = list(map(onp.dtype, ttypes)) # canonicalize
if ignore_fp_precision:
types = [
onp.floating if dtypes.issubdtype(dtype, onp.floating)
else onp.complexfloating if dtypes.issubdtype(dtype, onp.complexfloating)
else dtype for dtype in types]
if len({dtypes.canonicalize_dtype(t) for t in types}) != 1:
if ignore_fp_precision:
msg = ("{} requires arguments to have same dtypes up to floating point "
"precision, got {}.")
else:
msg = "{} requires arguments to have the same dtypes, got {}."
raise TypeError(msg.format(name, ", ".join(map(str, types))))
def _check_conv_shapes(name, lhs_shape, rhs_shape, window_strides):
"""Check that conv shapes are valid and are consistent with window_strides."""
if len(lhs_shape) != len(rhs_shape):
msg = "Arguments to {} must have same rank, got {} and {}."
raise TypeError(msg.format(name, len(lhs_shape), len(rhs_shape)))
if len(lhs_shape) < 2:
msg = "Arguments to {} must have rank at least 2, got {} and {}."
raise TypeError(msg.format(name, len(lhs_shape), len(rhs_shape)))
if lhs_shape[1] != rhs_shape[1]:
msg = "Arguments to {} must agree on input feature size, got {} and {}."
raise TypeError(msg.format(name, lhs_shape[1], rhs_shape[1]))
_check_shapelike(name, "window_strides", window_strides)
if not onp.all(onp.greater(window_strides, 0)):
msg = "All elements of window_strides must be positive, got {}."
raise TypeError(msg.format(window_strides))
if len(window_strides) != len(lhs_shape) - 2:
msg = "{} window_strides has wrong length: expected {}, got {}."
expected_length = len(lhs_shape) - 2
raise TypeError(msg.format(name, expected_length, len(window_strides)))
def conv_shape_tuple(lhs_shape, rhs_shape, strides, pads):
"""Compute the shape tuple of a conv given input shapes in canonical order."""
if isinstance(pads, str):
pads = padtype_to_pads(lhs_shape[2:], rhs_shape[2:], strides, pads)
if len(pads) != len(lhs_shape) - 2:
msg = "Wrong number of explicit pads for convolution: expected {}, got {}."
raise TypeError(msg.format(len(lhs_shape) - 2, len(pads)))
lhs_padded = onp.add(lhs_shape[2:], onp.add(*zip(*pads)))
out_space = onp.floor_divide(
onp.subtract(lhs_padded, rhs_shape[2:]), strides) + 1
out_space = onp.maximum(0, out_space)
out_shape = (lhs_shape[0], rhs_shape[0]) + tuple(out_space)
return tuple(out_shape)
def conv_general_shape_tuple(lhs_shape, rhs_shape, window_strides, padding,
dimension_numbers):
lhs_perm, rhs_perm, out_perm = conv_general_permutations(dimension_numbers)
lhs_trans = onp.take(lhs_shape, lhs_perm)
rhs_trans = onp.take(rhs_shape, rhs_perm)
out_trans = conv_shape_tuple(lhs_trans, rhs_trans, window_strides, padding)
return tuple(onp.take(out_trans, onp.argsort(out_perm)))
def conv_transpose_shape_tuple(lhs_shape, rhs_shape, window_strides, padding,
dimension_numbers):
lhs_perm, rhs_perm, out_perm = conv_general_permutations(dimension_numbers)
lhs_trans = onp.take(lhs_shape, lhs_perm)
rhs_trans = onp.take(rhs_shape, rhs_perm)
if isinstance(padding, str):
padding = [_conv_transpose_padding(k, s, padding)
for k,s in zip(rhs_trans[2:], window_strides)]
padding = list(map(onp.sum, padding))
unpad_out_space = [(i-1) * s - k + 2
for i, k, s in zip(lhs_trans[2:],
rhs_trans[2:],
window_strides)]
out_space = onp.sum([unpad_out_space, padding], axis=0).tolist()
out_trans = tuple((lhs_trans[0], rhs_trans[0]) + tuple(out_space))
return tuple(onp.take(out_trans, onp.argsort(out_perm)))
def _check_shapelike(fun_name, arg_name, obj):
"""Check that `obj` is a shape-like value (e.g. tuple of nonnegative ints)."""
if (type(obj) is masking.ShapeExpr
or type(obj) is tuple and any(type(d) is masking.Poly for d in obj)):
return obj
if not isinstance(obj, (tuple, list, onp.ndarray)):
msg = "{} {} must be of type tuple/list/ndarray, got {}."
raise TypeError(msg.format(fun_name, arg_name, type(obj)))
# bool(obj) for an ndarray raises an error, so we check len
if not len(obj): # pylint: disable=g-explicit-length-test
return
obj_arr = onp.array(obj)
if obj_arr.ndim != 1:
msg = "{} {} must be rank 1, got {}."
raise TypeError(msg.format(obj_arr.ndim))
if not dtypes.issubdtype(obj_arr.dtype, onp.integer):
msg = "{} {} must have every element be an integer type, got {}."
raise TypeError(msg.format(fun_name, arg_name, tuple(map(type, obj))))
if not (obj_arr >= 0).all():
msg = "{} {} must have every element be nonnegative, got {}."
raise TypeError(msg.format(fun_name, arg_name, obj))
def _dynamic_slice_indices(operand, start_indices):
if not isinstance(start_indices, (tuple, list)):
if start_indices.ndim != 1:
raise ValueError("Slice indices must be a 1D sequence, got {}"
.format(start_indices.shape))
start_indices = [reshape(slice(start_indices, [i], [i+1]), ())
for i in range(operand.ndim)]
else:
start_indices = [onp.asarray(i, dtype=dtypes.int_) if isinstance(i, int)
else i for i in start_indices]
if len(start_indices) != operand.ndim:
msg = ("Length of slice indices must match number of operand dimensions ({} "
"vs {})")
raise ValueError(msg.format(len(start_indices, operand.shape)))
# map int over operand.shape to raise any dynamic-shape errors
return [select(lt(i, _const(i, 0)), add(i, _const(i, int(d))), i)
for i, d in zip(start_indices, operand.shape)]
def _const(example, val):
if dtypes.is_python_scalar(example):
return dtypes.scalar_type_of(example)(val)
return onp.array(val, _dtype(example))
_zeros = partial(full_like, fill_value=0)
_zero = partial(full_like, shape=(), fill_value=0)
_ones = partial(full_like, fill_value=1)
_one = partial(full_like, shape=(), fill_value=1)
_twos = partial(full_like, fill_value=2)
_two = partial(full_like, shape=(), fill_value=2)
_dtype = dtype = dtypes.result_type
_iscomplex = lambda x: dtypes.issubdtype(_dtype(x), onp.complexfloating)
def ranges_like(*xs):
start = 0
for x in xs:
x_len = len(x)
yield range(start, start + x_len)
start += x_len
def remaining(original, *removed_lists):
blacklist = set(itertools.chain(*removed_lists))
return [i for i in original if i not in blacklist]
def _canonicalize_precision(precision):
if precision is None:
return None
if isinstance(precision, Precision):
return precision
else:
msg = "Precision argument must be None or a lax.Precision value; got {}"
raise ValueError(msg.format(precision))
# lhs_spec and out_spec are lists containing
# [batch dim, feature dim, spatial dims ...]
# rhs_spec is a list containing:
# [out feature dim, in feature dim, spatial dims ...]
class ConvDimensionNumbers(collections.namedtuple(
"ConvDimensionNumbers", ["lhs_spec", "rhs_spec", "out_spec"])):
"""Describes batch, spatial, and feature dimensions of a convolution.
Args:
lhs_spec: a tuple of nonnegative integer dimension numbers containing
`(batch dimension, feature dimension, spatial dimensions...)`.
rhs_spec: a tuple of nonnegative integer dimension numbers containing
`(out feature dimension, in feature dimension, spatial dimensions...)`.
out_spec: a tuple of nonnegative integer dimension numbers containing
`(batch dimension, feature dimension, spatial dimensions...)`.
"""
def conv_dimension_numbers(lhs_shape, rhs_shape, dimension_numbers):
"""Converts convolution `dimension_numbers` to a `ConvDimensionNumbers`.
Args:
lhs_shape: tuple of nonnegative integers, shape of the convolution input.
rhs_shape: tuple of nonnegative integers, shape of the convolution kernel.
dimension_numbers: None or a tuple/list of strings, following the
convolution dimension number specification format in xla_client.py.
Returns:
A `ConvDimensionNumbers` object that represents `dimension_numbers` in the
canonical form used by lax functions.
"""
if len(lhs_shape) != len(rhs_shape):
msg = "convolution requires lhs and rhs ndim to be equal, got {} and {}."
raise TypeError(msg.format(len(lhs_shape), len(rhs_shape)))
if dimension_numbers is None:
iota = tuple(range(len(lhs_shape)))
return ConvDimensionNumbers(iota, iota, iota)
elif isinstance(dimension_numbers, (list, tuple)):
if len(dimension_numbers) != 3:
msg = "convolution dimension_numbers list/tuple must be length 3, got {}."
raise TypeError(msg.format(len(dimension_numbers)))
if not all(isinstance(elt, str) for elt in dimension_numbers):
msg = "convolution dimension_numbers elements must be strings, got {}."
raise TypeError(msg.format(tuple(map(type, dimension_numbers))))
msg = ("convolution dimension_numbers[{}] must have len equal to the ndim "
"of lhs and rhs, got {} for lhs and rhs shapes {} and {}.")
for i, elt in enumerate(dimension_numbers):
if len(elt) != len(lhs_shape):
raise TypeError(msg.format(i, len(elt), lhs_shape, rhs_shape))
lhs_spec, rhs_spec, out_spec = conv_general_permutations(dimension_numbers)
return ConvDimensionNumbers(lhs_spec, rhs_spec, out_spec)
else:
msg = "convolution dimension_numbers must be tuple/list or None, got {}."
raise TypeError(msg.format(type(dimension_numbers)))
def conv_general_permutations(dimension_numbers):
"""Utility for convolution dimension permutations relative to Conv HLO."""
lhs_spec, rhs_spec, out_spec = dimension_numbers
lhs_char, rhs_char, out_char = charpairs = ("N", "C"), ("O", "I"), ("N", "C")
for i, (a, b) in enumerate(charpairs):
if not dimension_numbers[i].count(a) == dimension_numbers[i].count(b) == 1:
msg = ("convolution dimension_numbers[{}] must contain the characters "
"'{}' and '{}' exatly once, got {}.")
raise TypeError(msg.format(i, a, b, dimension_numbers[i]))
if len(dimension_numbers[i]) != len(set(dimension_numbers[i])):
msg = ("convolution dimension_numbers[{}] cannot have duplicate "
"characters, got {}.")
raise TypeError(msg.format(i, dimension_numbers[i]))
if not (set(lhs_spec) - set(lhs_char) == set(rhs_spec) - set(rhs_char) ==
set(out_spec) - set(out_char)):
msg = ("convolution dimension_numbers elements must each have the same "
"set of spatial characters, got {}.")
raise TypeError(msg.format(dimension_numbers))
def getperm(spec, charpair):
spatial = (i for i, c in enumerate(spec) if c not in charpair)
if spec is not rhs_spec:
spatial = sorted(spatial, key=lambda i: rhs_spec.index(spec[i]))
return (spec.index(charpair[0]), spec.index(charpair[1])) + tuple(spatial)
lhs_perm, rhs_perm, out_perm = map(getperm, dimension_numbers, charpairs)
return lhs_perm, rhs_perm, out_perm
def _conv_general_proto(dimension_numbers):
assert type(dimension_numbers) is ConvDimensionNumbers
lhs_spec, rhs_spec, out_spec = dimension_numbers
proto = xla_client.ConvolutionDimensionNumbers()
proto.input_batch_dimension = lhs_spec[0]
proto.input_feature_dimension = lhs_spec[1]
proto.output_batch_dimension = out_spec[0]
proto.output_feature_dimension = out_spec[1]
proto.kernel_output_feature_dimension = rhs_spec[0]
proto.kernel_input_feature_dimension = rhs_spec[1]
proto.input_spatial_dimensions.extend(lhs_spec[2:])
proto.kernel_spatial_dimensions.extend(rhs_spec[2:])
proto.output_spatial_dimensions.extend(out_spec[2:])
return proto
def _conv_general_vjp_lhs_padding(
in_shape, window_dimensions, window_strides, out_shape, padding,
lhs_dilation, rhs_dilation):
lhs_dilated_shape = _dilate_shape(in_shape, lhs_dilation)
rhs_dilated_shape = _dilate_shape(window_dimensions, rhs_dilation)
out_dilated_shape = _dilate_shape(out_shape, window_strides)
pad_before = onp.subtract(rhs_dilated_shape, [lo for lo, _ in padding]) - 1
pad_after = (onp.add(lhs_dilated_shape, rhs_dilated_shape) - 1
- out_dilated_shape - pad_before)
return zip(pad_before, pad_after)
def _conv_general_vjp_rhs_padding(
in_shape, window_dimensions, window_strides, out_shape, padding,
lhs_dilation, rhs_dilation):
lhs_dilated_shape = _dilate_shape(in_shape, lhs_dilation)
rhs_dilated_shape = _dilate_shape(window_dimensions, rhs_dilation)
out_dilated_shape = _dilate_shape(out_shape, window_strides)
total_in_pad = out_dilated_shape + rhs_dilated_shape - lhs_dilated_shape - 1
return [(pad[0], tot - pad[0]) for pad, tot in zip(padding, total_in_pad)]
def _balanced_eq(x, z, y):
return div(select(_eq_meet(x, z), _ones(z), _zeros(z)),
select(_eq_meet(y, z), _twos(z), _ones(z)))
def _eq_meet(a, b):
a_dtype, b_dtype = _dtype(a), _dtype(b)
if a_dtype != b_dtype:
higher_dtype = dtypes.promote_types(a_dtype, b_dtype)
if higher_dtype == a_dtype:
a = convert_element_type(a, b_dtype)
else:
b = convert_element_type(b, a_dtype)
return eq(a, b)
def subvals(lst, replace):
lst = list(lst)
for i, v in replace:
lst[i] = v
return tuple(lst)
def _abstractify(x):
return raise_to_shaped(core.get_aval(x))
def _check_user_dtype_supported(dtype, fun_name=None):
if dtype is not None and onp.dtype(dtype) != dtypes.canonicalize_dtype(dtype):
msg = ("Explicitly requested dtype {} {} is not available, "
"and will be truncated to dtype {}. To enable more dtypes, set the "
"jax_enable_x64 configuration option or the JAX_ENABLE_X64 shell "
"environment variable. "
"See https://github.com/google/jax#current-gotchas for more.")
fun_name = "requested in {}".format(fun_name) if fun_name else ""
truncated_dtype = dtypes.canonicalize_dtype(dtype).name
warnings.warn(msg.format(dtype, fun_name , truncated_dtype))
|
jax-master
|
jax/lax/lax.py
|
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
"""
Parallelization primitives.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import six
from six.moves import xrange
import numpy as onp
from jax import core
from jax import ad_util
from jax import dtypes
from jax.lax import lax
from jax.abstract_arrays import ShapedArray
from jax.interpreters import ad
from jax.interpreters import parallel
from jax.interpreters import xla
from jax.interpreters import pxla
from jax.util import partial, unzip2, prod
from jax.lib import xla_client
from jax.interpreters.pxla import axis_index
### parallel traceables
def psum(x, axis_name):
"""Compute an all-reduce sum on ``x`` over the pmapped axis ``axis_name``.
Args:
x: array with a mapped axis named ``axis_name``.
axis_name: hashable Python object used to name a pmapped axis (see the
``pmap`` docstring for more details).
Returns:
An array with the same shape as ``x`` representing the result of an
all-reduce sum along the axis ``axis_name``.
For example, with 4 XLA devices available:
>>> x = np.arange(4)
>>> y = jax.pmap(lambda x: jax.lax.psum(x, 'i'), axis_name='i')(x)
>>> print(y)
[6 6 6 6]
>>> y = jax.pmap(lambda x: x / jax.lax.psum(x, 'i'), axis_name='i')(x)
>>> print(y)
[ 0. 0.16666667 0.33333334 0.5 ]
"""
return psum_p.bind(x, axis_name=axis_name)
def pmax(x, axis_name):
"""Compute an all-reduce max on ``x`` over the pmapped axis ``axis_name``.
Args:
x: array with a mapped axis named ``axis_name``.
axis_name: hashable Python object used to name a pmapped axis (see the
``pmap`` docstring for more details).
Returns:
An array with the same shape as ``x`` representing the result of an
all-reduce max along the axis ``axis_name``.
"""
return pmax_p.bind(x, axis_name=axis_name)
def pmin(x, axis_name):
"""Compute an all-reduce min on ``x`` over the pmapped axis ``axis_name``.
Args:
x: array with a mapped axis named ``axis_name``.
axis_name: hashable Python object used to name a pmapped axis (see the
``pmap`` docstring for more details).
Returns:
An array with the same shape as ``x`` representing the result of an
all-reduce min along the axis ``axis_name``.
"""
return pmin_p.bind(x, axis_name=axis_name)
def ppermute(x, axis_name, perm):
"""Perform a collective permutation according to the permutation ``perm``.
This function is an analog of the CollectivePermute XLA HLO.
Args:
x: array with a mapped axis named ``axis_name``.
axis_name: hashable Python object used to name a pmapped axis (see the
``pmap`` docstring for more details).
perm: list of pairs of ints, representing (source_index, destination_index)
pairs that encode how the mapped axis named ``axis_name`` should be
shuffled. The integer values are treated as indices into the mapped axis
``axis_name``. Any two pairs should not have the same source index or the
same destination index. For each index of the axis ``axis_name`` that does
not correspond to a destination index in ``perm``, the corresponding
values in the result are filled with zeros of the appropriate type.
Returns:
An array with the same shape as ``x`` with slices along the axis
``axis_name`` gathered from ``x`` according to the permutation ``perm``.
"""
return ppermute_p.bind(x, axis_name=axis_name, perm=tuple(perm))
def pswapaxes(x, axis_name, axis):
"""Swap the pmapped axis ``axis_name`` with the unmapped axis ``axis``.
The mapped axis size must be equal to the size of the unmapped axis; that is,
we must have ``lax.psum(1, axis_name) == x.shape[axis]``.
This function is a special case of ``all_to_all`` where the pmapped axis of
the input is placed at the position ``axis`` in the output. That is, it is
equivalent to ``all_to_all(x, axis_name, axis, axis)``.
Args:
x: array with a mapped axis named ``axis_name``.
axis_name: hashable Python object used to name a pmapped axis (see the
``pmap`` docstring for more details).
axis: int indicating the unmapped axis of ``x`` to map with the name
``axis_name``.
Returns:
An array with shape ``np.insert(np.delete(x.shape, axis), axis, axis_size)``
where ``axis_size`` is the size of the mapped axis named ``axis_name`` in
the input ``x``.
"""
return all_to_all(x, axis_name, axis, axis)
def all_to_all(x, axis_name, split_axis, concat_axis):
"""Materialize the mapped axis and map a different axis.
In the output, the input mapped axis ``axis_name`` is materialized at the
logical axis position ``concat_axis``, and the input unmapped axis at position
``split_axis`` is mapped with the name ``axis_name``.
The input mapped axis size must be equal to the size of the axis to be mapped;
that is, we must have ``lax.psum(1, axis_name) == x.shape[split_axis]``.
Args:
x: array with a mapped axis named ``axis_name``.
axis_name: hashable Python object used to name a pmapped axis (see the
``pmap`` docstring for more details).
split_axis: int indicating the unmapped axis of ``x`` to map with the name
``axis_name``.
concat_axis: int indicating the position in the output to materialize the
mapped axis of the input with the name ``axis_name``.
Returns:
An array with shape given by the expression::
np.insert(np.delete(x.shape, split_axis), concat_axis, axis_size)
where ``axis_size`` is the size of the mapped axis named ``axis_name`` in
the input ``x``, i.e. ``axis_size = lax.psum(1, axis_name)``.
"""
if psum(1, axis_name) != x.shape[split_axis]:
msg = ("all_to_all requires the size of the mapped axis axis_name to equal "
"x.shape[split_axis], but they are {} and {} respectively.")
raise ValueError(msg.format(psum(1, axis_name), x.shape[split_axis]))
return all_to_all_p.bind(x, split_axis=split_axis, concat_axis=concat_axis,
axis_name=axis_name)
### parallel primitives
def standard_pmap_primitive(name):
prim = core.Primitive(name)
prim.def_impl(partial(pxla.apply_parallel_primitive, prim))
prim.def_abstract_eval(lambda x, *args, **params: x)
return prim
def _allreduce_split_axis_rule(prim, reducer, vals, which_mapped, axis_name):
assert tuple(which_mapped) == (True,)
x, = vals
return prim.bind(reducer(x, [0]), axis_name=axis_name), False
def _allreduce_translation_rule(prim, c, val, replica_groups):
dtype = c.GetShape(val).numpy_dtype()
scalar = ShapedArray((), dtype)
computation = xla.primitive_subcomputation(prim, scalar, scalar)
return c.AllReduce(val, computation, replica_groups=replica_groups)
# psum translation rule has special handling for complex dtypes
def _psum_translation_rule(c, val, replica_groups):
psum = partial(_allreduce_translation_rule, lax.add_p, c,
replica_groups=replica_groups)
dtype = c.GetShape(val).numpy_dtype()
if dtypes.issubdtype(dtype, onp.complexfloating):
return c.Complex(psum(c.Real(val)), psum(c.Imag(val)))
else:
return psum(val)
psum_p = standard_pmap_primitive('psum')
pxla.split_axis_rules[psum_p] = \
partial(_allreduce_split_axis_rule, psum_p, lax._reduce_sum)
xla.parallel_translations[psum_p] = _psum_translation_rule
pxla.parallel_pure_rules[psum_p] = lambda x, shape: x * prod(shape)
ad.deflinear(psum_p, lambda t, axis_name: [psum(t, axis_name)])
pxla.multi_host_supported_collectives.add(psum_p)
pmax_p = standard_pmap_primitive('pmax')
xla.parallel_translations[pmax_p] = \
partial(_allreduce_translation_rule, lax.max_p)
pxla.split_axis_rules[pmax_p] = \
partial(_allreduce_split_axis_rule, pmax_p, lax._reduce_max)
pmin_p = standard_pmap_primitive('pmin')
xla.parallel_translations[pmin_p] = \
partial(_allreduce_translation_rule, lax.min_p)
pxla.split_axis_rules[pmin_p] = \
partial(_allreduce_split_axis_rule, pmin_p, lax._reduce_min)
def _ppermute_translation_rule(c, x, replica_groups, perm):
group_size = len(replica_groups[0])
srcs, dsts = unzip2((src % group_size, dst % group_size) for src, dst in perm)
if not (len(srcs) == len(set(srcs)) and len(dsts) == len(set(dsts))):
msg = "ppermute sources and destinations must be unique, got {}."
raise ValueError(msg.format(perm))
full_perm = []
for grp in replica_groups:
grp = list(sorted(grp))
full_perm.extend((grp[src], grp[dst]) for src, dst in perm)
return c.CollectivePermute(x, full_perm)
def _ppermute_transpose_rule(t, perm, axis_name):
srcs, dsts = unzip2(perm)
inverse_perm = list(zip(dsts, srcs))
return [ppermute(t, axis_name=axis_name, perm=inverse_perm)]
ppermute_p = standard_pmap_primitive('ppermute')
ad.deflinear(ppermute_p, _ppermute_transpose_rule)
xla.parallel_translations[ppermute_p] = _ppermute_translation_rule
def _all_to_all_translation_rule(c, x, split_axis, concat_axis, replica_groups):
return c.AllToAll(x, split_axis, concat_axis, replica_groups)
def _all_to_all_split_axis_rule(vals, which_mapped, split_axis, concat_axis,
axis_name):
assert tuple(which_mapped) == (True,)
x, = vals
# perform the communication to swap the hardware-mapped axes
stacked = all_to_all_p.bind(x, split_axis=split_axis + 1, concat_axis=0,
axis_name=axis_name)
# transpose the newly mapped axis to the front, newly unmapped to concat_axis
out = _moveaxis(split_axis + 1, 0, stacked)
out = _moveaxis(1, concat_axis + 1, out)
return out, True
def _moveaxis(src, dst, x):
perm = [i for i in range(x.ndim) if i != src]
perm.insert(dst, src)
return lax.transpose(x, perm)
all_to_all_p = standard_pmap_primitive('all_to_all')
xla.parallel_translations[all_to_all_p] = _all_to_all_translation_rule
pxla.split_axis_rules[all_to_all_p] = _all_to_all_split_axis_rule
### papply rules
# TODO(skye): it would be nice if we could put these with their corresponding
# primitives, but that currently causes circular dependencies. More refactoring
# might fix this.
def _drop(x, dim, axis_name):
return lax.dynamic_index_in_dim(x, axis_index(axis_name), dim, False)
def _allgather(x, dim, size, axis_name):
shape = list(x.shape)
shape.insert(dim, size)
out = lax.full(shape, lax._const(x, 0))
out = lax.dynamic_update_index_in_dim(out, x, axis_index(axis_name), dim)
return psum(out, axis_name)
def _broadcasting_papply(prim, name, size, vals, axes, **params):
x, y = vals
xdim, ydim = axes
if xdim is None:
if x.shape:
if x.shape[ydim] == 1:
x = x.reshape(onp.delete(x.shape, ydim))
else:
x = _drop(x, ydim, name)
return prim.bind(x, y, **params), ydim
elif ydim is None:
if y.shape:
if y.shape[xdim] == 1:
y = y.reshape(onp.delete(y.shape, xdim))
else:
y = _drop(y, xdim, name)
return prim.bind(x, y, **params), xdim
elif xdim == ydim:
return prim.bind(x, y, **params), xdim
else:
x_tosplit = ydim - int(xdim <= ydim)
y_tosplit = xdim - int(ydim <= xdim)
if y.shape[y_tosplit] == 1:
y = _allgather(y, ydim, size, name)
y = y.reshape(onp.delete(y.shape, xdim))
return prim.bind(x, y, **params), ydim
elif x.shape[x_tosplit] == 1:
x = _allgather(x, xdim, size, name)
x = x.reshape(onp.delete(x.shape, ydim))
return prim.bind(x, y, **params), ydim
else:
x = all_to_all(x, name, x_tosplit, xdim)
return prim.bind(x, y, **params), ydim
def _defbroadcasting(prim):
parallel.papply_primitive_rules[prim] = partial(_broadcasting_papply, prim)
def _vectorized_papply(prim, name, size, vals, axes, **params):
assert all(axes[0] == a for a in axes[1:])
return prim.bind(*vals, **params), axes[0]
def _defvectorized(prim):
parallel.papply_primitive_rules[prim] = partial(_vectorized_papply, prim)
def _reducer_papply(prim, cprim, name, size, vals, papply_axes, axes, **kwargs):
operand, = vals
papply_axis, = papply_axes
other_axes = [i for i in axes if i != papply_axis]
other_axes = [i - 1 if i > papply_axis else i for i in other_axes]
if other_axes:
if 'input_shape' in kwargs: # special to the reduce-sum family
s = kwargs['input_shape']
kwargs['input_shape'] = s[:papply_axis] + s[papply_axis + 1:]
result = prim.bind(operand, axes=tuple(other_axes), **kwargs)
else:
result = operand
if not axes or papply_axis in axes:
return cprim.bind(result, axis_name=name), None
else:
new_papply_axis = papply_axis - onp.sum(onp.less(other_axes, papply_axis))
return result, new_papply_axis
def _defreducer(prim, collective_prim):
parallel.papply_primitive_rules[prim] = partial(_reducer_papply, prim, collective_prim)
def _identity_papply(prim, argnum, name, size, vals, axes, **params):
return prim.bind(*vals, **params), axes[argnum]
def _defidentity(prim, argnum=0):
parallel.papply_primitive_rules[prim] = partial(_identity_papply, prim, argnum)
_defvectorized(lax.neg_p)
_defvectorized(lax.sign_p)
_defvectorized(lax.floor_p)
_defvectorized(lax.ceil_p)
_defvectorized(lax.round_p)
_defvectorized(lax.is_finite_p)
_defvectorized(lax.exp_p)
_defvectorized(lax.log_p)
_defvectorized(lax.expm1_p)
_defvectorized(lax.log1p_p)
_defvectorized(lax.tanh_p)
_defvectorized(lax.sin_p)
_defvectorized(lax.cos_p)
_defvectorized(lax.lgamma_p)
_defvectorized(lax.digamma_p)
_defvectorized(lax.erf_p)
_defvectorized(lax.erfc_p)
_defvectorized(lax.erf_inv_p)
_defvectorized(lax.real_p)
_defvectorized(lax.imag_p)
_defvectorized(lax.conj_p)
_defvectorized(lax.abs_p)
_defvectorized(lax.sqrt_p)
_defbroadcasting(lax.atan2_p)
_defbroadcasting(lax.complex_p)
_defbroadcasting(lax.pow_p)
_defbroadcasting(lax.and_p)
_defbroadcasting(lax.or_p)
_defbroadcasting(lax.xor_p)
_defbroadcasting(lax.add_p)
_defbroadcasting(lax.sub_p)
_defbroadcasting(lax.mul_p)
_defbroadcasting(lax.safe_mul_p)
_defbroadcasting(lax.div_p)
_defbroadcasting(lax.rem_p)
_defbroadcasting(lax.max_p)
_defbroadcasting(lax.min_p)
_defbroadcasting(lax.shift_left_p)
_defbroadcasting(lax.shift_right_arithmetic_p)
_defbroadcasting(lax.shift_right_logical_p)
_defidentity(lax.tie_in_p)
_defreducer(lax.reduce_sum_p, psum_p)
_defreducer(lax.reduce_max_p, pmax_p)
_defreducer(lax.reduce_min_p, pmin_p)
def _dot_general_papply_rule(name, size, vals, dims, dimension_numbers,
precision):
x, y = vals
xdim, ydim = dims
(lhs_contract, rhs_contract), (lhs_batch, rhs_batch) = dimension_numbers
if lhs_batch or rhs_batch:
raise NotImplementedError(
('papply of dot_general with batch dimensions: '
'xdim={}, ydim={}, dimension_numbers={}').format(
xdim, ydim, dimension_numbers))
def adjust_dims(dims, thresh):
return tuple(i - 1 if i > thresh else i for i in dims if i != thresh)
def sub_dims(xdim, ydim, xcontract, ycontract, xbatch, ybatch):
if xdim is not None:
xbatch = adjust_dims(xbatch, xdim)
xcontract = adjust_dims(xcontract, xdim)
if ydim is not None:
ybatch = adjust_dims(ybatch, ydim)
ycontract = adjust_dims(ycontract, ydim)
return ((xcontract, ycontract), (xbatch, ybatch))
def cases(x, y, xdim, ydim, xc, yc, xb, yb):
# Consider three states in which an operand may be
# 1: split, contracting
# 2: split, not contracting
# 3: not split
#
# We will handle the following cases, marked by corresponding letter
# symbols:
#
# |1 2 3|y
# -+-----+-
# 1|a b c
# 2|d e f
# 3|g h i
# -+
# x|
#
# Case i is already covered and we can assume that it is excluded at the
# outset, since a papply rule is not invoked when no operands are split.
if xdim in xc:
# cases a, b, c
if ydim in yc:
# case a: both operands are split and contracting
# TODO(frostig): Might the following work?
# z = lax.dot_general(
# x, y, sub_dims(xdim, ydim, xc, yc, xb, yb), precision)
# return True, (psum(z, name), None)
return False, 'both operands split and contracting'
elif ydim is not None:
# case b: x split and contracting, y split but not contracting
# TODO(frostig): Might the following work?
# new_ydim = yc[xc.index(xdim)]
# y = all_to_all(y, name, new_ydim, ydim)
# z = lax.dot_general(
# x, y, sub_dims(xdim, new_ydim, xc, yc, xb, yb), precision)
# return True, (psum(z, name), None)
return False, 'rhs split but not contracting, lhs split and contracting'
else:
# case c: x split and contracting, y not split
assert ydim is None
return False, 'one operand split and contracting, other is not split'
elif xdim is not None:
# cases d, e, f
if ydim in yc:
# case d: x split but not contracting, y split and contracting
# TODO(frostig): Might the following work?
# new_xdim = xc[yc.index(ydim)]
# x = all_to_all(x, name, new_xdim, xdim)
# z = lax.dot_general(
# x, y, sub_dims(new_xdim, ydim, xc, yc, xb, yb), precision)
# return True, (psum(z, name), None)
return False, 'lhs split but not contracting, rhs split and contracting'
elif ydim is not None:
# case e: both operands are split but not contracting
y = _allgather(y, ydim, size, name)
z = lax.dot_general(
x, y, sub_dims(xdim, None, xc, yc, xb, yb), precision)
zdim = xdim + len(xb) - len([d for d in xrange(xdim) if d in xc])
return True, (z, zdim)
else:
# case f: x split but not contracting, y not split
assert ydim is None
z = lax.dot_general(
x, y, sub_dims(xdim, None, xc, yc, xb, yb), precision)
zdim = xdim + len(xb) - len([d for d in xrange(xdim) if d in xc])
return True, (z, zdim)
else:
# cases g, h
assert xdim is None
if ydim in yc:
# case g: x not split, y split and contracting
return False, 'one operand split and contracting, other is not split'
else:
# case h: x not split, y split but not contracting
assert ydim is not None
# TODO(frostig): Might the following work?
# z = lax.dot_general(
# x, y, sub_dims(None, ydim, xc, yc, xb, yb), precision)
# zdim = (
# ydim + len(xb) + # batch dimensions
# x.ndim - len(xc) - # non-contracting x dimensions
# len([d for d in xrange(ydim) if d in yc]))
# return True, (z, zdim)
return False, 'lhs not split, rhs split but not contracting'
assert False, 'unreachable'
ok, out = cases(
x, y, xdim, ydim, lhs_contract, rhs_contract, lhs_batch, rhs_batch)
if ok:
return out
else:
raise NotImplementedError(
('papply of dot_general, {}: '
'xdim={}, ydim={}, dimension_numbers={}').format(
out, xdim, ydim, dimension_numbers))
def _reshape_papply_rule(name, size, vals, axes, new_sizes, dimensions,
old_sizes):
operand, = vals
axis, = axes
def filter_ones(xs):
return filter(lambda x: x != 1, xs)
def find_new_axis(old_axis, old_sizes, new_sizes):
left = onp.prod(old_sizes[:old_axis])
size = old_sizes[old_axis]
prod = 1
for i, cur_sz in enumerate(new_sizes):
if prod == left and cur_sz == size:
return i
prod = prod * cur_sz
return None
if dimensions is None:
new_axis = find_new_axis(axis, old_sizes, new_sizes)
if new_axis is not None:
new_sizes_ = new_sizes[:new_axis] + new_sizes[new_axis + 1:]
return lax.reshape(operand, new_sizes_, dimensions=dimensions), new_axis
else:
raise NotImplementedError(
'papply of reshape that would change hidden dimension size')
else:
raise NotImplementedError('papply of reshape with `dimensions`')
def _transpose_papply_rule(name, size, vals, dims, permutation):
x, = vals
xdim, = dims
local_perm = [i if i < xdim else i - 1 for i in permutation if i != xdim]
return lax.transpose(x, local_perm), permutation.index(xdim)
def _select_papply_rule(name, size, vals, dims):
dimset = {d for d in dims if d is not None}
if len(dimset) != 1:
raise NotImplementedError(
'papply of select with operands split along different dimensions')
dim, = dimset
def drop(x, d):
return _drop(x, dim, name) if d is None else x
return lax.select_p.bind(*map(drop, vals, dims)), dim
def _add_jaxvals_papply_rule(name, size, vals, dims):
x, y = vals
xdim, ydim = dims
if xdim == ydim:
out_dim = xdim
elif ydim is None:
y = lax.psplit_like(y, x, name)
out_dim = xdim
else:
x = lax.psplit_like(x, y, name)
out_dim = ydim
return ad_util.add_jaxvals_p.bind(x, y), out_dim
def _convert_element_type_papply_rule(
name, size, vals, dims, new_dtype, **params):
operand, = vals
dim, = dims
return lax.convert_element_type(operand, new_dtype), dim
def _conv_general_dilated_papply_rule(
name, size, vals, dims, window_strides, padding, lhs_dilation, rhs_dilation,
dimension_numbers, feature_group_count, precision, **unused_kwargs):
lhs, rhs = vals
lhs_dim, rhs_dim = dims
lhs_spec_batch_dim = dimension_numbers.lhs_spec[0]
if rhs_dim is None and lhs_dim == lhs_spec_batch_dim:
lhs = lax.reshape(lhs, tuple(onp.insert(lhs.shape, lhs_dim, 1)))
out = lax.conv_general_dilated(
lhs, rhs, window_strides, padding, lhs_dilation, rhs_dilation,
dimension_numbers, feature_group_count, precision)
return out, lhs_dim
else:
raise NotImplementedError(
"splitting a convolution along anything but input batch dimension")
def _broadcast_in_dim_papply_rule(name, size, vals, dims, shape,
broadcast_dimensions):
operand, = vals
dim, = dims
out_dim = broadcast_dimensions[dim]
if shape[out_dim] != shape[dim]:
raise ValueError(
"broadcast_in_dim changes hidden dimension size: {} to {}".format(
shape[dim], shape[out_dim]))
sub_bdims = tuple(onp.delete(broadcast_dimensions, dim))
sub_shape = tuple(onp.delete(shape, out_dim))
return lax.broadcast_in_dim(operand, sub_shape, sub_bdims), out_dim
def _pad_papply_rule(name, size, vals, dims, padding_config):
operand, padding_value = vals
operand_dim, padding_value_dim = dims
assert padding_value_dim is None
padding_config = list(padding_config)
if padding_config[operand_dim] == (0, 0, 0):
padded = lax.pad(
operand,
padding_value,
padding_config[:operand_dim] + padding_config[operand_dim + 1:])
return padded, operand_dim
else:
raise NotImplementedError(
'pad changes size of hidden dimension {} with config {}'.format(
operand_dim, padding_config))
def _slice_papply_rule(name, size, vals, dims, start_indices, limit_indices,
strides, **kwargs):
operand, = vals
dim, = dims
start_indices = list(start_indices)
limit_indices = list(limit_indices)
if (start_indices[dim] != 0 or
limit_indices[dim] != size or
strides is not None and strides[dim] != 1):
raise NotImplementedError('slice changes side of hidden dimension')
out = lax.slice(
operand,
start_indices[:dim] + start_indices[dim + 1:],
limit_indices[:dim] + limit_indices[dim + 1:],
strides[:dim] + strides[dim + 1:] if strides is not None else None)
return out, dim
def _gather_papply_rule(
name, size, vals, dims, dimension_numbers, slice_sizes, operand_shape):
operand, start_indices = vals
operand_dim, start_indices_dim = dims
if (operand_dim is None and
start_indices_dim is not None and
start_indices_dim not in dimension_numbers.offset_dims and
dimension_numbers.collapsed_slice_dims == (0,)):
offset_dims = tuple(i - 1 if i > start_indices_dim else i
for i in dimension_numbers.offset_dims)
dnums = lax.GatherDimensionNumbers(
offset_dims=offset_dims,
collapsed_slice_dims=dimension_numbers.collapsed_slice_dims,
start_index_map=dimension_numbers.start_index_map)
out = lax.gather(operand, start_indices, dimension_numbers=dnums,
slice_sizes=slice_sizes)
out_dim = start_indices_dim + onp.sum(
onp.less_equal(offset_dims, start_indices_dim))
return out, out_dim
else:
raise NotImplementedError
parallel.papply_primitive_rules[lax.dot_general_p] = _dot_general_papply_rule
parallel.papply_primitive_rules[lax.reshape_p] = _reshape_papply_rule
parallel.papply_primitive_rules[lax.transpose_p] = _transpose_papply_rule
parallel.papply_primitive_rules[lax.select_p] = _select_papply_rule
parallel.papply_primitive_rules[ad_util.add_jaxvals_p] = \
_add_jaxvals_papply_rule
parallel.papply_primitive_rules[lax.convert_element_type_p] = \
_convert_element_type_papply_rule
parallel.papply_primitive_rules[lax.conv_general_dilated_p] = \
_conv_general_dilated_papply_rule
parallel.papply_primitive_rules[lax.broadcast_in_dim_p] = \
_broadcast_in_dim_papply_rule
parallel.papply_primitive_rules[lax.pad_p] = _pad_papply_rule
parallel.papply_primitive_rules[lax.slice_p] = _slice_papply_rule
parallel.papply_primitive_rules[lax.gather_p] = _gather_papply_rule
|
jax-master
|
jax/lax/lax_parallel.py
|
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as onp
from jax.abstract_arrays import ShapedArray
from jax.core import Primitive
from jax.interpreters import xla
from .. import dtypes
from ..interpreters import ad
from ..interpreters import batching
def fft(x, fft_type, fft_lengths=None):
if fft_lengths is None:
fft_lengths = x.shape
elif len(fft_lengths) == 0:
# XLA FFT doesn't support 0-rank.
return x
else:
fft_lengths = tuple(fft_lengths)
return fft_p.bind(x, fft_type=fft_type, fft_lengths=fft_lengths)
def fft_impl(x, fft_type, fft_lengths):
return xla.apply_primitive(fft_p, x, fft_type=fft_type, fft_lengths=fft_lengths)
def fft_abstract_eval(x, fft_type, fft_lengths):
if not dtypes.issubdtype(x.dtype, onp.complexfloating):
raise TypeError("FFT requires complex inputs, got {}.".format(x.dtype.name))
if x.dtype != onp.complex64:
msg = "FFT is only implemented for complex64 types, got {}."
raise NotImplementedError(msg.format(x.dtype.name))
return ShapedArray(x.shape, x.dtype)
def fft_translation_rule(c, x, fft_type, fft_lengths):
return c.Fft(x, fft_type, fft_lengths)
def fft_transpose_rule(t, fft_type, fft_lengths):
return fft(t, fft_type, fft_lengths),
def fft_batching_rule(batched_args, batch_dims, fft_type, fft_lengths):
x, = batched_args
bd, = batch_dims
x = batching.moveaxis(x, bd, 0)
return fft(x, fft_type, fft_lengths), 0
fft_p = Primitive('fft')
fft_p.def_impl(fft_impl)
fft_p.def_abstract_eval(fft_abstract_eval)
xla.translations[fft_p] = fft_translation_rule
ad.deflinear(fft_p, fft_transpose_rule)
batching.primitive_batchers[fft_p] = fft_batching_rule
|
jax-master
|
jax/lax/lax_fft.py
|
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from .lax import *
from .lax import (_reduce_sum, _reduce_max, _reduce_min, _reduce_or,
_reduce_and, _reduce_window_sum, _reduce_window_max,
_reduce_window_min, _reduce_window_prod,
_select_and_gather_add, _float, _complex,
_input_dtype, _const, _eq_meet, _safe_mul,
_broadcasting_select, _check_user_dtype_supported,
_one, _const, _upcast_fp16_for_computation,
_broadcasting_shape_rule)
from .lax_control_flow import *
from .lax_fft import *
from .lax_parallel import *
|
jax-master
|
jax/lax/__init__.py
|
# coding=utf-8
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
"""
Control flow primitives.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import itertools
import operator
import threading
import numpy as onp
import six
from jax import api
from jax import core
from jax import dtypes
from jax.lax import lax
from jax import linear_util as lu
from jax.abstract_arrays import ShapedArray, raise_to_shaped
from jax.api_util import flatten_fun_nokwargs, apply_flat_fun_nokwargs
from jax.interpreters import ad
from jax.interpreters import partial_eval as pe
from jax.interpreters import xla
from jax.interpreters import batching
from jax.interpreters import masking
from jax.lib import xla_bridge as xb
from jax.lib import xla_client
from jax.util import (partial, unzip2, safe_map, safe_zip, split_list,
split_dict, cache)
from jax.tree_util import (tree_flatten, tree_unflatten, treedef_is_leaf,
treedef_children, treedef_tuple)
from jax import ad_util
_map = safe_map
zip = safe_zip
_reduce = six.moves.reduce
@cache()
def _initial_style_jaxpr(fun, in_tree, in_avals):
in_pvals = [pe.PartialVal((aval, core.unit)) for aval in in_avals]
fun, out_tree = flatten_fun_nokwargs(lu.wrap_init(fun), in_tree)
jaxpr, out_pvals, consts = pe.trace_to_jaxpr(fun, in_pvals, instantiate=True,
stage_out_calls=True)
out_avals = _map(raise_to_shaped, unzip2(out_pvals)[0])
const_avals = tuple(raise_to_shaped(core.get_aval(c)) for c in consts)
typed_jaxpr = core.TypedJaxpr(pe.closure_convert_jaxpr(jaxpr),
(), const_avals + in_avals, out_avals)
return typed_jaxpr, consts, out_tree()
def _abstractify(x):
return raise_to_shaped(core.get_aval(x))
def typecheck(aval, x):
aval = raise_to_shaped(aval).strip_weak_type()
try:
return aval == core.lattice_join(aval, core.get_aval(x)).strip_weak_type()
except TypeError:
return False
def typematch(aval1, aval2):
return (raise_to_shaped(aval1).strip_weak_type() ==
raise_to_shaped(aval2).strip_weak_type())
class FixedPointError(Exception): pass
### fori_loop and while_loop
def _fori_cond_fun(loop_carry):
i, upper, _ = loop_carry
return lax.lt(i, upper)
@cache()
def _fori_body_fun(body_fun):
def while_body_fun(loop_carry):
i, upper, x = loop_carry
return lax.add(i, lax._const(i, 1)), upper, body_fun(i, x)
return while_body_fun
def fori_loop(lower, upper, body_fun, init_val):
"""Loop from ``lower`` to ``upper`` by reduction to ``while_loop``.
The type signature in brief is
.. code-block:: haskell
fori_loop :: Int -> Int -> ((int, a) -> a) -> a -> a
The semantics of ``fori_loop`` are given by this Python implementation::
def fori_loop(lower, upper, body_fun, init_val):
val = init_val
for i in range(lower, upper):
val = body_fun(i, val)
return val
Unlike that Python version, ``fori_loop`` is implemented in terms of a call to
``while_loop``. See the docstring for ``while_loop`` for more information.
Also unlike the Python analogue, the loop-carried value ``val`` must hold a
fixed shape and dtype across all iterations (and not just be consistent up to
NumPy rank/shape broadcasting and dtype promotion rules, for example). In
other words, the type ``a`` in the type signature above represents an array
with a fixed shape and dtype (or a nested tuple/list/dict container data
structure with a fixed structure and arrays with fixed shape and dtype at the
leaves).
Args:
lower: an integer representing the loop index lower bound (inclusive)
upper: an integer representing the loop index upper bound (exclusive)
body_fun: function of type ``(int, a) -> a``.
init_val: initial loop carry value of type ``a``.
Returns:
Loop value from the final iteration, of type ``a``.
"""
# TODO: perhaps do more type checking here, for better error messages.
lower_dtype = dtypes.canonicalize_dtype(lax.dtype(lower))
upper_dtype = dtypes.canonicalize_dtype(lax.dtype(upper))
if lower_dtype != upper_dtype:
msg = ("lower and upper arguments to fori_loop must have equal types, "
"got {} and {}")
raise TypeError(msg.format(lower_dtype.name, upper_dtype.name))
_, _, result = while_loop(_fori_cond_fun, _fori_body_fun(body_fun),
(lower, upper, init_val))
return result
def while_loop(cond_fun, body_fun, init_val):
"""Call ``body_fun`` repeatedly in a loop while ``cond_fun`` is True.
The type signature in brief is
.. code-block:: haskell
while_loop :: (a -> Bool) -> (a -> a) -> a -> a
The semantics of ``while_loop`` are given by this Python implementation::
def while_loop(cond_fun, body_fun, init_val):
val = init_val
while cond_fun(val):
val = body_fun(val)
return val
Unlike that Python version, ``while_loop`` is a JAX primitive and is lowered
to a single XLA While HLO. That makes it useful for reducing compilation times
for jit-compiled functions, since native Python loop constructs in an ``@jit``
function are unrolled, leading to large XLA computations.
Also unlike the Python analogue, the loop-carried value ``val`` must hold a
fixed shape and dtype across all iterations (and not just be consistent up to
NumPy rank/shape broadcasting and dtype promotion rules, for example). In
other words, the type ``a`` in the type signature above represents an array
with a fixed shape and dtype (or a nested tuple/list/dict container data
structure with a fixed structure and arrays with fixed shape and dtype at the
leaves).
Another difference from using Python-native loop constructs is that
``while_loop`` is not reverse-mode differentiable because XLA computations
require static bounds on memory requirements.
Args:
cond_fun: function of type ``a -> Bool``.
body_fun: function of type ``a -> a``.
init_val: value of type ``a``, a type that can be a scalar, array, or any
pytree (nested Python tuple/list/dict) thereof, representing the initial
loop carry value.
Returns:
The output from the final iteration of body_fun, of type ``a``.
"""
init_vals, in_tree = tree_flatten((init_val,))
init_avals = tuple(_map(_abstractify, init_vals))
cond_jaxpr, cond_consts, cond_tree = _initial_style_jaxpr(cond_fun, in_tree, init_avals)
body_jaxpr, body_consts, body_tree = _initial_style_jaxpr(body_fun, in_tree, init_avals)
if not treedef_is_leaf(cond_tree) or len(cond_jaxpr.out_avals) != 1:
msg = "cond_fun must return a boolean scalar, but got pytree {}."
raise TypeError(msg.format(cond_tree))
if cond_jaxpr.out_avals[0].strip_weak_type() != ShapedArray((), onp.bool_):
msg = "cond_fun must return a boolean scalar, but got output type(s) {}."
raise TypeError(msg.format(cond_jaxpr.out_avals))
in_tree_children = in_tree.children()
assert len(in_tree_children) == 1
_check_tree_and_avals("body_fun output and input",
# Extract the subtree and avals for the first element of the return tuple
body_tree, body_jaxpr.out_avals,
in_tree_children[0], init_avals)
outs = while_p.bind(*itertools.chain(cond_consts, body_consts, init_vals),
cond_nconsts=len(cond_consts), cond_jaxpr=cond_jaxpr,
body_nconsts=len(body_consts), body_jaxpr=body_jaxpr)
return tree_unflatten(body_tree, outs)
def _while_loop_abstract_eval(*args, **kwargs):
return kwargs["body_jaxpr"].out_avals
def _while_loop_translation_rule(c, axis_env, *args, **kwargs):
backend = kwargs.pop('backend')
cond_jaxpr, body_jaxpr, cond_nconsts, body_nconsts = split_dict(
kwargs, ["cond_jaxpr", "body_jaxpr", "cond_nconsts", "body_nconsts"])
cond_consts, body_consts, init_vals = split_list(args, [cond_nconsts, body_nconsts])
batched = bool(cond_jaxpr.out_avals[0].shape)
# Since jaxprs don't have tuples and have multiple return values, but we need
# the HLO While loop to take a single tuple input and output a single boolean
# (for the cond computation) or a single tuple output (for the body
# computation), we build XLA computations that handle the tuple munging before
# generating a Call into the computations formed from the jaxprs.
init_carry = c.Tuple(*(cond_consts + body_consts + init_vals))
cond_c = xb.make_computation_builder("cond_computation")
cond_carry = cond_c.ParameterWithShape(c.GetShape(init_carry))
cond_carry_elts = [cond_c.GetTupleElement(cond_carry, i) for i in range(len(args))]
x, _, z = split_list(cond_carry_elts, [cond_nconsts, body_nconsts])
pred, = xla.jaxpr_subcomp(cond_c, cond_jaxpr.jaxpr, backend, axis_env,
_map(cond_c.Constant, cond_jaxpr.literals), (), *(x + z))
if batched:
scalar = ShapedArray((), onp.bool_)
or_ = xla.primitive_subcomputation(lax.or_p, scalar, scalar)
pred = cond_c.Reduce(pred, cond_c.Constant(onp.array(False)), or_,
list(range(cond_jaxpr.out_avals[0].ndim)))
body_c = xb.make_computation_builder("body_computation")
body_carry = body_c.ParameterWithShape(c.GetShape(init_carry))
body_carry_elts = [body_c.GetTupleElement(body_carry, i) for i in range(len(args))]
x, y, z = split_list(body_carry_elts, [cond_nconsts, body_nconsts])
new_z = xla.jaxpr_subcomp(body_c, body_jaxpr.jaxpr, backend, axis_env,
_map(body_c.Constant, body_jaxpr.literals), (), *(y + z))
if batched:
body_pred, = xla.jaxpr_subcomp(body_c, cond_jaxpr.jaxpr, backend, axis_env,
_map(body_c.Constant, cond_jaxpr.literals), (), *(x + z))
new_z = _map(partial(_pred_bcast_select, body_c, body_pred), new_z, z)
assert _map(body_c.GetShape, new_z) == _map(body_c.GetShape, z) # no broadcast
new_carry = body_c.Tuple(*itertools.chain(x, y, new_z))
ans = c.While(cond_c.Build(pred), body_c.Build(new_carry), init_carry)
ans_elts = [c.GetTupleElement(ans, i) for i in range(len(args))]
_, _, z = split_list(ans_elts, [cond_nconsts, body_nconsts])
return c.Tuple(*z)
def _pred_bcast_select(c, pred, x, y):
pred_shape = c.GetShape(pred).dimensions()
x_shape = c.GetShape(x).dimensions()
y_shape = c.GetShape(y).dimensions()
assert x_shape == y_shape
assert pred_shape == x_shape[:len(pred_shape)] == y_shape[:len(pred_shape)]
bcast_pred = c.BroadcastInDim(pred, x_shape, list(range(len(pred_shape))))
return c.Select(bcast_pred, x, y)
def _while_loop_batching_rule(args, dims, cond_nconsts, cond_jaxpr,
body_nconsts, body_jaxpr):
size, = {x.shape[d] for x, d in zip(args, dims) if d is not batching.not_mapped}
orig_batched = [d is not batching.not_mapped for d in dims]
cconst_bat, bconst_bat, init_bat = split_list(orig_batched, [cond_nconsts, body_nconsts])
# Fixpoint computation of which carry are batched: either
# batched from init, or the carry out is batched. Each iteration promotes
# at least one carry to batched. We need at most len(carry) iterations,
# but we need one last iteration to prepare the jaxpr based on the final
# carry_bat.
carry_bat = init_bat
for _ in range(1 + len(carry_bat)):
batched = bconst_bat + carry_bat
body_jaxpr_batched, carry_bat_out = batching.batch_jaxpr(
body_jaxpr, size, batched, instantiate=carry_bat)
cond_jaxpr_batched, (pred_bat,) = batching.batch_jaxpr(
cond_jaxpr, size, cconst_bat + carry_bat, instantiate=False)
carry_bat_out = _map(partial(operator.or_, pred_bat), carry_bat_out)
if carry_bat_out == carry_bat:
break
else:
carry_bat = _map(operator.or_, carry_bat, carry_bat_out)
else:
assert False, "Fixpoint not reached"
consts, init = split_list(args, [cond_nconsts + body_nconsts])
const_dims, init_dims = split_list(dims, [cond_nconsts + body_nconsts])
new_consts = [batching.moveaxis(x, d, 0) if d is not batching.not_mapped and d != 0
else x for x, d in zip(consts, const_dims)]
new_init = [batching.broadcast(x, size, 0) if now_bat and not was_bat
else batching.moveaxis(x, d, 0) if now_bat else x
for x, d, was_bat, now_bat in zip(init, init_dims, init_bat, carry_bat)]
outs = while_p.bind(*(new_consts + new_init),
cond_nconsts=cond_nconsts, cond_jaxpr=cond_jaxpr_batched,
body_nconsts=body_nconsts, body_jaxpr=body_jaxpr_batched)
out_bdims = [0 if b else batching.not_mapped for b in carry_bat]
return outs, out_bdims
while_p = lax.Primitive('while')
while_p.multiple_results = True
while_p.def_impl(partial(xla.apply_primitive, while_p))
while_p.def_abstract_eval(_while_loop_abstract_eval)
xla.initial_style_translations[while_p] = _while_loop_translation_rule
batching.primitive_batchers[while_p] = _while_loop_batching_rule
### cond
def cond(pred, true_operand, true_fun, false_operand, false_fun):
"""Conditionally apply ``true_fun`` or ``false_fun``.
Has equivalent semantics to this Python implementation::
def cond(pred, true_operand, true_fun, false_operand, false_fun):
if pred:
return true_fun(true_operand)
else:
return false_fun(false_operand)
Pred has to be a scalar type, collection types (list, tuple) are not supported
"""
if len(onp.shape(pred)) != 0:
raise TypeError("Pred must be a scalar, got {} of shape {}.".format(pred, onp.shape(pred)))
try:
pred_dtype = dtypes.result_type(pred)
except TypeError:
msg = ("Pred type must be either boolean or number, got {}.")
raise TypeError(msg.format(pred))
if pred_dtype.kind != 'b':
if pred_dtype.kind in 'iuf':
pred = pred != 0
else:
msg = ("Pred type must be either boolean or number, got {}.")
raise TypeError(msg.format(pred_dtype))
true_ops, true_tree = tree_flatten((true_operand,))
true_avals = tuple(_map(_abstractify, true_ops))
true_jaxpr, true_consts, true_out_tree = _initial_style_jaxpr(true_fun, true_tree, true_avals)
false_ops, false_tree = tree_flatten((false_operand,))
false_avals = tuple(_map(_abstractify, false_ops))
false_jaxpr, false_consts, false_out_tree = _initial_style_jaxpr(false_fun, false_tree, false_avals)
_check_tree_and_avals("true_fun and false_fun output",
true_out_tree, true_jaxpr.out_avals,
false_out_tree, false_jaxpr.out_avals)
out = cond_p.bind(
*itertools.chain([pred], true_consts, true_ops, false_consts, false_ops),
true_jaxpr=true_jaxpr, false_jaxpr=false_jaxpr,
true_nconsts=len(true_consts), false_nconsts=len(false_consts))
return tree_unflatten(true_out_tree, out)
def _cond_abstract_eval(*args, **kwargs):
return kwargs["true_jaxpr"].out_avals
def _cond_translation_rule(c, axis_env, pred, *args, **kwargs):
backend = kwargs.pop("backend", None)
true_jaxpr, false_jaxpr, true_nconsts, false_nconsts = split_dict(
kwargs, ["true_jaxpr", "false_jaxpr", "true_nconsts", "false_nconsts"])
true_nops = len(true_jaxpr.in_avals) - true_nconsts
true_consts, true_ops, false_consts, false_ops = split_list(
args, [true_nconsts, true_nops, false_nconsts])
def make_computation(name, jaxpr, op_shape):
c = xb.make_computation_builder(name)
op = c.ParameterWithShape(op_shape)
ops = [c.GetTupleElement(op, i) for i in range(len(jaxpr.in_avals))]
outs = xla.jaxpr_subcomp(c, jaxpr.jaxpr, backend, axis_env,
_map(c.Constant, jaxpr.literals), (), *ops)
return c.Build(c.Tuple(*outs))
true_op = c.Tuple(*(true_consts + true_ops))
true_c = make_computation("true_comp", true_jaxpr, c.GetShape(true_op))
false_op = c.Tuple(*(false_consts + false_ops))
false_c = make_computation("false_comp", false_jaxpr, c.GetShape(false_op))
return c.Conditional(pred, true_op, true_c, false_op, false_c)
def _cond_pred_bcast_select(pred, x, y):
bcast_pred = lax.broadcast_in_dim(pred, onp.shape(x), list(range(onp.ndim(pred))))
return lax.select(bcast_pred, x, y)
def _cond_batching_rule(args, dims, true_jaxpr, false_jaxpr, true_nconsts,
false_nconsts):
# TODO: maybe avoid moving arg axes to front if we're promoting to select?
args = [batching.moveaxis(x, d, 0) if d is not batching.not_mapped and d != 0
else x for x, d in zip(args, dims)]
true_nops = len(true_jaxpr.in_avals) - true_nconsts
(pred,), true_consts, true_ops, false_consts, false_ops = split_list(
args, [1, true_nconsts, true_nops, false_nconsts])
size, = {x.shape[d] for x, d in zip(args, dims) if d is not batching.not_mapped}
orig_bat = [d is not batching.not_mapped for d in dims]
(pred_bat,), tconst_bat, t_bat, fconst_bat, f_bat = split_list(
orig_bat, [1, true_nconsts, true_nops, false_nconsts])
_, true_out_bat = batching.batch_jaxpr(true_jaxpr, size, tconst_bat + t_bat, False)
_, false_out_bat = batching.batch_jaxpr(false_jaxpr, size, fconst_bat + f_bat, False)
out_bat = [a or b for a, b in zip(true_out_bat, false_out_bat)]
true_jaxpr_batched, _ = batching.batch_jaxpr(true_jaxpr, size, tconst_bat + t_bat, out_bat)
false_jaxpr_batched, _ = batching.batch_jaxpr(false_jaxpr, size, fconst_bat + f_bat, out_bat)
if pred_bat:
true_out = core.jaxpr_as_fun(true_jaxpr_batched)(*(true_consts + true_ops))
false_out = core.jaxpr_as_fun(false_jaxpr_batched)(*(false_consts + false_ops))
true_out = [batching.broadcast(x, size, 0) if not b else x
for x, b in zip(true_out, out_bat)]
false_out = [batching.broadcast(x, size, 0) if not b else x
for x, b in zip(false_out, out_bat)]
return [_cond_pred_bcast_select(pred, t, f)
for t, f in zip(true_out, false_out)], [0] * len(true_out)
else:
out_dims = [0 if b else batching.not_mapped for b in out_bat]
return cond_p.bind(
*itertools.chain([pred], true_consts, true_ops, false_consts, false_ops),
true_jaxpr=true_jaxpr_batched, false_jaxpr=false_jaxpr_batched,
true_nconsts=len(true_consts), false_nconsts=len(false_consts)), out_dims
cond_p = lax.Primitive('cond')
cond_p.multiple_results = True
cond_p.def_impl(partial(xla.apply_primitive, cond_p))
cond_p.def_abstract_eval(_cond_abstract_eval)
batching.primitive_batchers[cond_p] = _cond_batching_rule
xla.initial_style_translations[cond_p] = _cond_translation_rule
### scan
def scan(f, init, xs, length=None):
"""Scan a function over leading array axes while carrying along state.
The type signature in brief is
.. code-block:: haskell
scan :: (c -> a -> (c, b)) -> c -> [a] -> (c, [b])
where we use [t] here to denote the type t with an additional leading axis.
That is, if t is an array type then [t] represents the type with an additional
leading axis, and if t is a pytree (container) type with array leaves then [t]
represents the type with the same pytree structure and corresponding leaves
each with an additional leading axis.
When ``a`` is an array type or None, and ``b`` is an array type, the semantics
of ``scan`` are given roughly by this Python implementation::
def scan(f, init, xs, length=None):
if xs is None:
xs = [None] * length
carry = init
ys = []
for x in xs:
carry, y = f(carry, x)
ys.append(y)
return carry, np.stack(ys)
Unlike that Python version, both ``a`` and ``b`` may be arbitrary pytree
types, and so multiple arrays can be scanned over at once and produce multiple
output arrays. (None is actually an empty pytree.)
Also unlike that Python version, ``scan`` is a JAX primitive and is lowered to
a single XLA While HLO. That makes it useful for reducing compilation times
for jit-compiled functions, since native Python loop constructs in an ``@jit``
function are unrolled, leading to large XLA computations.
Finally, the loop-carried value ``carry`` must hold a fixed shape and dtype
across all iterations (and not just be consistent up to NumPy rank/shape
broadcasting and dtype promotion rules, for example). In other words, the type
``c`` in the type signature above represents an array with a fixed shape and
dtype (or a nested tuple/list/dict container data structure with a fixed
structure and arrays with fixed shape and dtype at the leaves).
Args:
f: a Python function to be scanned of type ``c -> a -> (c, b)``, meaning
that ``f`` accepts two arguments where the first is a value of the loop
carry and the second is a slice of ``xs`` along its leading axis, and that
``f`` returns a pair where the first element represents a new value for
the loop carry and the second represents a slice of the output.
init: an initial loop carry value of type ``c``, which can be a scalar,
array, or any pytree (nested Python tuple/list/dict) thereof, representing
the initial loop carry value. This value must have the same structure as
the first element of the pair returned by ``f``.
xs: the value of type ``[a]`` over which to scan along the leading axis,
where ``[a]`` can be an array or any pytree (nested Python
tuple/list/dict) thereof with consistent leading axis sizes.
length: optional integer specifying the number of loop iterations, which
must agree with the sizes of leading axes of the arrays in ``xs`` (but can
be used to perform scans where no input ``xs`` are needed).
Returns:
A pair of type ``(c, [b])`` where the first element represents the final
loop carry value and the second element represents the stacked outputs of
the second output of ``f`` when scanned over the leading axis of the inputs.
"""
init_flat, init_tree = tree_flatten(init)
xs_flat, _ = tree_flatten(xs)
in_flat, in_tree = tree_flatten((init, xs))
try:
lengths = [x.shape[0] for x in xs_flat]
except AttributeError:
msg = "scan got value with no leading axis to scan over: {}."
raise ValueError(msg.format(', '.join(str(x) for x in xs_flat
if not hasattr(x, 'shape'))))
if length is not None:
length = int(length)
if not all(length == l for l in lengths):
msg = ("scan got `length` argument of {} which disagrees with "
"leading axis sizes {}.")
raise ValueError(msg.format(length, [x.shape[0] for x in xs_flat]))
else:
unique_lengths = set(lengths)
if len(unique_lengths) > 1:
msg = "scan got values with different leading axis sizes: {}."
raise ValueError(msg.format(', '.join(str(x.shape[0]) for x in xs_flat)))
elif len(unique_lengths) == 0:
msg = "scan got no values to scan over and `length` not provided."
raise ValueError(msg)
else:
length, = unique_lengths
carry_avals = tuple(_map(_abstractify, init_flat))
x_shapes = [masking.padded_shape_as_value(x.shape[1:]) for x in xs_flat]
x_dtypes = [x.dtype for x in xs_flat]
x_avals = tuple(_map(ShapedArray, x_shapes, x_dtypes))
jaxpr, consts, out_tree = _initial_style_jaxpr(f, in_tree, carry_avals + x_avals)
out_tree_children = out_tree.children()
if len(out_tree_children) != 2:
msg = "scan body output must be a pair, got {}."
raise TypeError(msg.format(tree_unflatten(out_tree, jaxpr.out_avals)))
_check_tree_and_avals("scan carry output and input",
# Extract the subtree and avals for the first element of the return tuple
out_tree_children[0], jaxpr.out_avals[:out_tree_children[0].num_leaves],
init_tree, carry_avals)
out = scan_p.bind(*itertools.chain(consts, in_flat),
forward=True, length=length, jaxpr=jaxpr,
num_consts=len(consts), num_carry=len(init_flat),
linear=(False,) * (len(consts) + len(in_flat)))
return tree_unflatten(out_tree, out)
def _scan_impl(*args, **kwargs):
forward, length, num_consts, num_carry, jaxpr, linear = split_dict(
kwargs, ["forward", "length", "num_consts", "num_carry", "jaxpr", "linear"])
consts, init, xs = split_list(args, [num_consts, num_carry])
_, _, x_avals = split_list(jaxpr.in_avals, [num_consts, num_carry])
_, y_avals = split_list(jaxpr.out_avals, [num_carry])
def body_fun(i, vals):
i = i if forward else length - i - 1
carry, ys = split_list(vals, [num_carry])
x = _map(partial(_index_array, i), x_avals, xs)
out_flat = core.jaxpr_as_fun(jaxpr)(*(consts + carry + x))
carry_out, y_updates = split_list(out_flat, [num_carry])
ys_out = _map(partial(_update_array, i), y_avals, ys, y_updates)
return carry_out + ys_out
ys_init = _map(partial(_empty_array, length), y_avals)
return fori_loop(lax._const(length, 0), length, body_fun, init + ys_init)
def _index_array(i, aval, x):
if aval is core.abstract_unit:
return core.unit
else:
return lax.dynamic_index_in_dim(x, i, keepdims=False)
def _empty_array(sz, aval):
if aval is core.abstract_unit:
return core.unit
else:
return lax.full((sz,) + aval.shape, 0, aval.dtype)
def _update_array(i, aval, xs, x):
if aval is core.abstract_unit:
return core.unit
else:
return lax.dynamic_update_index_in_dim(xs, x, i, 0)
def _scan_jvp(primals, tangents, forward, length, jaxpr, num_consts, num_carry,
linear):
num_xs = len(jaxpr.in_avals) - num_carry - num_consts
num_ys = len(jaxpr.out_avals) - num_carry
nonzeros = [t is not ad_util.zero for t in tangents]
const_nz, init_nz, xs_nz = split_list(nonzeros, [num_consts, num_carry])
# Fixpoint computation of which carry are not ad.zero: either
# non-zero from init, or the carry out is non-zero. Each iteration promotes
# at least one carry to non-zero. We need at most len(carry) iterations,
# but we need one last iteration to prepare the jaxpr based on the final
# carry_nz.
carry_nz = init_nz
for _ in range(1 + len(carry_nz)):
nonzeros = const_nz + carry_nz + xs_nz
jaxpr_jvp, nonzeros_out = ad.jvp_jaxpr(
jaxpr, nonzeros, instantiate=carry_nz + [False] * num_ys)
carry_nz_out, ys_nz = nonzeros_out[:num_carry], nonzeros_out[num_carry:]
if carry_nz_out == carry_nz:
break
else:
carry_nz = _map(operator.or_, carry_nz, carry_nz_out)
else:
assert False, "Fixpoint not reached"
tangents = [ad.instantiate_zeros(x, t) if t is ad_util.zero and nz else t
for x, t, nz in zip(primals, tangents, nonzeros)]
consts, init, xs = split_list(primals, [num_consts, num_carry])
all_tangents = split_list(tangents, [num_consts, num_carry])
consts_dot, init_dot, xs_dot = _map(_prune_zeros, all_tangents)
jaxpr_jvp_rearranged = ad.rearrange_binders(
jaxpr_jvp,
[num_consts, num_carry, num_xs], [len(consts_dot), len(init_dot), len(xs_dot)],
[num_carry, num_ys], [len(init_dot), sum(nonzeros_out) - len(init_dot)])
consts_linear, init_linear, xs_linear = split_list(linear, [num_consts, num_carry])
jaxpr_jvp_linear = (consts_linear + [True] * len(consts_dot)
+ init_linear + [True] * len(init_dot)
+ xs_linear + [True] * len(xs_dot))
out_flat = scan_p.bind(
*(consts + consts_dot + init + init_dot + xs + xs_dot),
forward=forward, length=length, jaxpr=jaxpr_jvp_rearranged,
num_consts=num_consts+len(consts_dot), num_carry=num_carry+len(init_dot),
linear=jaxpr_jvp_linear)
carry, carry_dot, ys, ys_dot = split_list(out_flat, [num_carry, len(init_dot), num_ys])
primals_out = carry + ys
tangents_out = iter(carry_dot + ys_dot)
tangents_out = [next(tangents_out) if nz else ad_util.zero for nz in nonzeros_out]
return primals_out, tangents_out
def _prune_zeros(ts):
return [t for t in ts if t is not ad_util.zero]
def _scan_partial_eval(trace, *tracers, **kwargs):
forward, length, num_consts, num_carry, jaxpr, linear = split_dict(
kwargs, ["forward", "length", "num_consts", "num_carry", "jaxpr", "linear"])
num_xs = len(jaxpr.in_avals) - num_carry - num_consts
num_ys = len(jaxpr.out_avals) - num_carry
unknowns = [t.pval[0] is not None for t in tracers]
const_uk, init_uk, xs_uk = split_list(unknowns, [num_consts, num_carry])
# Fixpoint computation of which carry are unknown (not a constant): either
# unknown from init, or the carry out is unknown. Each iteration promotes
# at least one carry to unknown. We need at most len(carry) iterations,
# but we need one last iteration to prepare the jaxpr based on the final
# carry_uk.
carry_uk = init_uk
for _ in range(1 + len(carry_uk)):
unknowns = const_uk + carry_uk + xs_uk
jaxpr_1, jaxpr_2, out_uk = pe.partial_eval_jaxpr(
jaxpr, unknowns, instantiate=carry_uk + [False] * num_ys)
carry_uk_out, ys_uk = out_uk[:num_carry], out_uk[num_carry:]
if carry_uk_out == carry_uk:
break
else:
carry_uk = _map(operator.or_, carry_uk, carry_uk_out)
else:
assert False, "Fixpoint not reached"
num_res = len(jaxpr_1.out_avals) - len(jaxpr_2.out_avals)
# The residuals are treated as extensive outputs of jaxpr_1 (and extensive
# inputs to jaxpr_2), but residuals that are loop-invariant can be hoisted.
# TODO(mattjj): hoist other loop-invariant values here too (instantiate=False)
invariant_pvals = [pe.PartialVal((None, core.unit if uk else t.pval[1]))
for uk, t in zip(unknowns[:num_consts], tracers[:num_consts])]
other_pvals = [pe.PartialVal((a, core.unit)) for a in jaxpr_1.in_avals[num_consts:]]
in_pvals_1 = invariant_pvals + other_pvals
untyped_jaxpr_1, out_pvals_1, consts_1 = pe.trace_to_jaxpr(
lu.wrap_init(core.jaxpr_as_fun(jaxpr_1)), in_pvals_1,
instantiate=[True] * (num_carry + num_ys) + [False] * num_res)
const_avals_1 = [raise_to_shaped(core.get_aval(c)) for c in consts_1]
in_avals_1 = [core.abstract_unit] * num_consts + jaxpr_1.in_avals[num_consts:]
out_avals_1 = [core.abstract_unit if pv is None else pv for pv, c in out_pvals_1]
jaxpr_1_opt = pe.TypedJaxpr(pe.closure_convert_jaxpr(untyped_jaxpr_1),
(), const_avals_1 + in_avals_1, out_avals_1)
num_consts_1 = num_consts + len(consts_1)
# any now-known residuals are intensive, so we want to revise jaxpr_2 to take
# those inputs as constants rather than as extensive inputs
_, _, res_pvals = split_list(out_pvals_1, [num_carry, num_ys])
intensive_residuals = [const for pv, const in res_pvals if pv is None]
move = [False] * len(jaxpr_1.in_avals) + [pv is None for pv, _ in res_pvals]
jaxpr_2_opt = pe.move_binders_to_front(jaxpr_2, move)
num_consts_2 = num_consts + len(intensive_residuals)
in_consts = (list(consts_1) + [core.unit] * num_consts +
[core.unit if uk else t.pval[1]
for uk, t in zip(unknowns[num_consts:], tracers[num_consts:])])
linear_1 = ([False] * len(consts_1) + [True] * num_consts +
[lin or uk for uk, lin in zip(unknowns[num_consts:], linear[num_consts:])])
out_flat = scan_p.bind(
*in_consts, forward=forward, length=length, jaxpr=jaxpr_1_opt,
num_consts=num_consts_1, num_carry=num_carry, linear=linear_1)
out_carry, ys, res_and_units = split_list(out_flat, [num_carry, num_ys])
extensive_residuals = [r for r, (pv, _) in zip(res_and_units, res_pvals) if pv is not None]
new_tracers = [trace.instantiate_const(t) if uk else trace.new_instantiated_literal(core.unit)
for uk, t in zip(unknowns, tracers)]
carry_avals, y_avals = split_list(jaxpr.out_avals, [num_carry])
ys_avals = _map(partial(_promote_aval_rank, length), y_avals)
out_avals = carry_avals + ys_avals
out_pvs = [aval if uk else None for aval, uk in zip(out_avals, out_uk)]
out_consts = out_carry + ys
int_res_tracers = _map(trace.new_instantiated_const, intensive_residuals)
ext_res_tracers = _map(trace.new_instantiated_const, extensive_residuals)
out_tracers = [pe.JaxprTracer(trace, pe.PartialVal((pv, const)), None)
for pv, const in zip(out_pvs, out_consts)]
linear_2 = ([False] * len(int_res_tracers) +
[lin or not uk for uk, lin in zip(unknowns, linear)] +
[False] * len(ext_res_tracers))
eqn = pe.new_eqn_recipe(int_res_tracers + new_tracers + ext_res_tracers,
out_tracers, scan_p, (),
dict(forward=forward, length=length, jaxpr=jaxpr_2_opt,
num_consts=num_consts_2,
num_carry=num_carry, linear=linear_2))
for t in out_tracers: t.recipe = eqn
return out_tracers
def _promote_aval_rank(sz, aval):
if aval is core.abstract_unit:
return core.abstract_unit
else:
return ShapedArray((sz,) + aval.shape, aval.dtype)
def _scan_transpose(cts, *args, **kwargs):
forward, length, num_consts, num_carry, jaxpr, linear = split_dict(
kwargs, ["forward", "length", "num_consts", "num_carry", "jaxpr", "linear"])
# we've only implemented transposing scans with specific lin/nonlin patterns
consts_lin, init_lin, xs_lin = split_list(linear, [num_consts, num_carry])
num_ires = len(consts_lin) - sum(consts_lin)
num_eres = len(xs_lin) - sum(xs_lin)
if consts_lin != [False] * num_ires + [True] * (len(consts_lin) - num_ires):
raise NotImplementedError
if xs_lin != [True] * (len(xs_lin) - num_eres) + [False] * num_eres:
raise NotImplementedError
if not all(init_lin):
raise NotImplementedError
consts, init, xs = split_list(args, [num_consts, num_carry])
ires, consts = split_list(consts, [num_ires])
xs, eres = split_list(xs, [sum(xs_lin)])
assert not any(r is ad.undefined_primal for r in ires)
assert not any(r is ad.undefined_primal for r in eres)
carry_avals, y_avals = split_list(jaxpr.out_avals, [num_carry])
ys_avals = _map(partial(_promote_aval_rank, length), y_avals)
ct_carry, ct_ys = split_list(cts, [num_carry])
ct_carry = _map(ad.instantiate_zeros_aval, carry_avals, ct_carry)
ct_ys = _map(ad.instantiate_zeros_aval, ys_avals, ct_ys)
ct_consts = _map(ad_util.zeros_like_aval, jaxpr.in_avals[num_ires:num_consts])
# jaxpr :: [ires, T d] -> [T c] -> [T a, eres] -> ([T c], [T b])
# jaxpr_trans :: [ires] -> [CT d, CT c] -> [CT b, eres] -> ([CT d, CT c], [CT a])
jaxpr_trans = _transpose_jaxpr(num_ires, num_consts - num_ires, num_eres, jaxpr)
linear_trans = ([False] * num_ires +
[True] * (len(ct_consts) + len(ct_carry) + len(ct_ys)) +
[False] * num_eres)
outs = scan_p.bind(
*(ires + ct_consts + ct_carry + ct_ys + eres), forward=not forward,
length=length, jaxpr=jaxpr_trans, num_consts=num_ires,
num_carry=num_consts-num_ires+num_carry, linear=linear_trans)
ct_consts, ct_init, ct_xs = split_list(outs, [num_consts - num_ires, num_carry])
return [None] * num_ires + ct_consts + ct_init + ct_xs + [None] * num_eres
# transpose_jaxpr :: ([res1, c, a, res2] -> b)
# -> ([res1, CT c, CT b, res2] -> [CT c, CT a])
def _transpose_jaxpr(num_res1, num_c, num_res2, jaxpr):
num_a = len(jaxpr.in_avals) - num_res1 - num_c - num_res2
res1_avals, c_avals, a_avals, res2_avals = split_list(
jaxpr.in_avals, [num_res1, num_c, num_a])
num_b = len(jaxpr.out_avals)
b_avals = list(jaxpr.out_avals)
@lu.wrap_init
def transposed(*res1_cbar_bbar_res2):
res1, c_bar, b_bar, res2 = split_list(
res1_cbar_bbar_res2, [num_res1, num_c, num_b])
primals = res1 + [ad.undefined_primal] * (num_c + num_a) + res2
_, cbar_abar = ad.backward_pass(jaxpr.jaxpr, jaxpr.literals, (), primals,
b_bar)
_, new_c_bar, a_bar, _ = split_list(cbar_abar, [num_res1, num_c, num_a])
a_bar = _map(ad.instantiate_zeros_aval, a_avals, a_bar)
c_bar = _map(ad.instantiate_zeros_aval, c_avals,
_map(ad.add_tangents, c_bar, new_c_bar))
return c_bar + a_bar
return _make_typed_jaxpr(transposed, res1_avals + c_avals + b_avals + res2_avals)
def _make_typed_jaxpr(traceable, in_avals):
pvals = [pe.PartialVal((aval, core.unit)) for aval in in_avals]
jaxpr, pvals_out, consts = pe.trace_to_jaxpr(traceable, pvals, instantiate=True)
out_avals, _ = unzip2(pvals_out)
return core.TypedJaxpr(jaxpr, consts, in_avals, out_avals)
def _scan_batching_rule(args, dims, forward, length, jaxpr, num_consts,
num_carry, linear):
num_ys = len(jaxpr.out_avals) - num_carry
size, = {x.shape[d] for x, d in zip(args, dims) if d is not batching.not_mapped}
orig_batched = [d is not batching.not_mapped for d in dims]
const_batched, init_batched, xs_batched = split_list(orig_batched, [num_consts, num_carry])
# Fixpoint computation of which carry are batched: either
# batched from init, or the carry out is batched. Each iteration promotes
# at least one carry to batched. We need at most len(carry) iterations,
# but we need one last iteration to prepare the jaxpr based on the final
# carry_batched.
carry_batched = init_batched
for _ in range(1 + len(carry_batched)):
batched = const_batched + carry_batched + xs_batched
jaxpr_batched, batched_out = batching.batch_jaxpr(
jaxpr, size, batched, instantiate=carry_batched + [False] * num_ys)
carry_batched_out, ys_batched = batched_out[:num_carry], batched_out[num_carry:]
if carry_batched_out == carry_batched:
break
else:
carry_batched = _map(operator.or_, carry_batched, carry_batched_out)
else:
assert False, "Fixpoint not reached"
consts, init, xs = split_list(args, [num_consts, num_carry])
consts_bdims, init_bdims, xs_bdims = split_list(dims, [num_consts, num_carry])
new_consts = [batching.moveaxis(x, d, 0) if d is not batching.not_mapped and d != 0
else x for x, d in zip(consts, consts_bdims)]
new_init = [batching.broadcast(x, size, 0) if now_batched and not was_batched
else batching.moveaxis(x, d, 0) if now_batched else x
for x, d, was_batched, now_batched in
zip(init, init_bdims, init_batched, carry_batched)]
new_xs = [batching.moveaxis(x, d, 1) if d is not batching.not_mapped and d != 1
else x for x, d in zip(xs, xs_bdims)]
new_args = new_consts + new_init + new_xs
outs = scan_p.bind(*new_args, forward=forward, length=length, jaxpr=jaxpr_batched,
num_consts=num_consts, num_carry=num_carry, linear=linear)
carry_bdims = [0 if b else batching.not_mapped for b in carry_batched]
ys_bdims = [1 if b else batching.not_mapped for b in ys_batched]
return outs, carry_bdims + ys_bdims
def _scan_polymorphic_shape_rule(shape_exprs, forward, length, jaxpr,
num_consts, num_carry, linear):
const_shexprs, init_shexprs, xs_shexprs = split_list(shape_exprs, [num_consts, num_carry])
_, y_avals = split_list(jaxpr.out_avals, [num_carry])
ys_shapes = [ShapeExpr(length, *y_aval.shape) for y_aval in y_avals]
return init_shexprs + ys_shapes
def _scan_masking_rule(shape_envs, padded_vals, shape_exprs, forward, length,
jaxpr, num_consts, num_carry, linear):
out_shape = _scan_polymorphic_shape_rule(shape_exprs, forward, length, jaxpr,
num_consts, num_carry, linear)
dynamic_length = masking.eval_dim_expr(shape_envs.logical, length)
masked_jaxpr = _masked_scan_jaxpr(jaxpr, num_consts, num_carry)
consts, init, xs = split_list(padded_vals, [num_consts, num_carry])
max_length, = {x.shape[0] for x in xs}
const_linear, init_linear, xs_linear = split_list(linear, [num_consts, num_carry])
out_vals = scan_p.bind(
*itertools.chain([dynamic_length] + consts, [0], init, xs),
forward=forward, length=max_length, jaxpr=masked_jaxpr,
num_consts=1 + num_consts, num_carry=1 + num_carry,
linear=[False] + const_linear + [False] + init_linear + xs_linear)
return out_vals[1:], out_shape
def _masked_scan_jaxpr(jaxpr, num_consts, num_carry):
fun = core.jaxpr_as_fun(jaxpr)
@lu.wrap_init
def masked(*args):
[dynamic_length], consts, [i], carry, xs = split_list(
args, [1, num_consts, 1, num_carry])
out = fun(*(consts + carry + xs))
new_carry, ys = split_list(out, [num_carry])
new_carry = [lax.select(i < dynamic_length, new_c, c)
for new_c, c in zip(new_carry, carry)]
return [i + 1] + new_carry + ys
aval = ShapedArray((), dtypes.int_)
const_avals, carry_avals, x_avals = split_list(jaxpr.in_avals, [num_consts, num_carry])
return _make_typed_jaxpr(masked, [aval] + const_avals + [aval] + carry_avals + x_avals)
def scan_bind(*args, **kwargs):
forward, length, num_consts, num_carry, jaxpr, linear = split_dict(
kwargs, ["forward", "length", "num_consts", "num_carry", "jaxpr", "linear"])
consts, init, xs = split_list(args, [num_consts, num_carry])
assert len(linear) == len(args)
# check that args match input types
consts_avals, init_avals, x_avals = split_list(jaxpr.in_avals, [num_consts, num_carry])
xs_avals = _map(partial(_promote_aval_rank, length), x_avals)
assert all(_map(typecheck, consts_avals, consts)), (consts, consts_avals)
assert all(_map(typecheck, init_avals, init))
# assert all(_map(typecheck, xs_avals, xs))
# check that output carry type matches input carry type
carry_avals, _ = split_list(jaxpr.out_avals, [num_carry])
assert all(_map(typematch, init_avals, carry_avals))
# check that the data flow is sensible
core.check_jaxpr(jaxpr.jaxpr)
return core.Primitive.bind(scan_p, *args, forward=forward, length=length,
jaxpr=jaxpr, num_consts=num_consts,
num_carry=num_carry, linear=linear)
scan_p = core.Primitive("scan")
scan_p.multiple_results = True
scan_p.def_custom_bind(scan_bind)
scan_p.def_impl(_scan_impl)
ad.primitive_jvps[scan_p] = _scan_jvp
ad.primitive_transposes[scan_p] = _scan_transpose
pe.custom_partial_eval_rules[scan_p] = _scan_partial_eval
xla.initial_style_translations[scan_p] = xla.lower_fun(_scan_impl, initial_style=True)
batching.primitive_batchers[scan_p] = _scan_batching_rule
masking.shape_parameterized_primitive_rules[scan_p] = _scan_masking_rule
def map(f, xs):
"""Map a function over leading array axes.
Like Python's builtin map, except inputs and outputs are in the form of
stacked arrays. Consider using the ``jax.vmap`` transform instead, unless you
need to apply a function element by element for reduced memory usage or
heterogeneous computation with other control flow primitives.
When ``xs`` is an array type, the semantics of ``map`` are given by this
Python implementation::
def map(f, xs):
return np.stack([f(x) for x in xs])
Like ``scan``, ``map`` is implemented in terms of JAX primitives so many of
the same advantages over a Python loop apply: ``xs`` may be an arbitrary
nested pytree type, and the mapped computation is compiled only once.
Args:
f: a Python function to apply element-wise over the first axis or axes of
``xs``.
xs: values over which to map along the leading axis.
Returns:
Mapped values.
"""
g = lambda _, x: ((), f(x))
_, ys = scan(g, (), xs)
return ys
def _concat_masking_rule(padded_vals, logical_shapes, dimension, operand_shapes):
del operand_shapes # Unused.
result = lax.concatenate(padded_vals, dimension) # fragmented
offset = 0
for padded_val, logical_shape in zip(padded_vals, logical_shapes):
result = _memcpy(dimension, logical_shape[dimension], padded_val,
result, offset)
offset = offset + logical_shape[dimension]
return result
def _memcpy(axis, num, src, dst, offset):
def body(i, dst):
update = lax.dynamic_index_in_dim(src, i, axis)
return lax.dynamic_update_index_in_dim(dst, update, i + offset, axis)
return fori_loop(0, num, body, dst)
masking.masking_rules[lax.concatenate_p] = _concat_masking_rule
def _check_tree(func_name, expected_name, actual_tree, expected_tree):
if actual_tree != expected_tree:
raise TypeError(
"{}() output pytree structure must match {}, got {} and {}."
.format(func_name, expected_name, actual_tree, expected_tree))
def _check_tree_and_avals(what, tree1, avals1, tree2, avals2):
"""Raises TypeError if (tree1, avals1) does not match (tree2, avals2).
Corresponding `tree` and `avals` must match in the sense that the number of leaves in
`tree` must be equal to the length of `avals`.
`what` will be prepended to details of the mismatch in TypeError.
"""
if tree1 != tree2:
msg = ("{} must have same type structure, got {} and {}.")
raise TypeError(msg.format(what, tree1, tree2))
if not all(safe_map(typematch, avals1, avals2)):
msg = ("{} must have identical types, "
"got\n{}\nand\n{}.")
raise TypeError(msg.format(what, tree_unflatten(tree1, avals1),
tree_unflatten(tree2, avals2)))
def _stop_gradient_fun(f):
"""Create a version of f() that stops all gradients."""
def wrapper(*args, **kwargs):
args_flat, in_args_tree = tree_flatten((args, kwargs))
args_avals = tuple(_map(_abstractify, args_flat))
g = lambda a, b: f(*a, **b)
jaxpr, consts, out_tree = _initial_style_jaxpr(g, in_args_tree, args_avals)
out = core.jaxpr_as_fun(jaxpr)(*lax.stop_gradient(consts + tuple(args_flat)))
return tree_unflatten(out_tree, out)
return wrapper
_RootTuple = collections.namedtuple('_RootTuple', 'f, solve, l_and_s')
def _split_root_args(args, const_lengths):
params_list = split_list(args, list(const_lengths))
return _RootTuple(*params_list[:-1]), params_list[-1]
def custom_root(f, initial_guess, solve, tangent_solve):
"""Differentiably solve for a roots of a function.
This is a low-level routine, mostly intended for internal use in JAX.
Gradients of custom_root() are defined with respect to closed-over variables
from the provided function ``f`` via the implicit function theorem:
https://en.wikipedia.org/wiki/Implicit_function_theorem
Args:
f: function for which to find a root. Should accept a single argument,
return a tree of arrays with the same structure as its input.
initial_guess: initial guess for a zero of f.
solve: function to solve for the roots of f. Should take two positional
arguments, f and initial_guess, and return a solution with the same
structure as initial_guess such that func(solution) = 0. In other words,
the following is assumed to be true (but not checked)::
solution = solve(f, initial_guess)
error = f(solution)
assert all(error == 0)
tangent_solve: function to solve the tangent system. Should take two
positional arguments, a linear function ``g`` (the function ``f``
linearized at its root) and a tree of array(s) ``y`` with the same
structure as initial_guess, and return a solution ``x`` such that
``g(x)=y``:
- For scalar ``y``, use ``lambda g, y: y / g(1.0)``.
- For vector ``y``, you could use a linear solve with the Jacobian, if
dimensionality of ``y`` is not too large:
``lambda g, y: np.linalg.solve(jacobian(g)(y), y)``.
Returns:
The result of calling solve(f, initial_guess) with gradients defined via
implicit differentiation assuming ``f(solve(f, initial_guess)) == 0``.
"""
guess_flat, in_args_tree = tree_flatten((initial_guess,))
guess_avals = tuple(_map(_abstractify, guess_flat))
f_jaxpr, f_consts, out_tree = _initial_style_jaxpr(
f, in_args_tree, guess_avals)
in_tree, = treedef_children(in_args_tree)
_check_tree("f", "initial_guess", out_tree, in_tree)
solve_jaxpr, solve_consts, solution_tree = _initial_style_jaxpr(
partial(solve, _stop_gradient_fun(f)), in_args_tree, guess_avals)
_check_tree("solve", "initial_guess", solution_tree, in_tree)
def linearize_and_solve(x, b):
unchecked_zeros, f_jvp = api.linearize(f, x)
return tangent_solve(f_jvp, b)
l_and_s_jaxpr, l_and_s_consts, out_tree = _initial_style_jaxpr(
linearize_and_solve, treedef_tuple((in_tree,) * 2), guess_avals * 2)
_check_tree("tangent_solve", "x", out_tree, in_tree)
all_consts = [f_consts, solve_consts, l_and_s_consts]
const_lengths = _RootTuple(*_map(len, all_consts))
jaxprs = _RootTuple(f_jaxpr, solve_jaxpr, l_and_s_jaxpr)
out_flat = root_p.bind(
*(_flatten(all_consts) + guess_flat),
const_lengths=const_lengths, jaxprs=jaxprs)
return tree_unflatten(out_tree, out_flat)
def _root_abstract_eval(*args, **kwargs):
return _map(raise_to_shaped, args[sum(kwargs['const_lengths']):])
def _root_impl(*args, **kwargs):
const_lengths, jaxprs = split_dict(kwargs, ['const_lengths', 'jaxprs'])
params, initial_guess = _split_root_args(args, const_lengths)
solution = core.jaxpr_as_fun(jaxprs.solve)(*(params.solve + initial_guess))
return solution
def _root_jvp(primals, tangents, const_lengths, jaxprs):
params, _ = _split_root_args(primals, const_lengths)
solution = tuple(root_p.bind(
*primals, const_lengths=const_lengths, jaxprs=jaxprs))
params_dot, _ = _split_root_args(tangents, const_lengths)
# F(m, u) = 0 # system of equations in u, parameterized by m
# # solution is u*(m) defined in a neighborhood
# F(m, u*(m)) = 0 # satisfied in a neighborhood
#
# ∂_0 F(m, u*(m)) + ∂_1 F(m, u*(m)) ∂ u*(m) = 0 # implied by line above
# ∂ u*(m) = - (∂_1 F(m, u*(m)))^{-1} ∂_0 F(m, u*(m)) # rearrange
#
# ∂ u*(m)[v] = - (∂_1 F(m, u*(m)))^{-1} [∂_0 F(m, u*(m))[v]] # jvp
f = core.jaxpr_as_fun(jaxprs.f)
linearize_and_solve = partial(
core.jaxpr_as_fun(jaxprs.l_and_s), *params.l_and_s)
f_at_solution = lambda *params: f(*itertools.chain(params, solution))
_, rhs = ad.jvp(lu.wrap_init(f_at_solution)).call_wrapped(
params.f, params_dot.f)
solution_dot = _map(
operator.neg, linearize_and_solve(*itertools.chain(solution, rhs)))
return solution, solution_dot
root_p = core.Primitive('root')
root_p.multiple_results = True
root_p.def_impl(_root_impl)
root_p.def_abstract_eval(_root_abstract_eval)
ad.primitive_jvps[root_p] = _root_jvp
xla.initial_style_translations[root_p] = xla.lower_fun(
_root_impl, initial_style=True)
# TODO(shoyer): write batching rule
class _LinearSolveTuple(collections.namedtuple(
'_LinearSolveTuple', 'matvec, vecmat, solve, transpose_solve')):
def transpose(self):
return type(self)(self.vecmat, self.matvec, self.transpose_solve, self.solve)
def _split_linear_solve_args(args, const_lengths):
params_list = split_list(args, list(const_lengths))
return _LinearSolveTuple(*params_list[:-1]), params_list[-1]
def _transpose_function(linear_fun, primals):
"""Transpose a linear function."""
# TODO(shoyer): can we use something more direct than the vjp machinery?
# It's particularly awkward that we need the second argument to give
# particular values of the primals, which are entirely arbitrary.
_, vjp_fun = api.vjp(linear_fun, primals)
def transposed_fun(x):
(y,) = vjp_fun(x)
return y
return transposed_fun
def _flatten(args):
return [x for arg in args for x in arg]
def _check_shapes(func_name, expected_name, actual, expected, tree):
actual_shapes = _map(onp.shape, actual)
expected_shapes = _map(onp.shape, expected)
if actual_shapes != expected_shapes:
actual_shape_tree = tree_unflatten(tree, actual_shapes)
act_shape_tree = tree_unflatten(tree, actual_shapes)
raise ValueError('{}() output shapes must match {}, got {} and {}'
.format(func_name, expected_name,
tree_unflatten(tree, actual_shapes),
tree_unflatten(tree, expected_shapes)))
def custom_linear_solve(
matvec, b, solve, transpose_solve=None, symmetric=False):
"""Perform a matrix-free linear solve with implicitly defined gradients.
This function allows for overriding or defining gradients for a linear
solve directly via implicit differentiation at the solution, rather than by
differenting *through* the solve operation. This can sometimes be much faster
or more numerically stable, or differentiating through the solve operation
may not even be implemented (e.g., if ``solve`` uses ``lax.while_loop``).
Required invariant::
x = solve(matvec, b) # solve the linear equation
assert matvec(x) == b # not checked
Args:
matvec: linear function to invert. Must be differentiable.
b: constant right handle side of the equation. May be any nested structure
of arrays.
solve: higher level function that solves for solution to the linear
equation, i.e., ``solve(matvec, x)) == x`` for all ``x`` of the same form
as ``b``. This function need not be differenatiable.
transpose_solve: higher level function for solving the transpose linear
equation, i.e., ``transpose_solve(vecmat, x) == x``, where ``vecmat`` is
the transpose of the linear map ``matvec`` (computed automatically with
autodiff). Required for backwards mode automatic differentiation, unless
``symmetric=True``, in which case ``solve`` provides the default value.
symmetric: bool indicating if it is safe to assume the linear map
corresponds to a symmetric matrix, i.e., ``matvec == vecmat``.
Returns:
Result of ``solve(matvec, b)``, with gradients defined assuming that the
solution ``x`` satisfies the linear equation ``matvec(x) == b``.
"""
if transpose_solve is None and symmetric:
transpose_solve = solve
b_flat, in_args_tree = tree_flatten((b,))
b_avals = tuple(_map(_abstractify, b_flat))
matvec_jaxpr, matvec_consts, out_tree = _initial_style_jaxpr(
matvec, in_args_tree, b_avals)
tree, = treedef_children(in_args_tree)
_check_tree("matvec", "b", out_tree, tree)
solve_jaxpr, solve_consts, out_tree = _initial_style_jaxpr(
partial(solve, matvec), in_args_tree, b_avals)
_check_tree("solve", "b", out_tree, tree)
if transpose_solve is None:
vecmat_jaxpr = tr_solve_jaxpr = None
vecmat_consts = tr_solve_consts = []
else:
if symmetric:
vecmat = matvec
vecmat_jaxpr = matvec_jaxpr
vecmat_consts = matvec_consts
else:
vecmat = _transpose_function(matvec, b)
vecmat_jaxpr, vecmat_consts, out_tree = _initial_style_jaxpr(
vecmat, in_args_tree, b_avals)
assert out_tree == tree
tr_solve_jaxpr, tr_solve_consts, out_tree = _initial_style_jaxpr(
partial(transpose_solve, vecmat), in_args_tree, b_avals)
_check_tree("transpose_solve", "b", out_tree, tree)
all_consts = [matvec_consts, vecmat_consts, solve_consts, tr_solve_consts]
const_lengths = _LinearSolveTuple(*_map(len, all_consts))
jaxprs = _LinearSolveTuple(
matvec_jaxpr, vecmat_jaxpr, solve_jaxpr, tr_solve_jaxpr)
out_flat = linear_solve_p.bind(
*(_flatten(all_consts) + b_flat),
const_lengths=const_lengths, jaxprs=jaxprs, tree=tree)
return tree_unflatten(tree, out_flat)
def _linear_solve_abstract_eval(*args, **kwargs):
return _map(raise_to_shaped, args[sum(kwargs['const_lengths']):])
def _custom_linear_solve_impl(*args, **kwargs):
const_lengths, jaxprs, tree = split_dict(
kwargs, ['const_lengths', 'jaxprs', 'tree'])
params, b = _split_linear_solve_args(args, const_lengths)
x = core.jaxpr_as_fun(jaxprs.solve)(*(params.solve + b))
_check_shapes('solve', 'b', x, b, tree)
return x
def _tangent_linear_map(func, params, params_dot, *x):
"""Compute the tangent of a linear map.
Assuming ``func(*params, *x)`` is linear in ``x`` and computes ``A @ x``,
this function computes ``∂A @ x``.
"""
assert any(p is not ad_util.zero for p in params_dot)
zeros = [ad_util.zero] * len(x)
_, out_tangent = ad.jvp(lu.wrap_init(func)).call_wrapped(
params + list(x), params_dot + zeros)
return out_tangent
def _custom_linear_solve_jvp(primals, tangents, const_lengths, jaxprs, tree):
# A x - b = 0
# ∂A x + A ∂x - ∂b = 0
# ∂x = A^{-1} (∂b - ∂A x)
kwargs = dict(const_lengths=const_lengths, jaxprs=jaxprs, tree=tree)
x = linear_solve_p.bind(*primals, **kwargs)
params, _ = _split_linear_solve_args(primals, const_lengths)
params_dot, b_dot = _split_linear_solve_args(tangents, const_lengths)
if all(p is ad_util.zero for p in params_dot.matvec):
# no need to evaluate matvec_tangents
rhs = b_dot
else:
matvec_tangents = _tangent_linear_map(
core.jaxpr_as_fun(jaxprs.matvec), params.matvec, params_dot.matvec, *x)
_check_shapes("matvec", "b", matvec_tangents, x, tree)
rhs = _map(ad.add_tangents, b_dot, _map(operator.neg, matvec_tangents))
x_dot = linear_solve_p.bind(*(_flatten(params) + rhs), **kwargs)
return x, x_dot
def _linear_solve_transpose_rule(cotangent, *primals, **kwargs):
const_lengths, jaxprs, tree = split_dict(
kwargs, ['const_lengths', 'jaxprs', 'tree'])
if jaxprs.transpose_solve is None:
raise TypeError('transpose_solve required for backwards mode automatic '
'differentiation of custom_linear_solve')
params, b = _split_linear_solve_args(primals, const_lengths)
assert b == [ad.undefined_primal] * len(b)
cotangent_b = linear_solve_p.bind(
*(_flatten(params.transpose()) + cotangent),
const_lengths=const_lengths.transpose(), jaxprs=jaxprs.transpose(),
tree=tree)
return [None] * sum(const_lengths) + cotangent_b
linear_solve_p = core.Primitive('custom_linear_solve')
linear_solve_p.multiple_results = True
linear_solve_p.def_impl(_custom_linear_solve_impl)
linear_solve_p.def_abstract_eval(_linear_solve_abstract_eval)
ad.primitive_jvps[linear_solve_p] = _custom_linear_solve_jvp
xla.initial_style_translations[linear_solve_p] = xla.lower_fun(
_custom_linear_solve_impl, initial_style=True)
ad.primitive_transposes[linear_solve_p] = _linear_solve_transpose_rule
# TODO(shoyer): write batching rule
|
jax-master
|
jax/lax/lax_control_flow.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
"""
Implements the NumPy API, using the primitives in :mod:`jax.lax`.
NumPy operations are implemented in Python in terms of the primitive operations
in :mod:`jax.lax`. Since NumPy operations are not primitive and instead are
implemented in terms of :mod:`jax.lax` operations, we do not need to define
transformation rules such as gradient or batching rules. Instead,
transformations for NumPy primitives can be derived from the transformation
rules for the underlying :code:`lax` primitives.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from distutils.util import strtobool
import collections
try:
from collections.abc import Sequence
except ImportError: # python 2
from collections import Sequence
import itertools
import os
import re
import string
import types
import warnings
import numpy as onp
import opt_einsum
import six
from six.moves import builtins, xrange
from jax import jit, device_put, custom_transforms, defjvp
from .. import core
from .. import dtypes
from ..abstract_arrays import UnshapedArray, ShapedArray, ConcreteArray
from ..config import flags
from ..interpreters.xla import DeviceArray
from .. import lax
from ..util import partial, get_module_functions, unzip2, prod as _prod
from ..lib import pytree
from ..lib import xla_client
FLAGS = flags.FLAGS
flags.DEFINE_enum(
'jax_numpy_rank_promotion', os.getenv('JAX_NUMPY_RANK_PROMOTION', 'allow'),
enum_values=['allow', 'warn', 'raise'],
help=
'Control NumPy-style automatic rank promotion broadcasting '
'("allow", "warn", or "raise").')
if six.PY3:
def removechars(s, chars):
return s.translate(str.maketrans(dict.fromkeys(chars)))
else:
def removechars(s, chars):
return s.translate(None, ''.join(chars))
newaxis = None
# We replace some builtin names to follow Numpy's API, so we capture here.
_abs = builtins.abs
_all = builtins.all
_any = builtins.any
_max = builtins.max
_min = builtins.min
_sum = builtins.sum
_divmod = builtins.divmod
# NumPy constants
pi = onp.pi
e = onp.e
euler_gamma = onp.euler_gamma
inf = onp.inf
NINF = onp.NINF
PZERO = onp.PZERO
NZERO = onp.NZERO
nan = onp.nan
# And some numpy utility functions
set_printoptions = onp.set_printoptions
# We want isinstance(x, np.ndarray) checks in user code to work with the our
# array-like types, including DeviceArray and UnshapedArray (i.e. the abstract
# array base class). We can override the isinstance behavior directly, without
# having the complexity of multiple inheritance on those classes, by defining
# the ndarray class to have a metaclass with special __instancecheck__ behavior.
_arraylike_types = (onp.ndarray, UnshapedArray, DeviceArray)
class _ArrayMeta(type(onp.ndarray)):
"""Metaclass for overriding ndarray isinstance checks."""
def __instancecheck__(self, instance):
try:
return isinstance(instance.aval, _arraylike_types)
except AttributeError:
return isinstance(instance, _arraylike_types)
class ndarray(six.with_metaclass(_ArrayMeta, onp.ndarray)):
def __init__(shape, dtype=None, buffer=None, offset=0, strides=None,
order=None):
raise TypeError("jax.numpy.ndarray() should not be instantiated explicitly."
" Use jax.numpy.array, or jax.numpy.zeros instead.")
iscomplexobj = onp.iscomplexobj
shape = _shape = onp.shape
ndim = _ndim = onp.ndim
size = onp.size
_dtype = dtypes.result_type
# At present JAX doesn't have a reason to distinguish between scalars and arrays
# in its object system. Further, we want JAX scalars to have the same type
# promotion behaviors as JAX arrays. Rather than introducing a new type of JAX
# scalar object with JAX promotion behaviors, instead we make the JAX scalar
# types return JAX arrays when instantiated.
class _ScalarMeta(type):
def __hash__(self):
return hash(self.dtype.type)
def __eq__(self, other):
return id(self) == id(other) or self.dtype == other
def __ne__(self, other):
return not (self == other)
def __call__(self, x):
return array(self.dtype.type(x), dtype=self.dtype)
def _make_scalar_type(onp_scalar_type):
return type(onp_scalar_type.__name__,
(six.with_metaclass(_ScalarMeta, object),),
{"dtype": onp.dtype(onp_scalar_type)})
bool_ = _make_scalar_type(onp.bool_)
uint8 = _make_scalar_type(onp.uint8)
uint16 = _make_scalar_type(onp.uint16)
uint32 = _make_scalar_type(onp.uint32)
uint64 = _make_scalar_type(onp.uint64)
int8 = _make_scalar_type(onp.int8)
int16 = _make_scalar_type(onp.int16)
int32 = _make_scalar_type(onp.int32)
int64 = _make_scalar_type(onp.int64)
bfloat16 = _make_scalar_type(dtypes.bfloat16)
float16 = _make_scalar_type(onp.float16)
float32 = single = _make_scalar_type(onp.float32)
float64 = double = _make_scalar_type(onp.float64)
complex64 = csingle = _make_scalar_type(onp.complex64)
complex128 = cdouble = _make_scalar_type(onp.complex128)
int_ = int32 if dtypes.int_ == onp.int32 else int64
float_ = float32 if dtypes.float_ == onp.float32 else float64
complex_ = complex64 if dtypes.complex_ == onp.complex64 else complex128
number = onp.number
inexact = onp.inexact
complexfloating = onp.complexfloating
floating = onp.floating
integer = onp.integer
signedinteger = onp.signedinteger
unsignedinteger = onp.unsignedinteger
flexible = onp.flexible
character = onp.character
object_ = onp.object_
iinfo = dtypes.iinfo
dtype = onp.dtype
can_cast = dtypes.can_cast
issubsctype = dtypes.issubsctype
result_type = dtypes.result_type
promote_types = dtypes.promote_types
ComplexWarning = onp.ComplexWarning
array_str = onp.array_str
array_repr = onp.array_repr
save = onp.save
savez = onp.savez
load = onp.load
### utility functions
def _promote_shapes(fun_name, *args):
"""Prepend implicit leading singleton dimensions for Numpy broadcasting."""
if len(args) < 2:
return args
else:
shapes = [shape(arg) for arg in args]
nonscalar_ranks = [len(shp) for shp in shapes if shp]
if not nonscalar_ranks or len(set(nonscalar_ranks)) == 1:
return args
else:
if FLAGS.jax_numpy_rank_promotion != "allow":
_rank_promotion_warning_or_error(fun_name, shapes)
result_rank = len(lax.broadcast_shapes(*shapes))
return [lax.reshape(arg, (1,) * (result_rank - len(shp)) + shp)
if shp and len(shp) != result_rank else arg
for arg, shp in zip(args, shapes)]
def _rank_promotion_warning_or_error(fun_name, shapes):
if FLAGS.jax_numpy_rank_promotion == "warn":
msg = ("Following NumPy automatic rank promotion for {} on shapes {}. "
"Set the jax_numpy_rank_promotion config option to 'allow' to "
"disable this warning; for more information, see "
"https://jax.readthedocs.io/en/latest/rank_promotion_warning.html.")
warnings.warn(msg.format(fun_name, ' '.join(map(str, shapes))))
elif FLAGS.jax_numpy_rank_promotion == "raise":
msg = ("Operands could not be broadcast together for {} on shapes {} "
"and with the config option jax_numpy_rank_promotion='raise'. "
"For more information, see "
"https://jax.readthedocs.io/en/latest/rank_promotion_warning.html.")
raise ValueError(msg.format(fun_name, ' '.join(map(str, shapes))))
def _promote_dtypes(*args):
"""Convenience function to apply Numpy argument dtype promotion."""
# TODO(dougalm,mattjj): This is a performance bottleneck. Consider memoizing.
if len(args) < 2:
return args
else:
to_dtype = result_type(*args)
return [lax.convert_element_type(x, to_dtype) for x in args]
def _promote_dtypes_inexact(*args):
"""Convenience function to apply Numpy argument dtype promotion.
Promotes arguments to an inexact type."""
to_dtype = _to_inexact_dtype(result_type(*args))
return [lax.convert_element_type(x, to_dtype) for x in args]
def _to_inexact_dtype(dtype):
"""Promotes a dtype into an inexact dtype, if it is not already one."""
return dtype if issubdtype(dtype, inexact) else promote_types(dtype, float_)
def _complex_elem_type(dtype):
"""Returns the float type of the real/imaginary parts of a complex dtype."""
return onp.abs(onp.zeros((), dtype)).dtype
def _result_dtype(op, *args):
"""Compute result dtype of applying op to arguments with given dtypes."""
args = [onp.ones((0,) * ndim(arg), _dtype(arg)) for arg in args]
return _dtype(op(*args))
def _arraylike(x): return isinstance(x, ndarray) or isscalar(x)
def _check_arraylike(fun_name, *args):
"""Check if all args fit JAX's definition of arraylike (ndarray or scalar)."""
if _any(not _arraylike(arg) for arg in args):
pos, arg = next((i, arg) for i, arg in enumerate(args)
if not _arraylike(arg))
msg = "{} requires ndarray or scalar arguments, got {} at position {}."
raise TypeError(msg.format(fun_name, type(arg), pos))
def _promote_args(fun_name, *args):
"""Convenience function to apply Numpy argument shape and dtype promotion."""
_check_arraylike(fun_name, *args)
return _promote_shapes(fun_name, *_promote_dtypes(*args))
def _promote_args_inexact(fun_name, *args):
"""Convenience function to apply Numpy argument shape and dtype promotion.
Promotes non-inexact types to an inexact type."""
_check_arraylike(fun_name, *args)
return _promote_shapes(fun_name, *_promote_dtypes_inexact(*args))
def _constant_like(x, const):
return onp.array(const, dtype=_dtype(x))
def update_numpydoc(docstr, fun, op):
'''Transforms the numpy docstring to remove references of
parameters that are supported by the numpy version but not the JAX version'''
#Some numpy functions have an extra tab at the beginning of each line,
#If this function is one of those we remove this extra tab from all the lines
if not hasattr(op, '__code__'):
return docstr
if docstr[:4] == ' ':
lines = docstr.split('\n')
for idx, line in enumerate(lines):
lines[idx] = line.replace(' ', '', 1)
docstr = '\n'.join(lines)
begin_idx = docstr.find("Parameters")
begin_idx = docstr.find("--\n", begin_idx) + 2
end_idx = docstr.find("Returns", begin_idx)
parameters = docstr[begin_idx:end_idx]
param_list = parameters.replace('\n ', '@@').split('\n')
for idx, p in enumerate(param_list):
param = p[:p.find(' : ')].split(", ")[0]
if param not in op.__code__.co_varnames:
param_list[idx] = ''
param_list = [param for param in param_list if param != '']
parameters = '\n'.join(param_list).replace('@@', '\n ')
return docstr[:begin_idx + 1] + parameters + docstr[end_idx - 2:]
_numpy_signature_re = re.compile(r'^([\w., ]+=)?\s*[\w\.]+\(.*\)$')
def _wraps(fun, update_doc=True, lax_description=""):
"""Like functools.wraps but works with numpy.ufuncs.
It is important that when wrapping numpy functions the parameters names
in the original function and in the JAX version are the same
Parameters:
fun: The function being wrapped
update_doc: whether to transform the numpy docstring to remove references of
parameters that are supported by the numpy version but not the JAX version.
If False, include the numpy docstring verbatim.
"""
def wrap(op):
if not hasattr(fun, '__doc__') or fun.__doc__ is None:
return op
try:
# Numpy doc comments have the form:
# fn(x, y, z) (optional)
#
# A one-line summary
#
# ... everything else ...
# We (a) move the summary to the top, since it is what the Sphinx
# autosummary extension expects, and (b) add a comment below the summary
# to the effect that this is a LAX wrapper of a Numpy function.
sections = fun.__doc__.split("\n\n")
signatures = []
summary = None
for i in xrange(len(sections)):
if _numpy_signature_re.match(sections[i]):
signatures.append(sections[i])
else:
summary = sections[i].strip()
break
body = "\n\n".join(signatures + sections[i + 1:])
if update_doc:
body = update_numpydoc(body, fun, op)
desc = lax_description + "\n" if lax_description else ""
docstr = (
"{summary}\n\nLAX-backend implementation of :func:`{fun}`.\n"
"{lax_description}Original docstring below.\n\n{body}"
.format(summary=summary, lax_description=desc,
fun=fun.__name__, body=body))
op.__name__ = fun.__name__
op.__doc__ = docstr
finally:
return op
return wrap
def _canonicalize_axis(axis, num_dims):
"""Canonicalize an axis in (-num_dims, num_dims) to [0, num_dims)."""
axis = int(axis)
if axis < 0:
axis = axis + num_dims
if axis < 0 or axis >= num_dims:
raise ValueError(
"axis {} is out of bounds for array of dimension {}".format(
axis, num_dims))
return axis
### implementations of numpy functions in terms of lax
@_wraps(onp.finfo)
def finfo(dtype): return dtypes.finfo(dtype)
@_wraps(onp.issubdtype)
def issubdtype(arg1, arg2): return dtypes.issubdtype(arg1, arg2)
@_wraps(onp.isscalar)
def isscalar(num): return dtypes.is_python_scalar(num) or onp.isscalar(num)
@_wraps(onp.result_type)
def result_type(*args):
return dtypes.result_type(*args)
def _one_to_one_unop(numpy_fn, lax_fn, promote_to_inexact=False):
if promote_to_inexact:
def fn(x):
x = lax.convert_element_type(x, _to_inexact_dtype(_dtype(x)))
return lax_fn(x)
else:
fn = lambda x: lax_fn(x)
return _wraps(numpy_fn)(fn)
def _one_to_one_binop(numpy_fn, lax_fn, promote_to_inexact=False):
if promote_to_inexact:
fn = lambda x1, x2: lax_fn(*_promote_args_inexact(numpy_fn, x1, x2))
else:
fn = lambda x1, x2: lax_fn(*_promote_args(numpy_fn.__name__, x1, x2))
return _wraps(numpy_fn)(fn)
def _maybe_bool_binop(numpy_fn, lax_fn, bool_lax_fn):
def fn(x1, x2):
x1, x2 = _promote_args(numpy_fn.__name__, x1, x2)
return lax_fn(x1, x2) if x1.dtype != bool_ else bool_lax_fn(x1, x2)
return _wraps(numpy_fn)(fn)
absolute = abs = _one_to_one_unop(onp.absolute, lax.abs)
fabs = _one_to_one_unop(onp.fabs, lax.abs, True)
bitwise_not = _one_to_one_unop(onp.bitwise_not, lax.bitwise_not)
negative = _one_to_one_unop(onp.negative, lax.neg)
positive = _one_to_one_unop(onp.positive, lambda x: x)
sign = _one_to_one_unop(onp.sign, lax.sign)
floor = _one_to_one_unop(onp.floor, lax.floor, True)
ceil = _one_to_one_unop(onp.ceil, lax.ceil, True)
exp = _one_to_one_unop(onp.exp, lax.exp, True)
log = _one_to_one_unop(onp.log, lax.log, True)
expm1 = _one_to_one_unop(onp.expm1, lax.expm1, True)
log1p = _one_to_one_unop(onp.log1p, lax.log1p, True)
sin = _one_to_one_unop(onp.sin, lax.sin, True)
cos = _one_to_one_unop(onp.cos, lax.cos, True)
tan = _one_to_one_unop(onp.tan, lax.tan, True)
arcsin = _one_to_one_unop(onp.arcsin, lax.asin, True)
arccos = _one_to_one_unop(onp.arccos, lax.acos, True)
arctan = _one_to_one_unop(onp.arctan, lax.atan, True)
sinh = _one_to_one_unop(onp.sinh, lax.sinh, True)
cosh = _one_to_one_unop(onp.cosh, lax.cosh, True)
tanh = _one_to_one_unop(onp.tanh, lax.tanh, True)
sqrt = _one_to_one_unop(onp.sqrt, lax.sqrt, True)
add = _maybe_bool_binop(onp.add, lax.add, lax.bitwise_or)
bitwise_and = _one_to_one_binop(onp.bitwise_and, lax.bitwise_and)
bitwise_or = _one_to_one_binop(onp.bitwise_or, lax.bitwise_or)
bitwise_xor = _one_to_one_binop(onp.bitwise_xor, lax.bitwise_xor)
right_shift = _one_to_one_binop(onp.right_shift, lax.shift_right_arithmetic)
left_shift = _one_to_one_binop(onp.left_shift, lax.shift_left)
equal = _one_to_one_binop(onp.equal, lax.eq)
multiply = _maybe_bool_binop(onp.multiply, lax.mul, lax.bitwise_and)
not_equal = _one_to_one_binop(onp.not_equal, lax.ne)
subtract = _one_to_one_binop(onp.subtract, lax.sub)
arctan2 = _one_to_one_binop(onp.arctan2, lax.atan2, True)
minimum = _one_to_one_binop(onp.minimum, lax.min)
maximum = _one_to_one_binop(onp.maximum, lax.max)
float_power = _one_to_one_binop(onp.float_power, lax.pow, True)
nextafter = _one_to_one_binop(onp.nextafter, lax.nextafter, True)
def _comparison_op(numpy_fn, lax_fn):
def fn(x1, x2):
x1, x2 = _promote_args(numpy_fn.__name__, x1, x2)
# Comparison on complex types are defined as a lexicographic ordering on
# the (real, imag) pair.
if issubdtype(_dtype(x1), complexfloating):
rx = lax.real(x1)
ry = lax.real(x2)
return lax.select(lax.eq(rx, ry), lax_fn(lax.imag(x1), lax.imag(x2)),
lax_fn(rx, ry))
return lax_fn(x1, x2)
return _wraps(numpy_fn)(fn)
greater_equal = _comparison_op(onp.greater_equal, lax.ge)
greater = _comparison_op(onp.greater, lax.gt)
less_equal = _comparison_op(onp.less_equal, lax.le)
less = _comparison_op(onp.less, lax.lt)
def _logical_op(np_op, bitwise_op):
@_wraps(np_op, update_doc=False)
def op(*args):
zero = lambda x: lax.full_like(x, shape=(), fill_value=0)
args = (x if issubdtype(_dtype(x), bool_) else lax.ne(x, zero(x))
for x in args)
return bitwise_op(*_promote_args(np_op.__name__, *args))
return op
logical_and = _logical_op(onp.logical_and, lax.bitwise_and)
logical_not = _logical_op(onp.logical_not, lax.bitwise_not)
logical_or = _logical_op(onp.logical_or, lax.bitwise_or)
logical_xor = _logical_op(onp.logical_xor, lax.bitwise_xor)
@_wraps(onp.true_divide)
def true_divide(x1, x2):
x1, x2 = _promote_args_inexact("true_divide", x1, x2)
return lax.div(x1, x2)
@_wraps(onp.divide)
def divide(x1, x2):
# decide whether to perform integer division based on Numpy result dtype, as a
# way to check whether Python 3 style division is active in Numpy
result_dtype = _result_dtype(onp.divide, x1, x2)
if issubdtype(result_dtype, integer):
return floor_divide(x1, x2)
else:
return true_divide(x1, x2)
@_wraps(onp.floor_divide)
def floor_divide(x1, x2):
x1, x2 = _promote_args("floor_divide", x1, x2)
dtype = _dtype(x1)
if issubdtype(dtype, integer):
quotient = lax.div(x1, x2)
select = logical_and(lax.sign(x1) != lax.sign(x2), lax.rem(x1, x2) != 0)
# TODO(mattjj): investigate why subtracting a scalar was causing promotion
return where(select, quotient - onp.array(1, _dtype(quotient)), quotient)
elif issubdtype(dtype, complexfloating):
x1r = lax.real(x1)
x1i = lax.imag(x1)
x2r = lax.real(x2)
x2i = lax.imag(x2)
which = lax.ge(lax.abs(x2r), lax.abs(x2i))
rat1 = where(which, lax._const(x2i, 1), lax.div(x2r, x2i))
rat2 = where(which, lax.div(x2i, x2r), lax._const(x2i, 1))
out = lax.floor(lax.div(lax.add(lax.mul(x1r, rat1), lax.mul(x1i, rat2)),
lax.add(lax.mul(x2r, rat1), lax.mul(x2i, rat2))))
return lax.convert_element_type(out, dtype)
else:
return _float_divmod(x1, x2)[0]
@_wraps(onp.divmod)
def divmod(x1, x2):
x1, x2 = _promote_args("divmod", x1, x2)
if issubdtype(_dtype(x1), integer):
return floor_divide(x1, x2), remainder(x1, x2)
else:
return _float_divmod(x1, x2)
def _float_divmod(x1, x2):
# see float_divmod in floatobject.c of CPython
mod = lax.rem(x1, x2)
div = lax.div(lax.sub(x1, mod), x2)
ind = lax.bitwise_and(mod != 0, lax.sign(x2) != lax.sign(mod))
mod = lax.select(ind, mod + x2, mod)
div = lax.select(ind, div - _constant_like(div, 1), div)
return lax.round(div), mod
@_wraps(onp.power)
def power(x1, x2):
x1 = asarray(x1)
x2 = asarray(x2)
x1, x2 = _promote_args(onp.power, x1, x2)
dtype = _dtype(x1)
if not issubdtype(dtype, integer):
return lax.pow(x1, x2)
# Integer power => use binary exponentiation.
# TODO(phawkins): add integer pow support to XLA.
bits = 6 # Anything more would overflow for any x1 > 1
acc = ones(shape(x1), dtype=dtype)
for _ in xrange(bits):
acc = where(lax.bitwise_and(x2, _constant_like(x2, 1)),
lax.mul(acc, x1), acc)
x1 = lax.mul(x1, x1)
x2 = lax.shift_right_logical(x2, _constant_like(x2, 1))
return acc
@_wraps(onp.logaddexp)
def logaddexp(x1, x2):
x1, x2 = _promote_shapes("logaddexp", *_promote_dtypes_inexact(x1, x2))
amax = lax.max(x1, x2)
delta = lax.sub(x1, x2)
return lax.select(isnan(delta),
lax.add(x1, x2), # NaNs or infinities of the same sign.
lax.add(amax, lax.log1p(lax.exp(-lax.abs(delta)))))
@_wraps(onp.logaddexp2)
def logaddexp2(x1, x2):
x1, x2 = _promote_shapes("logaddexp2", *_promote_dtypes_inexact(x1, x2))
amax = lax.max(x1, x2)
delta = lax.sub(x1, x2)
return lax.select(isnan(delta),
lax.add(x1, x2), # NaNs or infinities of the same sign.
lax.add(amax, lax.div(lax.log1p(exp2(-lax.abs(delta))),
_constant_like(x1, onp.log(2)))))
@_wraps(onp.log2)
def log2(x):
x, = _promote_dtypes_inexact(x)
return lax.div(lax.log(x), lax.log(_constant_like(x, 2)))
@_wraps(onp.log10)
def log10(x):
x, = _promote_dtypes_inexact(x)
return lax.div(lax.log(x), lax.log(_constant_like(x, 10)))
@_wraps(onp.exp2)
def exp2(x):
x, = _promote_dtypes_inexact(x)
return lax.exp(lax.mul(lax.log(_constant_like(x, 2)), x))
@_wraps(onp.signbit)
def signbit(x):
x, = _promote_shapes("signbit", x)
dtype = _dtype(x)
if issubdtype(dtype, integer):
return lax.lt(x, _constant_like(x, 0))
elif issubdtype(dtype, bool_):
return full_like(x, False, dtype=bool_)
elif not issubdtype(dtype, floating):
raise ValueError(
"jax.numpy.signbit is not well defined for %s" % dtype)
# TPU supports BF16 but not S16 types, so as a workaround, convert BF16 to
# F32.
if dtype == bfloat16:
dtype = float32
x = lax.convert_element_type(x, float32)
info = finfo(dtype)
if info.bits == 16:
int_type = onp.int16
elif info.bits == 32:
int_type = onp.int32
elif info.bits == 64:
int_type = onp.int64
else:
raise NotImplementedError(
"jax.numpy.signbit only supports 16, 32, and 64-bit types.")
x = lax.bitcast_convert_type(x, int_type)
return lax.convert_element_type(x >> (info.nexp + info.nmant), onp.bool)
@_wraps(onp.remainder)
def remainder(x1, x2):
x1, x2 = _promote_args("remainder", x1, x2)
zero = _constant_like(x1, 0)
trunc_mod = lax.rem(x1, x2)
trunc_mod_not_zero = lax.ne(trunc_mod, zero)
do_plus = lax.bitwise_and(
lax.ne(lax.lt(trunc_mod, zero), lax.lt(x2, zero)), trunc_mod_not_zero)
return lax.select(do_plus, lax.add(trunc_mod, x2), trunc_mod)
mod = remainder
fmod = _wraps(onp.fmod)(lambda x1, x2: lax.rem(x1, x2))
@_wraps(onp.cbrt)
def cbrt(x):
x, = _promote_dtypes_inexact(x)
return lax.sign(x) * power(lax.abs(x), _constant_like(x, 1. / 3.))
@_wraps(onp.square)
def square(x): return lax.mul(x, x)
@_wraps(onp.deg2rad)
def deg2rad(x):
x, = _promote_dtypes_inexact(x)
return lax.mul(x, lax._const(x, pi / 180))
@_wraps(onp.rad2deg)
def rad2deg(x):
x, = _promote_dtypes_inexact(x)
return lax.mul(x, lax._const(x, 180 / pi))
degrees = rad2deg
radians = deg2rad
@_wraps(onp.heaviside)
def heaviside(x1, x2):
x1, x2 = _promote_dtypes_inexact(x1, x2)
zero = lax._const(x1, 0)
return where(lax.lt(x1, zero), zero,
where(lax.gt(x1, zero), lax._const(x1, 1), x2))
@_wraps(onp.hypot)
def hypot(x1, x2):
x1, x2 = _promote_dtypes_inexact(x1, x2)
return lax.sqrt(x1*x1 + x2*x2)
@_wraps(onp.reciprocal)
def reciprocal(x):
x, = _promote_dtypes_inexact(x)
return lax.div(lax._const(x, 1), x)
@_wraps(onp.sinc, update_doc=False)
def sinc(x):
x, = _promote_dtypes_inexact(x)
eq_zero = lax.eq(x, lax._const(x, 0))
safe_x = where(eq_zero, lax._const(x, 0), x)
pi_x = lax.mul(lax._const(x, pi), safe_x)
return where(eq_zero,
lax._const(x, 1), lax.div(lax.sin(pi_x), pi_x))
@_wraps(onp.arcsinh)
@custom_transforms
@jit
@lax._upcast_fp16_for_computation
def arcsinh(x):
# asinh(x) = log(x + sqrt(x**2 + 1))
x, = _promote_dtypes_inexact(x)
one = lax._const(x, 1)
result = lax.log(x + lax.sqrt(x * x + one))
if issubdtype(_dtype(result), complexfloating):
return result
a = abs(x)
sqrt_max_value = onp.sqrt(finfo(_dtype(x)).max)
log2 = lax._const(a, onp.log(2))
return lax.select(a < sqrt_max_value, result, lax.sign(x) * (lax.log(a) + log2))
defjvp(arcsinh, lambda g, ans, x: g / lax.sqrt(lax._const(x, 1) + square(x)))
@_wraps(onp.arccosh)
@jit
@lax._upcast_fp16_for_computation
def arccosh(x):
# acosh(x) = log(x + sqrt((x + 1) * (x - 1))) if x < sqrt_max_value
# log(x) + log(2) otherwise
x, = _promote_dtypes_inexact(x)
one = lax._const(x, 1)
result = lax.log(x + lax.sqrt((x + one) * (x - one)))
if issubdtype(_dtype(result), complexfloating):
return result
sqrt_max_value = onp.sqrt(finfo(_dtype(x)).max)
log2 = lax._const(x, onp.log(2))
return lax.select(x < sqrt_max_value, result, lax.log(x) + log2)
@_wraps(onp.arctanh)
def arctanh(x):
# atanh(x) = 0.5 * log((1 + x) / (1 - x))
x, = _promote_dtypes_inexact(x)
one = lax._const(x, 1)
result = lax._const(x, 0.5) * lax.log((one + x) / (one - x))
if issubdtype(_dtype(result), complexfloating):
return result
return lax.select(abs(x) <= 1, result, lax.full_like(x, onp.nan))
@_wraps(onp.transpose)
def transpose(a, axes=None):
axes = onp.arange(ndim(a))[::-1] if axes is None else axes
return lax.transpose(a, axes)
@_wraps(onp.rot90)
def rot90(m, k=1, axes=(0, 1)):
ax1, ax2 = axes
ax1 = _canonicalize_axis(ax1, m.ndim)
ax2 = _canonicalize_axis(ax2, m.ndim)
if ax1 == ax2:
raise ValueError("Axes must be different") # same as numpy error
k = k % 4
if k == 0:
return m
elif k == 2:
return flip(flip(m, ax1), ax2)
else:
perm = list(range(m.ndim))
perm[ax1], perm[ax2] = perm[ax2], perm[ax1]
if k == 1:
return transpose(flip(m, ax2), perm)
else:
return flip(transpose(m, perm), ax2)
@_wraps(onp.flip)
def flip(m, axis=None):
if axis is None:
return lax.rev(m, list(range(len(m.shape))))
return lax.rev(m, [_canonicalize_axis(axis, len(m.shape))])
@_wraps(onp.fliplr)
def fliplr(m):
return flip(m, 1)
@_wraps(onp.flipud)
def flipud(m):
return flip(m, 0)
@_wraps(onp.conjugate)
def conjugate(x):
return lax.conj(x) if iscomplexobj(x) else x
conj = conjugate
@_wraps(onp.imag)
def imag(val):
return lax.imag(val) if iscomplexobj(val) else zeros_like(val)
@_wraps(onp.real)
def real(val):
return lax.real(val) if iscomplexobj(val) else val
@_wraps(onp.iscomplex)
def iscomplex(x):
i = imag(x)
return lax.ne(i, lax._const(i, 0))
@_wraps(onp.isreal)
def isreal(x):
i = imag(x)
return lax.eq(i, lax._const(i, 0))
@_wraps(onp.angle)
def angle(z):
re = real(z)
im = imag(z)
dtype = _dtype(re)
if not issubdtype(dtype, inexact) or (
issubdtype(_dtype(z), floating) and ndim(z) == 0):
dtype = dtypes.canonicalize_dtype(float_)
re = lax.convert_element_type(re, dtype)
im = lax.convert_element_type(im, dtype)
return lax.atan2(im, re)
@_wraps(onp.diff)
def diff(a, n=1, axis=-1,):
if not isinstance(a, ndarray) or a.ndim == 0:
return a
if n == 0:
return a
if n < 0:
raise ValueError(
"order must be non-negative but got " + repr(n))
nd = a.ndim
slice1 = [slice(None)] * nd
slice2 = [slice(None)] * nd
slice1[axis] = slice(1, None)
slice2[axis] = slice(None, -1)
slice1 = tuple(slice1)
slice2 = tuple(slice2)
op = not_equal if a.dtype == onp.bool_ else subtract
for _ in range(n):
a = op(a[slice1], a[slice2])
return a
@_wraps(onp.isrealobj)
def isrealobj(x):
return not iscomplexobj(x)
@_wraps(onp.reshape)
def reshape(a, newshape, order="C"):
try:
return a.reshape(newshape, order=order) # forward to method for ndarrays
except AttributeError:
return _reshape(a, newshape, order=order)
def _compute_newshape(a, newshape):
"""Fixes a -1 value in newshape, if present."""
# other errors, like having more than one -1, are caught downstream
newsize = _prod(newshape)
if newsize < 0:
fix = a.size // -newsize
return [d if d != -1 else fix for d in newshape]
else:
return newshape
def _reshape(a, newshape, order="C"):
computed_newshape = _compute_newshape(a, newshape)
if order == "C":
return lax.reshape(a, computed_newshape, None)
elif order == "F":
dims = onp.arange(ndim(a))[::-1]
return lax.reshape(a, computed_newshape[::-1], dims).T
elif order == "A":
raise NotImplementedError("np.reshape order=A is not implemented.")
else:
raise ValueError("Unexpected value for 'order' argument: {}.".format(order))
def _reshape_method(a, *newshape, **kwargs):
order = kwargs.pop("order", "C")
if len(kwargs) == 1:
invalid_kwarg, = kwargs
msg = "'{}' is an invalid keyword argument for this function"
raise TypeError(msg.format(invalid_kwarg)) # same as NumPy error
elif kwargs:
invalid_kwargs = "'{}'".format("'".join(kwargs))
msg = "{} are invalid keyword arguments for this function"
raise TypeError(msg.format(invalid_kwargs)) # different from NumPy error
if len(newshape) == 1 and not isinstance(newshape[0], int):
newshape = newshape[0]
return _reshape(a, newshape, order=order)
@_wraps(onp.ravel)
def ravel(a, order="C"):
if order == "K":
raise NotImplementedError("Ravel not implemented for order='K'.")
return reshape(a, (size(a),), order)
@_wraps(onp.squeeze)
def squeeze(a, axis=None):
if 1 not in shape(a):
return a
if axis is None:
newshape = [d for d in shape(a) if d != 1]
else:
if isinstance(axis, int):
axis = (axis,)
axis = frozenset(_canonicalize_axis(i, ndim(a)) for i in axis)
newshape = [d for i, d in enumerate(shape(a))
if d != 1 or i not in axis]
return lax.reshape(a, newshape)
@_wraps(onp.expand_dims)
def expand_dims(a, axis):
shape = _shape(a)
axis = _canonicalize_axis(axis, ndim(a) + 1)
return lax.reshape(a, shape[:axis] + (1,) + shape[axis:])
@_wraps(onp.swapaxes)
def swapaxes(a, axis1, axis2):
perm = onp.arange(ndim(a))
perm[axis1], perm[axis2] = perm[axis2], perm[axis1]
return lax.transpose(a, perm)
@_wraps(onp.moveaxis)
def moveaxis(a, source, destination):
if isinstance(source, int):
source = (source,)
if isinstance(destination, int):
destination = (destination,)
source = tuple(_canonicalize_axis(i, ndim(a)) for i in source)
destination = tuple(_canonicalize_axis(i, ndim(a)) for i in destination)
if len(source) != len(destination):
raise ValueError("Inconsistent number of elements: {} vs {}"
.format(len(source), len(destination)))
perm = [i for i in range(ndim(a)) if i not in source]
for dest, src in sorted(zip(destination, source)):
perm.insert(dest, src)
return lax.transpose(a, perm)
@_wraps(onp.isclose)
def isclose(a, b, rtol=1e-05, atol=1e-08):
a, b = _promote_args("isclose", asarray(a), asarray(b))
dtype = _dtype(a)
if issubdtype(dtype, inexact):
if issubdtype(dtype, complexfloating):
dtype = _complex_elem_type(dtype)
rtol = lax.convert_element_type(rtol, dtype)
atol = lax.convert_element_type(atol, dtype)
out = lax.le(
lax.abs(lax.sub(a, b)),
lax.add(atol, lax.mul(rtol, lax.abs(b))))
return _maybe_numpy_1_13_isclose_behavior(a, out)
else:
return lax.eq(a, b)
numpy_version = tuple(map(int, onp.version.version.split('.')[:2]))
if numpy_version < (1, 14):
# see discussion at https://github.com/numpy/numpy/pull/9720
def _maybe_numpy_1_13_isclose_behavior(a, out):
if size(out) == 1 and issubdtype(_dtype(a), complexfloating):
return lax.reshape(out, (1,))
else:
return out
else:
def _maybe_numpy_1_13_isclose_behavior(a, out):
return out
# The `jit` on `where` exists to avoid materializing constants in cases like
# `np.where(np.zeros(1000), 7, 4)`. In op-by-op mode, we don't want to
# materialize the broadcast forms of scalar arguments.
@jit
def _where(condition, x=None, y=None):
if x is None or y is None:
raise ValueError("Either both or neither of the x and y arguments should "
"be provided to jax.numpy.where, got {} and {}."
.format(x, y))
if not issubdtype(_dtype(condition), bool_):
condition = lax.ne(condition, zeros_like(condition))
x, y = _promote_dtypes(x, y)
condition, x, y = broadcast_arrays(condition, x, y)
return lax.select(condition, x, y) if onp.size(x) else x
_WHERE_DOC = """\
At present, JAX does not support JIT-compilation of the single-argument form
of :py:func:`jax.numpy.where` because its output shape is data-dependent. The
three-argument form does not have a data-dependent shape and can be JIT-compiled
successfully.
"""
@_wraps(onp.where, update_doc=False, lax_description=_WHERE_DOC)
def where(condition, x=None, y=None):
if x is None and y is None:
return nonzero(asarray(condition))
else:
return _where(condition, x, y)
@_wraps(onp.select)
def select(condlist, choicelist, default=0):
if len(condlist) != len(choicelist):
msg = "condlist must have length equal to choicelist ({} vs {})"
raise ValueError(msg.format(len(condlist), len(choicelist)))
if len(condlist) == 0:
raise ValueError("condlist must be non-empty")
choices = _promote_dtypes(default, *choicelist)
choicelist = choices[1:]
output = choices[0]
for cond, choice in zip(condlist[::-1], choicelist[::-1]):
output = where(cond, choice, output)
return output
def broadcast_arrays(*args):
"""Like Numpy's broadcast_arrays but doesn't return views."""
shapes = [shape(arg) for arg in args]
if len(set(shapes)) == 1:
return [arg if isinstance(arg, ndarray) or isscalar(arg) else array(arg)
for arg in args]
result_shape = lax.broadcast_shapes(*shapes)
return [broadcast_to(arg, result_shape) for arg in args]
def broadcast_to(arr, shape):
"""Like Numpy's broadcast_to but doesn't necessarily return views."""
arr = arr if isinstance(arr, ndarray) else array(arr)
shape = tuple(map(int, shape)) # check that shape is concrete
arr_shape = _shape(arr)
if arr_shape == shape:
return arr
else:
nlead = len(shape) - len(arr_shape)
compatible = onp.equal(arr_shape, shape[nlead:]) | onp.equal(arr_shape, 1)
if nlead < 0 or not onp.all(compatible):
msg = "Incompatible shapes for broadcasting: {} and requested shape {}"
raise ValueError(msg.format(arr_shape, shape))
diff, = onp.where(onp.not_equal(shape[nlead:], arr_shape))
new_dims = tuple(range(nlead)) + tuple(nlead + diff)
kept_dims = tuple(onp.delete(onp.arange(len(shape)), new_dims))
return lax.broadcast_in_dim(squeeze(arr, diff), shape, kept_dims)
@_wraps(onp.split)
def split(ary, indices_or_sections, axis=0):
dummy_val = onp.broadcast_to(0, ary.shape) # zero strides
subarrays = onp.split(dummy_val, indices_or_sections, axis) # shapes
split_indices = onp.cumsum([0] + [onp.shape(sub)[axis] for sub in subarrays])
starts, ends = [0] * ndim(ary), shape(ary)
_subval = lambda x, i, v: lax.subvals(x, [(i, v)])
return [lax.slice(ary, _subval(starts, axis, start), _subval(ends, axis, end))
for start, end in zip(split_indices[:-1], split_indices[1:])]
def _split_on_axis(onp_fun, axis):
@_wraps(onp_fun, update_doc=False)
def f(ary, indices_or_sections):
return split(ary, indices_or_sections, axis=axis)
return f
vsplit = _split_on_axis(onp.vsplit, axis=0)
hsplit = _split_on_axis(onp.hsplit, axis=1)
dsplit = _split_on_axis(onp.dsplit, axis=2)
@_wraps(onp.clip)
def clip(a, a_min=None, a_max=None):
if a_min is None and a_max is None:
raise "At most one of a_min and a_max may be None"
if a_min is not None:
if _dtype(a_min) != _dtype(a):
a_min = lax.convert_element_type(a_min, _dtype(a))
a = maximum(a_min, a)
if a_max is not None:
if _dtype(a_max) != _dtype(a):
a_max = lax.convert_element_type(a_max, _dtype(a))
a = minimum(a_max, a)
return a
def _dtype_info(dtype):
"""Helper function for to get dtype info needed for clipping."""
if issubdtype(dtype, integer):
return iinfo(dtype)
return finfo(dtype)
def _round_to_nearest_even(x):
half = lax._const(x, 0.5)
one = lax._const(x, 1)
round_val = lax.floor(x)
fraction = x - round_val
nearest_even_int = lax.sub(
round_val, lax.mul(lax._const(x, 2), lax.floor(lax.mul(half, x))))
is_odd = lax.eq(nearest_even_int, one)
return lax.select(
lax.bitwise_or(lax.gt(fraction, half),
lax.bitwise_and(lax.eq(fraction, half), is_odd)),
lax.add(round_val, one), round_val)
@_wraps(onp.round, update_doc=False)
def round(a, decimals=0):
dtype = _dtype(a)
if issubdtype(dtype, integer):
if decimals < 0:
raise NotImplementedError(
"integer np.round not implemented for decimals < 0")
return a # no-op on integer types
def _round_float(x):
if decimals == 0:
return _round_to_nearest_even(x)
# TODO(phawkins): the strategy of rescaling the value isn't necessarily a
# good one since we may be left with an incorrectly rounded value at the
# end due to precision problems. As a workaround for float16, convert to
# float32,
x = lax.convert_element_type(x, onp.float32) if dtype == onp.float16 else x
factor = _constant_like(x, 10 ** decimals)
out = lax.div(_round_to_nearest_even(lax.mul(x, factor)), factor)
return lax.convert_element_type(out, dtype) if dtype == onp.float16 else out
if issubdtype(dtype, complexfloating):
return lax.complex(_round_float(lax.real(a)), _round_float(lax.imag(a)))
else:
return _round_float(a)
around = round
@_wraps(onp.fix)
def fix(x, out=None):
if out is not None:
raise ValueError("fix does not support the `out` argument.")
zero = lax._const(x, 0)
return where(lax.ge(x, zero), lax.floor(x), lax.ceil(x))
@_wraps(onp.isfinite)
def isfinite(x):
dtype = _dtype(x)
if issubdtype(dtype, floating):
return lax.is_finite(x)
elif issubdtype(dtype, complexfloating):
return lax.bitwise_and(lax.is_finite(real(x)), lax.is_finite(imag(x)))
else:
return full_like(x, True, dtype=bool_)
@_wraps(onp.isinf)
def isinf(x):
dtype = _dtype(x)
if issubdtype(dtype, floating):
return lax.eq(lax.abs(x), _constant_like(x, inf))
elif issubdtype(dtype, complexfloating):
re = lax.real(x)
im = lax.imag(x)
return lax.bitwise_or(lax.eq(lax.abs(re), _constant_like(re, inf)),
lax.eq(lax.abs(im), _constant_like(im, inf)))
else:
return full_like(x, False, dtype=bool_)
def _isposneginf(infinity, x):
dtype = _dtype(x)
if issubdtype(dtype, floating):
return lax.eq(x, _constant_like(x, infinity))
elif issubdtype(dtype, complexfloating):
raise ValueError("isposinf/isneginf are not well defined for complex types")
else:
return full_like(x, False, dtype=bool_)
isposinf = _wraps(onp.isposinf)(partial(_isposneginf, inf))
isneginf = _wraps(onp.isneginf)(partial(_isposneginf, -inf))
@_wraps(onp.isnan)
def isnan(x):
return lax.bitwise_and(lax.bitwise_not(isfinite(x)),
lax.bitwise_not(isinf(x)))
@_wraps(onp.nan_to_num)
def nan_to_num(x, copy=True):
del copy
dtype = _dtype(x)
if issubdtype(dtype, complexfloating):
return lax.complex(nan_to_num(lax.real(x)), nan_to_num(lax.imag(x)))
info = finfo(dtypes.canonicalize_dtype(dtype))
x = where(isnan(x), _constant_like(x, 0), x)
x = where(isposinf(x), _constant_like(x, info.max), x)
x = where(isneginf(x), _constant_like(x, info.min), x)
return x
### Reducers
def _make_reduction(np_fun, op, init_val, preproc=None, bool_op=None,
upcast_f16_for_computation=False):
"""Creates reduction function given a binary operation and monoid identity."""
bool_op = bool_op or op
@_wraps(np_fun)
def reduction(a, axis=None, dtype=None, out=None, keepdims=False):
if out is not None:
raise ValueError("reduction does not support the `out` argument.")
a = a if isinstance(a, ndarray) else asarray(a)
a = preproc(a) if preproc else a
dims = _reduction_dims(a, axis)
result_dtype = dtype or _dtype(np_fun(onp.ones((), dtype=_dtype(a))))
if upcast_f16_for_computation and issubdtype(result_dtype, inexact):
computation_dtype = promote_types(result_dtype, float32)
else:
computation_dtype = result_dtype
a = lax.convert_element_type(a, computation_dtype)
result = lax.reduce(a, _reduction_init_val(a, init_val),
op if computation_dtype != onp.bool_ else bool_op, dims)
if keepdims:
shape_with_singletons = lax.subvals(shape(a), zip(dims, (1,) * len(dims)))
result = lax.reshape(result, shape_with_singletons)
return lax.convert_element_type(result, dtype or result_dtype)
return reduction
def _reduction_dims(a, axis):
if axis is None:
return onp.arange(ndim(a))
elif isinstance(axis, (onp.ndarray, tuple, list)):
return tuple(_canonicalize_axis(x, ndim(a)) for x in axis)
elif isinstance(axis, int):
return (_canonicalize_axis(axis, ndim(a)),)
else:
raise TypeError("Unexpected type of axis argument: {}".format(type(axis)))
def _reduction_init_val(a, init_val):
a_dtype = dtypes.canonicalize_dtype(_dtype(a))
if a_dtype == 'bool':
return onp.array(init_val > 0, dtype=a_dtype)
try:
return onp.array(init_val, dtype=a_dtype)
except OverflowError:
assert issubdtype(a_dtype, integer)
sign, info = onp.sign(init_val), iinfo(a_dtype)
return onp.array(info.min if sign < 0 else info.max, dtype=a_dtype)
_cast_to_bool = partial(lax.convert_element_type, new_dtype=bool_)
sum = _make_reduction(onp.sum, lax.add, 0, upcast_f16_for_computation=True,
bool_op=lax.bitwise_or)
product = prod = _make_reduction(onp.prod, lax.mul, 1, bool_op=lax.bitwise_and,
upcast_f16_for_computation=True)
amax = max = _make_reduction(onp.max, lax.max, -onp.inf)
amin = min = _make_reduction(onp.min, lax.min, onp.inf)
all = alltrue = _make_reduction(onp.all, lax.bitwise_and, True, _cast_to_bool)
any = sometrue = _make_reduction(onp.any, lax.bitwise_or, False, _cast_to_bool)
@_wraps(onp.mean)
def mean(a, axis=None, dtype=None, out=None, keepdims=False):
if out is not None:
raise ValueError("mean does not support the `out` argument.")
if axis is None:
normalizer = size(a)
else:
normalizer = onp.prod(onp.take(shape(a), axis))
if dtype is None:
if issubdtype(_dtype(a), bool_) or issubdtype(_dtype(a), integer):
dtype = float_
else:
dtype = _dtype(a)
return lax.div(
sum(a, axis, dtype=dtype, keepdims=keepdims),
lax.convert_element_type(normalizer, dtype))
@_wraps(onp.average)
def average(a, axis=None, weights=None, returned=False):
a = asarray(a)
if weights is None: # Treat all weights as 1
avg = mean(a, axis=axis)
if axis is None:
weights_sum = full((), size(a), dtype=avg.dtype)
else:
weights_sum = full_like(avg, a.shape[axis], dtype=avg.dtype)
else:
weights = asarray(weights)
if issubdtype(a.dtype, inexact):
out_dtype = result_type(a.dtype, weights.dtype)
else:
out_dtype = result_type(a.dtype, weights.dtype, float_)
out_dtype = dtypes.canonicalize_dtype(out_dtype)
a_shape = shape(a)
a_ndim = len(a_shape)
weights_shape = shape(weights)
axis = None if axis is None else _canonicalize_axis(axis, a_ndim)
if a_shape != weights_shape:
# Make sure the dimensions work out
if axis is None:
raise ValueError("Axis must be specified when shapes of a and "
"weights differ.")
if len(weights_shape) != 1:
raise ValueError("1D weights expected when shapes of a and "
"weights differ.")
if weights_shape[0] != a_shape[axis]:
raise ValueError("Length of weights not "
"compatible with specified axis.")
weights = broadcast_to(weights, (a_ndim - 1) * (1,) + weights_shape)
weights = moveaxis(weights, -1, axis)
weights_sum = sum(weights, axis=axis, dtype=out_dtype)
avg = sum(multiply(a, weights), axis=axis, dtype=out_dtype) / weights_sum
if returned:
if avg.shape != weights_sum.shape:
weights_sum = broadcast_to(weights_sum, avg.shape)
return avg, weights_sum
return avg
@_wraps(onp.var)
def var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False):
if out is not None:
raise ValueError("var does not support the `out` argument.")
a_dtype = _dtype(a)
if dtype:
a_dtype = promote_types(a_dtype, dtype)
else:
if not issubdtype(a_dtype, inexact):
dtype = a_dtype = float_
else:
dtype = _complex_elem_type(a_dtype)
a_dtype = promote_types(a_dtype, float32)
a_mean = mean(a, axis, dtype=a_dtype, keepdims=True)
centered = a - a_mean
if issubdtype(centered.dtype, complexfloating):
centered = lax.real(lax.mul(centered, lax.conj(centered)))
else:
centered = lax.square(centered)
if axis is None:
normalizer = size(a)
else:
normalizer = onp.prod(onp.take(shape(a), axis))
normalizer = normalizer - ddof
result = sum(centered, axis, keepdims=keepdims)
out = lax.div(result, lax.convert_element_type(normalizer, result.dtype))
return lax.convert_element_type(out, dtype)
@_wraps(onp.std)
def std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False):
if out is not None:
raise ValueError("std does not support the `out` argument.")
return sqrt(var(a, axis=axis, dtype=dtype, ddof=ddof, keepdims=keepdims))
@_wraps(onp.ptp)
def ptp(a, axis=None, out=None, keepdims=False):
if out is not None:
raise ValueError("ptp does not support the `out` argument.")
x = amax(a, axis=axis, keepdims=keepdims)
y = amin(a, axis=axis, keepdims=keepdims)
return lax.sub(x, y)
@_wraps(onp.allclose)
def allclose(a, b, rtol=1e-05, atol=1e-08):
return all(isclose(a, b, rtol, atol))
@_wraps(onp.count_nonzero)
def count_nonzero(a, axis=None):
return sum(lax.ne(a, _constant_like(a, 0)), axis=axis,
dtype=dtypes.canonicalize_dtype(onp.int_))
_NONZERO_DOC = """\
At present, JAX does not support JIT-compilation of :py:func:`jax.numpy.nonzero`
because its output shape is data-dependent.
"""
@_wraps(onp.nonzero, lax_description=_NONZERO_DOC)
def nonzero(a):
# Note: this function cannot be jitted because its output has a dynamic
# shape.
a = atleast_1d(a)
dims = shape(a)
ndims = len(dims)
ds = [lax.broadcasted_iota(int_, dims + (1,), i) for i in range(ndims)]
d = concatenate(ds, axis=-1)
indexes = d[a != 0]
return tuple(indexes[..., i] for i in range(ndims))
def _make_nan_reduction(onp_reduction, np_reduction, init_val, nan_if_all_nan):
@_wraps(onp_reduction)
def nan_reduction(a, axis=None, out=None, keepdims=False, **kwargs):
out = np_reduction(where(isnan(a), _reduction_init_val(a, init_val), a),
axis=axis, out=out, keepdims=keepdims, **kwargs)
if nan_if_all_nan:
return where(all(isnan(a), axis=axis, keepdims=keepdims),
_constant_like(a, nan), out)
else:
return out
return nan_reduction
nanmin = _make_nan_reduction(onp.nanmin, min, inf, nan_if_all_nan=True)
nanmax = _make_nan_reduction(onp.nanmax, max, -inf, nan_if_all_nan=True)
nansum = _make_nan_reduction(onp.nansum, sum, 0, nan_if_all_nan=False)
nanprod = _make_nan_reduction(onp.nanprod, prod, 1, nan_if_all_nan=False)
@_wraps(onp.nanmean)
def nanmean(a, axis=None, dtype=None, out=None, keepdims=False):
if out is not None:
raise ValueError("nanmean does not support the `out` argument.")
if issubdtype(_dtype(a), bool_) or issubdtype(_dtype(a), integer):
return mean(a, axis, dtype, out, keepdims)
if dtype is None:
dtype = _dtype(a)
nan_mask = logical_not(isnan(a))
normalizer = sum(nan_mask, axis=axis, dtype=int32, keepdims=keepdims)
normalizer = lax.convert_element_type(normalizer, dtype)
td = lax.div(nansum(a, axis, dtype=dtype, keepdims=keepdims), normalizer)
return td
def _make_cumulative_reduction(onp_reduction, window_reduce, init_val,
squash_nan=False):
# We want to allow XLA to fuse the pad and reduce-window operators to
# avoid materializing the padded output.
# Consider removing `jit` once again if reduce-window is generalized to
# support arbitrary padding.
@partial(jit, static_argnums=(1, 2))
def _cumulative_reduction(a, axis, dtype):
if axis is None or isscalar(a):
a = ravel(a)
axis = 0
a_shape = list(shape(a))
num_dims = len(a_shape)
if axis < 0:
axis = axis + num_dims
if axis < 0 or axis >= num_dims:
raise ValueError(
"axis {} is out of bounds for array of dimension {}".format(
axis, num_dims))
if squash_nan:
a = where(isnan(a), _constant_like(a, init_val), a)
if dtype:
a = lax.convert_element_type(a, dtype)
if a_shape[axis] == 0:
return a
padding = [(0, 0, 0)] * num_dims
padding[axis] = (a_shape[axis] - 1, 0, 0)
a = lax.pad(a, _constant_like(a, init_val), padding)
strides = [1] * num_dims
window_dims = [1] * num_dims
window_dims[axis] = a_shape[axis]
return window_reduce(
a, window_dims, strides, xla_client.PaddingType.VALID)
@_wraps(onp_reduction)
def cumulative_reduction(a, axis=None, dtype=None):
# jit doesn't support kwargs as static_args.
return _cumulative_reduction(a, axis, dtype)
return cumulative_reduction
cumsum = _make_cumulative_reduction(
onp.cumsum, lax._reduce_window_sum, 0, squash_nan=False)
cumprod = _make_cumulative_reduction(
onp.cumprod, lax._reduce_window_prod, 1, squash_nan=False)
cumproduct = cumprod
nancumsum = _make_cumulative_reduction(
onp.nancumsum, lax._reduce_window_sum, 0, squash_nan=True)
nancumprod = _make_cumulative_reduction(
onp.nancumprod, lax._reduce_window_prod, 1, squash_nan=True)
### Array-creation functions
def _check_no_padding(axis_padding, mode):
if (axis_padding[0] > 0 or axis_padding[1] > 0):
msg = "Cannot apply '{}' padding to empty axis"
raise ValueError(msg.format(mode))
@partial(jit, static_argnums=(1, 2))
def _pad(array, pad_width, mode, constant_values):
array = asarray(array)
nd = ndim(array)
pad_width = onp.broadcast_to(onp.asarray(pad_width), (nd, 2))
if any(pad_width < 0):
raise ValueError("index can't contain negative values")
if mode == "constant":
constant_values = broadcast_to(asarray(constant_values), (nd, 2))
constant_values = lax.convert_element_type(constant_values, array.dtype)
for i in xrange(nd):
widths = [(0, 0, 0)] * nd
widths[i] = (pad_width[i, 0], 0, 0)
array = lax.pad(array, constant_values[i, 0], widths)
widths[i] = (0, pad_width[i, 1], 0)
array = lax.pad(array, constant_values[i, 1], widths)
return array
elif mode == "wrap":
for i in xrange(nd):
if array.shape[i] == 0:
_check_no_padding(pad_width[i], mode)
continue
size = array.shape[i]
repeats, (left_remainder, right_remainder) = _divmod(pad_width[i], size)
total_repeats = repeats.sum() + 1
parts = []
if left_remainder:
parts += [lax.slice_in_dim(array, size - left_remainder, size, axis=i)]
parts += total_repeats * [array]
if right_remainder:
parts += [lax.slice_in_dim(array, 0, right_remainder, axis=i)]
array = lax.concatenate(parts, dimension=i)
return array
elif mode in ("symmetric", "reflect"):
for i in xrange(nd):
if array.shape[i] == 0:
_check_no_padding(pad_width[i], mode)
continue
n = array.shape[i]
rarray = lax.rev(array, dimensions=(i,))
offset = 1 if (mode == "reflect" and n > 1) else 0
def build_padding(padding, forward):
xs = []
delta = n - offset
while padding > delta:
padding -= delta
p = array if forward else rarray
xs.append(lax.slice_in_dim(p, offset, n, axis=i))
forward = not forward
if padding > 0:
x = lax.slice_in_dim(array if forward else rarray, offset,
padding + offset, axis=i)
xs.append(x)
return xs
parts = reversed(build_padding(pad_width[i, 0], forward=True))
parts = [lax.rev(x, dimensions=(i,)) for x in parts]
parts += [array]
parts += build_padding(pad_width[i, 1], forward=False)
array = lax.concatenate(parts, dimension=i)
return array
else:
msg = "Unimplemented padding mode '{}' for np.pad."
raise NotImplementedError(msg.format(mode))
@_wraps(onp.pad)
def pad(array, pad_width, mode='constant', constant_values=0):
return _pad(array, pad_width, mode, constant_values)
@_wraps(onp.stack)
def stack(arrays, axis=0):
if not len(arrays):
raise ValueError("Need at least one array to stack.")
shape0 = shape(arrays[0])
axis = _canonicalize_axis(axis, len(shape0) + 1)
new_shape = list(shape0)
new_shape.insert(axis, 1)
new_arrays = []
for a in arrays:
if shape(a) != shape0:
raise ValueError("All input arrays must have the same shape.")
new_arrays.append(reshape(a, new_shape))
return concatenate(new_arrays, axis=axis)
@_wraps(onp.tile)
def tile(a, reps):
if isinstance(reps, int):
reps = (reps,)
a = reshape(a, (1,) * (len(reps) - ndim(a)) + shape(a))
reps = (1,) * (ndim(a) - len(reps)) + tuple(reps)
for i, rep in enumerate(reps):
a = concatenate([a] * int(rep), axis=i)
return a
@_wraps(onp.concatenate)
def concatenate(arrays, axis=0):
if not len(arrays):
raise ValueError("Need at least one array to concatenate.")
if ndim(arrays[0]) == 0:
raise ValueError("Zero-dimensional arrays cannot be concatenated.")
axis = _canonicalize_axis(axis, ndim(arrays[0]))
arrays = _promote_dtypes(*arrays)
# lax.concatenate can be slow to compile for wide concatenations, so form a
# tree of concatenations as a workaround especially for op-by-op mode.
# (https://github.com/google/jax/issues/653).
k = 16
while len(arrays) > 1:
arrays = [lax.concatenate(arrays[i:i+k], axis)
for i in range(0, len(arrays), k)]
return arrays[0]
@_wraps(onp.vstack)
def vstack(tup):
return concatenate([atleast_2d(m) for m in tup], axis=0)
row_stack = vstack
@_wraps(onp.hstack)
def hstack(tup):
arrs = [atleast_1d(m) for m in tup]
if arrs[0].ndim == 1:
return concatenate(arrs, 0)
return concatenate(arrs, 1)
@_wraps(onp.dstack)
def dstack(tup):
return concatenate([atleast_3d(m) for m in tup], axis=2)
@_wraps(onp.column_stack)
def column_stack(tup):
arrays = []
for v in tup:
arr = array(v)
if arr.ndim < 2:
arr = arr.reshape((-1, 1))
arrays.append(arr)
return concatenate(arrays, 1)
@_wraps(onp.atleast_1d, update_doc=False)
def atleast_1d(*arys):
if len(arys) == 1:
arr = array(arys[0])
return arr if ndim(arr) >= 1 else reshape(arr, -1)
else:
return [atleast_1d(arr) for arr in arys]
@_wraps(onp.atleast_2d, update_doc=False)
def atleast_2d(*arys):
if len(arys) == 1:
arr = array(arys[0])
return arr if ndim(arr) >= 2 else reshape(arr, (1, -1))
else:
return [atleast_2d(arr) for arr in arys]
@_wraps(onp.atleast_3d, update_doc=False)
def atleast_3d(*arys):
if len(arys) == 1:
arr = array(arys[0])
if ndim(arr) <= 1:
arr = reshape(arr, (1, -1, 1))
elif ndim(arr) == 2:
arr = reshape(arr, shape(arr) + (1,))
return arr
else:
return [atleast_3d(arr) for arr in arys]
@_wraps(onp.array)
def array(object, dtype=None, copy=True, order="K", ndmin=0):
if order is not None and order != "K":
raise NotImplementedError("Only implemented for order='K'")
lax._check_user_dtype_supported(dtype, "array")
if isinstance(object, ndarray):
if dtype and _dtype(object) != dtypes.canonicalize_dtype(dtype):
out = lax.convert_element_type(object, dtype)
else:
out = device_put(object)
elif isscalar(object):
out = lax.reshape(object, ())
if dtype and _dtype(out) != dtypes.canonicalize_dtype(dtype):
out = lax.convert_element_type(out, dtype)
elif hasattr(object, '__array__'):
# this case is for duck-typed handling of objects that implement `__array__`
out = array(object.__array__(), dtype and dtypes.canonicalize_dtype(dtype))
elif isinstance(object, (list, tuple)):
if object:
out = stack([array(elt, dtype=dtype) for elt in object])
else:
out = onp.array([], dtype or float_)
else:
try:
view = memoryview(object)
except TypeError:
pass # `object` does not support the buffer interface.
else:
return array(onp.asarray(view), dtype, copy)
raise TypeError("Unexpected input type for array: {}".format(type(object)))
if ndmin > ndim(out):
out = lax.reshape(out, (1,) * (ndmin - ndim(out)) + shape(out))
return out
@_wraps(onp.asarray)
def asarray(a, dtype=None, order=None):
lax._check_user_dtype_supported(dtype, "asarray")
return array(a, dtype=dtype, copy=False, order=order)
@_wraps(onp.zeros_like)
def zeros_like(x, dtype=None):
lax._check_user_dtype_supported(dtype, "zeros_like")
return lax.full_like(x, 0, dtype)
@_wraps(onp.ones_like)
def ones_like(x, dtype=None):
lax._check_user_dtype_supported(dtype, "ones_like")
return lax.full_like(x, 1, dtype)
@_wraps(onp.full)
def full(shape, fill_value, dtype=None):
lax._check_user_dtype_supported(dtype, "full")
shape = (shape,) if ndim(shape) == 0 else shape
return lax.full(shape, fill_value, dtype)
@_wraps(onp.full_like)
def full_like(a, fill_value, dtype=None):
lax._check_user_dtype_supported(dtype, "full_like")
return lax.full_like(a, fill_value, dtype)
@_wraps(onp.zeros)
def zeros(shape, dtype=None):
if isinstance(shape, types.GeneratorType):
raise TypeError("expected sequence object with len >= 0 or a single integer")
lax._check_user_dtype_supported(dtype, "zeros")
dtype = float_ if dtype is None else dtype
shape = (shape,) if ndim(shape) == 0 else shape
return lax.full(shape, 0, dtype)
@_wraps(onp.ones)
def ones(shape, dtype=None):
if isinstance(shape, types.GeneratorType):
raise TypeError("expected sequence object with len >= 0 or a single integer")
lax._check_user_dtype_supported(dtype, "ones")
dtype = float_ if dtype is None else dtype
shape = (shape,) if ndim(shape) == 0 else shape
return lax.full(shape, 1, dtype)
@_wraps(onp.array_equal)
def array_equal(a1, a2):
try:
a1, a2 = asarray(a1), asarray(a2)
except Exception:
return False
return shape(a1) == shape(a2) and all(asarray(a1 == a2))
# We can't create uninitialized arrays in XLA; use zeros for empty.
empty_like = zeros_like
empty = zeros
@_wraps(onp.eye)
def eye(N, M=None, k=None, dtype=None):
lax._check_user_dtype_supported(dtype, "eye")
dtype = float_ if dtype is None else dtype
M = N if M is None else M
if N < 0 or M < 0:
msg = "negative dimensions are not allowed, got {} and {}"
raise ValueError(msg.format(N, M))
if k is None:
return lax.broadcasted_eye(dtype, (N, M), (0, 1))
else:
k_dtype = _dtype(k)
if not issubdtype(k_dtype, integer):
msg = "eye argument `k` must be of integer dtype, got {}"
raise TypeError(msg.format(k_dtype))
rows = k + lax.broadcasted_iota(k_dtype, (N, M), 0)
cols = lax.broadcasted_iota(k_dtype, (N, M), 1)
return lax.convert_element_type(lax.eq(rows, cols), dtype)
@_wraps(onp.identity)
def identity(n, dtype=None):
lax._check_user_dtype_supported(dtype, "identity")
return eye(n, dtype=dtype)
@_wraps(onp.arange)
def arange(start, stop=None, step=None, dtype=None):
lax._check_user_dtype_supported(dtype, "arange")
# If called like np.arange(N), we create a lazy lax._IotaConstant.
if stop is None and step is None:
dtype = dtype or _dtype(start)
if issubdtype(dtype, integer):
return lax.iota(dtype, start) # avoids materializing
# Fall back to instantiating an ndarray in host memory
dtype = dtype or result_type(
*(x for x in (start, stop, step) if x is not None))
return onp.arange(start, stop=stop, step=step, dtype=dtype)
def _wrap_numpy_nullary_function(f):
"""Adapts `f` to return a DeviceArray instead of an onp.ndarray.
`f` cannot have any non-static array arguments.
"""
@_wraps(f, update_doc=False)
def wrapper(*args, **kwargs):
return asarray(f(*args, **kwargs))
return wrapper
@_wraps(onp.linspace)
def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None,
axis=0):
"""Implementation of linspace differentiable in start and stop args."""
lax._check_user_dtype_supported(dtype, "linspace")
if num < 0:
raise ValueError("Number of samples, %s, must be non-negative." % num)
dt = result_type(start, stop, float(num))
dtype = dtype or dt
bounds_shape = list(lax.broadcast_shapes(shape(start), shape(stop)))
broadcast_start = broadcast_to(start, bounds_shape)
axis = len(bounds_shape) + axis + 1 if axis < 0 else axis
bounds_shape.insert(axis, 1)
iota_shape = [1,] * len(bounds_shape)
iota_shape[axis] = num
div = (num - 1) if endpoint else num
if num > 1:
delta = lax.convert_element_type(stop - start, dt) / div
out = (reshape(broadcast_start, bounds_shape) +
reshape(lax.iota(dt, num), iota_shape) *
reshape(delta, bounds_shape))
elif num == 1:
delta = nan
out = reshape(broadcast_start, bounds_shape)
else: # num == 0 degenerate case, match onp behavior
empty_shape = list(lax.broadcast_shapes(shape(start), shape(stop)))
empty_shape.insert(axis, 0)
delta = nan
out = reshape(array([], dtype=dt), empty_shape)
if retstep:
return lax.convert_element_type(out, dtype), delta
else:
return lax.convert_element_type(out, dtype)
@_wraps(onp.logspace)
def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0):
"""Implementation of logspace differentiable in start and stop args."""
dtype = dtype or result_type(start, stop, float_)
computation_dtype = promote_types(dtype, float_)
start = asarray(start, dtype=computation_dtype)
stop = asarray(stop, dtype=computation_dtype)
lin = linspace(start, stop, num,
endpoint=endpoint, retstep=False, dtype=None, axis=axis)
return lax.convert_element_type(power(base, lin), dtype)
@_wraps(onp.geomspace)
def geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0):
"""Implementation of geomspace differentiable in start and stop args."""
dtype = dtype or result_type(start, stop, float(num), zeros((), dtype))
computation_dtype = promote_types(dtype, float32)
start = asarray(start, dtype=computation_dtype)
stop = asarray(stop, dtype=computation_dtype)
# follow the numpy geomspace convention for negative and complex endpoints
signflip = 1 - (1 - sign(real(start))) * (1 - sign(real(stop))) // 2
res = signflip * logspace(log10(signflip * start),
log10(signflip * stop), num,
endpoint=endpoint, base=10.0,
dtype=computation_dtype, axis=0)
if axis != 0:
res = moveaxis(res, 0, axis)
return lax.convert_element_type(res, dtype)
@_wraps(onp.meshgrid)
def meshgrid(*args, **kwargs):
indexing = kwargs.get("indexing", "xy")
sparse = kwargs.get("sparse", False)
copy = kwargs.get("copy", True)
if not copy:
raise ValueError("jax.numpy.meshgrid only supports copy=True")
args = list(args)
if indexing == "xy":
if len(args) >= 2:
args[0], args[1] = args[1], args[0]
elif indexing != "ij":
raise ValueError("Valid values for indexing are 'xy' and 'ij', got {}"
.format(indexing))
shape = []
for i, a in enumerate(args):
args[i] = a = asarray(a)
if len(a.shape) != 1:
msg = "Arguments to jax.numpy.meshgrid must be 1D, got shape {}"
raise ValueError(msg.format(a.shape))
shape.append(1 if sparse else a.shape[0])
output = []
for i, a in enumerate(args):
a = asarray(a)
s = shape
if sparse:
s = list(s)
s[i] = a.shape[0]
output.append(lax.broadcast_in_dim(a, s, (i,)))
if indexing == "xy" and len(args) >= 2:
output[0], output[1] = output[1], output[0]
return output
@_wraps(onp.ix_)
def ix_(*args):
n = len(args)
output = []
for i, a in enumerate(args):
a = asarray(a)
if len(a.shape) != 1:
msg = "Arguments to jax.numpy.ix_ must be 1-dimensional, got shape {}"
raise ValueError(msg.format(a.shape))
if _dtype(a) == bool_:
raise NotImplementedError(
"Boolean arguments to jax.numpy.ix_ are not implemented")
shape = [1] * n
shape[i] = a.shape[0]
if a.size == 0:
# Numpy uses an integer index type for empty arrays.
output.append(lax.full(shape, onp.zeros((), onp.intp)))
else:
output.append(lax.reshape(a, shape))
return tuple(output)
def _repeat_scalar(a, repeats, axis=None):
if not isscalar(repeats):
raise NotImplementedError(
"_repeat_scalar implementation only supports scalar repeats")
if axis is None or isscalar(a):
a = ravel(a)
axis = 0
a_shape = list(shape(a))
num_dims = len(a_shape)
if axis < 0:
axis = axis + num_dims
if axis < 0 or axis >= num_dims:
raise ValueError(
"axis {} is out of bounds for array of dimension {}".format(
axis, num_dims))
# Broadcasts to [..., X, repeats, ...] and reshapes to [..., X * repeats, ...]
broadcast_shape = list(a_shape)
broadcast_shape.insert(axis + 1, repeats)
broadcast_dims = onp.concatenate((onp.arange(0, axis + 1),
onp.arange(axis + 2, num_dims + 1)))
a_shape[axis] *= repeats
return lax.reshape(
lax.broadcast_in_dim(a, broadcast_shape, broadcast_dims),
a_shape)
@_wraps(onp.repeat)
def repeat(a, repeats, axis=None):
'''
:param repeats: int or array of ints
'''
# use `_repeat_scalar` when possible
if isscalar(repeats):
return _repeat_scalar(a, repeats, axis)
repeats_raveled = ravel(array(repeats)) # make sure it's jax's array type
if size(repeats_raveled) == 1:
return _repeat_scalar(a, list(repeats_raveled)[0], axis)
if axis is None or isscalar(a):
a = ravel(a)
axis = 0
# repeats must match the dimension along the requested axis
a_shape = list(a.shape)
n = a_shape[axis]
if size(repeats_raveled) != n:
raise ValueError("repeats shape {} does not match the dimension on axis {}".format(
repeats_raveled.shape, n
))
# calculating the new shape
total = sum(repeats_raveled)
new_shape = a_shape[:]
new_shape[axis] = total
a_flattened = ravel(a)
'''
main algorithm:
first break down raveled input array into list of chunks; each chunk is the unit of repeat
then tile the repeats to have same length as the list of chunks
finally repeat each unit x number of times according to the tiled repeat list
'''
chunks = product(a_shape[:axis+1]).item()
a_splitted = split(a_flattened, chunks)
repeats_tiled = tile(repeats_raveled, chunks // len(repeats_raveled))
ret = array([], dtype=a.dtype)
for i, repeat in enumerate(repeats_tiled):
if not isinstance(repeat, int):
repeat = repeat.item()
if repeat != 0:
ret = concatenate((ret, tile(a_splitted[i], repeat)))
return reshape(ret, new_shape)
@_wraps(onp.tri)
def tri(N, M=None, k=0, dtype=None):
lax._check_user_dtype_supported(dtype, "tri")
M = M if M is not None else N
dtype = dtype or float32
x = arange(N, dtype=int32)
y = arange(M, dtype=int32)
mask = lax.ge(
(lax.broadcast_in_dim(x, shape=(N, M), broadcast_dimensions=(0,)) +
int32(k)),
lax.broadcast(y, [N]))
return lax.convert_element_type(mask, dtype)
@_wraps(onp.tril)
def tril(m, k=0):
m_shape = shape(m)
if len(m_shape) < 2:
raise ValueError("Argument to jax.numpy.tril must be at least 2D")
mask = tri(*m_shape[-2:], k=k, dtype=bool)
return lax.select(lax.broadcast(mask, m_shape[:-2]), m, zeros_like(m))
@_wraps(onp.triu, update_doc=False)
def triu(m, k=0):
m_shape = shape(m)
if len(m_shape) < 2:
raise ValueError("Argument to jax.numpy.triu must be at least 2D")
mask = tri(*m_shape[-2:], k=k - 1, dtype=bool)
return lax.select(lax.broadcast(mask, m_shape[:-2]), zeros_like(m), m)
@_wraps(onp.trace)
def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None):
if out:
raise NotImplementedError("The 'out' argument to trace is not supported.")
lax._check_user_dtype_supported(dtype, "trace")
axis1 = _canonicalize_axis(axis1, ndim(a))
axis2 = _canonicalize_axis(axis2, ndim(a))
a_shape = shape(a)
if dtype is None:
dtype = _dtype(a)
if issubdtype(dtype, integer):
default_int = dtypes.canonicalize_dtype(onp.int_)
if iinfo(dtype).bits < iinfo(default_int).bits:
dtype = default_int
# Move the axis? dimensions to the end.
perm = [i for i in range(len(a_shape)) if i != axis1 and i != axis2]
perm = perm + [axis1, axis2]
a = lax.transpose(a, perm)
# Mask out the diagonal and reduce.
a = where(eye(a_shape[axis1], a_shape[axis2], k=offset, dtype=bool),
a, zeros_like(a))
return sum(a, axis=(-2, -1), dtype=dtype)
def _wrap_indices_function(f):
@_wraps(f, update_doc=False)
def wrapper(*args, **kwargs):
return tuple(asarray(x) for x in f(*args, **kwargs))
return wrapper
tril_indices = _wrap_indices_function(onp.tril_indices)
triu_indices = _wrap_indices_function(onp.triu_indices)
mask_indices = _wrap_indices_function(onp.mask_indices)
@_wraps(onp.diag_indices)
def diag_indices(n, ndim=2):
if n < 0:
raise ValueError("n argument to diag_indices must be nonnegative, got {}"
.format(n))
if ndim < 0:
raise ValueError("ndim argument to diag_indices must be nonnegative, got {}"
.format(ndim))
return (lax.iota(int_, n),) * ndim
@_wraps(onp.diagonal)
def diagonal(a, offset=0, axis1=0, axis2=1):
a_shape = shape(a)
a_ndims = len(a_shape)
# Move the two dimensions to the end.
axis1 = _canonicalize_axis(axis1, a_ndims)
axis2 = _canonicalize_axis(axis2, a_ndims)
perm = [i for i in range(a_ndims) if i != axis1 and i != axis2]
perm = perm + [axis1, axis2]
a = lax.transpose(a, perm)
# Mask out the diagonal and reduce over one of the axes
a = where(eye(a_shape[axis1], a_shape[axis2], k=offset, dtype=bool),
a, zeros_like(a))
reduce_axis = -2 if offset < 0 else -1
d = sum(a, axis=reduce_axis, dtype=_dtype(a))
# Slice out the correct diagonal size.
diag_size = _max(0, _min(a_shape[axis1] + _min(offset, 0),
a_shape[axis2] - _max(offset, 0)))
return lax.slice_in_dim(d, 0, diag_size, axis=-1)
@_wraps(onp.diag)
def diag(v, k=0):
v_shape = shape(v)
if len(v_shape) == 1:
zero = lambda x: lax.full_like(x, shape=(), fill_value=0)
n = v_shape[0] + _abs(k)
v = lax.pad(v, zero(v), ((_max(0, k), _max(0, -k), 0),))
return where(eye(n, k=k, dtype=bool), v, zeros_like(v))
elif len(v_shape) == 2:
return diagonal(v, offset=k)
else:
raise ValueError("diag input must be 1d or 2d")
@_wraps(onp.polyval)
def polyval(p, x):
if isinstance(p, onp.poly1d):
p = onp.asarray(p)
if isinstance(x, onp.poly1d):
y = 0
else:
y = zeros_like(x)
for i in range(len(p)):
y = y * x + p[i]
return y
@_wraps(onp.append)
def append(arr, values, axis=None):
if axis is None:
return concatenate([ravel(arr), ravel(values)], 0)
else:
return concatenate([arr, values], axis=axis)
### Tensor contraction operations
_PRECISION_DOC = """\
In addition to the original NumPy arguments listed below, also supports
``precision`` for extra control over matrix-multiplication precision
on supported devices. See :py:func:`jax.lax.dot` for details.
"""
@_wraps(onp.dot, lax_description=_PRECISION_DOC)
def dot(a, b, precision=None): # pylint: disable=missing-docstring
_check_arraylike("dot", a, b)
a, b = _promote_dtypes(a, b)
a_ndim, b_ndim = ndim(a), ndim(b)
if a_ndim == 0 or b_ndim == 0:
return lax.mul(a, b)
if _max(a_ndim, b_ndim) <= 2:
return lax.dot(a, b, precision=precision)
if b_ndim == 1:
contract_dims = ((a_ndim - 1,), (0,))
else:
contract_dims = ((a_ndim - 1,), (b_ndim - 2,))
batch_dims = ((), ())
return lax.dot_general(a, b, (contract_dims, batch_dims), precision)
@_wraps(onp.matmul, lax_description=_PRECISION_DOC)
def matmul(a, b, precision=None): # pylint: disable=missing-docstring
_check_arraylike("matmul", a, b)
a_is_vec, b_is_vec = (ndim(a) == 1), (ndim(b) == 1)
a = lax.reshape(a, (1,) + shape(a)) if a_is_vec else a
b = lax.reshape(b, shape(b) + (1,)) if b_is_vec else b
a, b = _promote_dtypes(a, b)
batch_shape = lax.broadcast_shapes(shape(a)[:-2], shape(b)[:-2])
a = broadcast_to(a, batch_shape + shape(a)[-2:])
b = broadcast_to(b, batch_shape + shape(b)[-2:])
batch_dims = tuple(range(len(batch_shape)))
dim_numbers = (((ndim(a) - 1,), (ndim(b) - 2,)), (batch_dims, batch_dims))
result = lax.dot_general(a, b, dim_numbers, precision)
if a_is_vec or b_is_vec:
m, n = shape(result)[-2:]
new_m = () if a_is_vec else (m,)
new_n = () if b_is_vec else (n,)
return lax.reshape(result, batch_shape + new_m + new_n)
else:
return result
@_wraps(onp.vdot, lax_description=_PRECISION_DOC)
def vdot(a, b, precision=None):
if issubdtype(_dtype(a), complexfloating):
a = conj(a)
return dot(a.ravel(), b.ravel(), precision=precision)
@_wraps(onp.tensordot, lax_description=_PRECISION_DOC)
def tensordot(a, b, axes=2, precision=None):
_check_arraylike("tensordot", a, b)
a_ndim = ndim(a)
b_ndim = ndim(b)
if a_ndim < 1 or b_ndim < 1:
msg = "tensordot requires a.ndim and b.dim to be at least 1, got {} and {}."
raise TypeError(msg.format(ndim(a), ndim(b)))
a, b = _promote_dtypes(a, b)
if type(axes) is int:
if axes > _min(a_ndim, b_ndim):
msg = "Number of tensordot axes (axes {}) exceeds input ranks ({} and {})"
raise msg.format(axes, a.shape, b.shape)
contracting_dims = tuple(range(a_ndim - axes, a_ndim)), tuple(range(axes))
elif type(axes) in (list, tuple) and len(axes) == 2:
ax1, ax2 = axes
if type(ax1) == type(ax2) == int:
contracting_dims = ((_canonicalize_axis(ax1, a_ndim),),
(_canonicalize_axis(ax2, b_ndim),))
elif type(ax1) in (list, tuple) and type(ax2) in (list, tuple):
if len(ax1) != len(ax2):
msg = "tensordot requires axes lists to have equal length, got {} and {}."
raise TypeError(msg.format(ax1, ax2))
contracting_dims = (tuple(_canonicalize_axis(i, a_ndim) for i in ax1),
tuple(_canonicalize_axis(i, b_ndim) for i in ax2))
else:
msg = ("tensordot axes argument must be an int, a pair of ints, or a pair "
"of lists/tuples of ints.")
raise TypeError(msg)
return lax.dot_general(a, b, (contracting_dims, ((), ())),
precision=precision)
@_wraps(onp.einsum, lax_description=_PRECISION_DOC)
def einsum(*operands, **kwargs):
optimize = kwargs.pop('optimize', 'auto')
optimize = 'greedy' if optimize is True else optimize
precision = kwargs.pop('precision', None)
if kwargs:
msg = 'invalid keyword arguments for einsum: {}'
raise TypeError(msg.format(', '.join(kwargs)))
# using einsum_call=True here is an internal api for opt_einsum
operands, contractions = opt_einsum.contract_path(
*operands, einsum_call=True, use_blas=True, optimize=optimize)
contractions = tuple(data[:3] for data in contractions)
return _einsum(operands, contractions, precision)
@_wraps(onp.einsum_path)
def einsum_path(subscripts, *operands, **kwargs):
optimize = kwargs.pop('optimize', 'greedy')
# using einsum_call=True here is an internal api for opt_einsum
return opt_einsum.contract_path(subscripts, *operands, optimize=optimize)
@partial(jit, static_argnums=(1, 2))
def _einsum(operands, contractions, precision):
operands = list(_promote_dtypes(*operands))
def sum(x, axes):
return lax.reduce(x, onp.array(0, x.dtype),
lax.add if x.dtype != bool_ else lax.bitwise_or, axes)
def sum_uniques(operand, names, uniques):
if uniques:
axes = [names.index(name) for name in uniques]
operand = sum(operand, axes)
names = removechars(names, uniques)
return operand, names
def sum_repeats(operand, names, counts, keep_names):
for name, count in counts.items():
if count > 1:
axes = [i for i, n in enumerate(names) if n == name]
eye = lax.broadcasted_eye(operand.dtype, operand.shape, axes)
if name not in keep_names:
operand = sum(operand * eye, axes)
names = names.replace(name, '')
else:
operand = sum(operand * eye, axes[:-1])
names = names.replace(name, '', count - 1)
return operand, names
for operand_indices, contracted_names, einstr in contractions:
input_str, result_names = einstr.split('->')
input_names = input_str.split(',')
# switch on the number of operands to be processed in this loop iteration.
# every case here sets 'operand' and 'names'.
if len(operand_indices) == 1:
operand = operands.pop(operand_indices[0])
names, = input_names
counts = collections.Counter(names)
# sum out unique contracted indices with a single reduce-sum
uniques = [name for name in contracted_names if counts[name] == 1]
operand, names = sum_uniques(operand, names, uniques)
# for every repeated index, do a contraction against an identity matrix
operand, names = sum_repeats(operand, names, counts, result_names)
elif len(operand_indices) == 2:
lhs, rhs = map(operands.pop, operand_indices)
lhs_counts, rhs_counts = map(collections.Counter, input_names)
lhs_names, rhs_names = input_names
# sum out unique contracted indices in lhs and rhs
lhs_uniques = [name for name in contracted_names
if lhs_counts[name] == 1 and rhs_counts[name] == 0]
lhs, lhs_names = sum_uniques(lhs, lhs_names, lhs_uniques)
rhs_uniques = [name for name in contracted_names
if rhs_counts[name] == 1 and lhs_counts[name] == 0]
rhs, rhs_names = sum_uniques(rhs, rhs_names, rhs_uniques)
# for every repeated index, contract against an identity matrix
lhs, lhs_names = sum_repeats(lhs, lhs_names, lhs_counts,
result_names + rhs_names)
rhs, rhs_names = sum_repeats(rhs, rhs_names, rhs_counts,
result_names + lhs_names)
contracted_names = contracted_names & (set(lhs_names) | set(rhs_names))
batch_names = (set(lhs_names) & set(rhs_names)) - contracted_names
lhs_batch, rhs_batch = unzip2((lhs_names.find(n), rhs_names.find(n))
for n in batch_names)
# NOTE(mattjj): this can fail non-deterministically in python3, maybe
# due to opt_einsum
assert _all(name in lhs_names and name in rhs_names and
lhs.shape[lhs_names.index(name)] == rhs.shape[rhs_names.index(name)]
for name in contracted_names)
# move batch dims to the front (required by lax.dot_general, and easier)
batch_dims = tuple(range(len(batch_names)))
if lhs_batch != rhs_batch or set(lhs_batch) != set(batch_dims):
lhs = moveaxis(lhs, lhs_batch, batch_dims)
lhs_names = _movechars(lhs_names, lhs_batch, batch_dims)
rhs = moveaxis(rhs, rhs_batch, batch_dims)
rhs_names = _movechars(rhs_names, rhs_batch, batch_dims)
batch_names = ''.join(batch_names)
else:
batch_dims = tuple(lhs_batch)
batch_names = ''.join(lhs_names[i] for i in range(len(lhs_names))
if i in batch_dims)
# contract using lax.dot_general
lhs_cont, rhs_cont = unzip2((lhs_names.index(n), rhs_names.index(n))
for n in contracted_names)
bdims = tuple(range(len(batch_dims)))
dimension_numbers = [(lhs_cont, rhs_cont), (bdims, bdims)]
operand = lax.dot_general(lhs, rhs, dimension_numbers, precision)
deleted_names = batch_names + ''.join(contracted_names)
names = (batch_names + removechars(lhs_names, deleted_names)
+ removechars(rhs_names, deleted_names))
else:
raise NotImplementedError # if this is actually reachable, open an issue!
# the resulting 'operand' with axis labels 'names' should be a permutation
# of the desired result
assert len(names) == len(result_names) == len(set(names))
assert set(names) == set(result_names)
if names != result_names:
perm = tuple([names.index(name) for name in result_names])
operand = lax.transpose(operand, perm)
operands.append(operand) # used in next iteration
return operands[0]
def _movechars(s, src, dst):
"""Helper for einsum string munging, like moveaxis on identifier strings."""
chars = [c for i, c in enumerate(s) if i not in src]
for i, j in sorted(zip(dst, src)):
chars.insert(i, s[j])
return ''.join(chars)
@_wraps(onp.inner, lax_description=_PRECISION_DOC)
def inner(a, b, precision=None):
if ndim(a) == 0 or ndim(b) == 0:
return a * b
return tensordot(a, b, (-1, -1), precision=precision)
@_wraps(onp.outer)
def outer(a, b, out=None):
if out:
raise NotImplementedError("The 'out' argument to outer is not supported.")
a, b = _promote_dtypes(a, b)
return ravel(a)[:, None] * ravel(b)
@partial(jit, static_argnums=(2, 3, 4))
def _cross(a, b, axisa, axisb, axisc):
a = moveaxis(a, axisa, -1)
b = moveaxis(b, axisb, -1)
if a.shape[-1] not in (2, 3) or b.shape[-1] not in (2, 3):
raise ValueError("Dimension must be either 2 or 3 for cross product")
if a.shape[-1] == 2 and b.shape[-1] == 2:
return a[..., 0] * b[..., 1] - a[..., 1] * b[..., 0]
a0 = a[..., 0]
a1 = a[..., 1]
a2 = a[..., 2] if a.shape[-1] == 3 else zeros_like(a0)
b0 = b[..., 0]
b1 = b[..., 1]
b2 = b[..., 2] if b.shape[-1] == 3 else zeros_like(b0)
c = array([a1 * b2 - a2 * b1, a2 * b0 - a0 * b2, a0 * b1 - a1 * b0])
return moveaxis(c, 0, axisc)
@_wraps(onp.cross)
def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None):
if axis is not None:
axisa = axis
axisb = axis
axisc = axis
return _cross(a, b, axisa, axisb, axisc)
@_wraps(onp.kron)
def kron(a, b):
a, b = _promote_dtypes(a, b)
if ndim(a) < ndim(b):
a = reshape(a, (1,) * (ndim(b) - ndim(a)) + shape(a))
elif ndim(b) < ndim(a):
b = reshape(b, (1,) * (ndim(a) - ndim(b)) + shape(b))
a_reshaped = reshape(a, [i for d in shape(a) for i in (d, 1)])
b_reshaped = reshape(b, [i for d in shape(b) for i in (1, d)])
out_shape = tuple(onp.multiply(shape(a), shape(b)))
return reshape(lax.mul(a_reshaped, b_reshaped), out_shape)
@_wraps(onp.vander)
def vander(x, N=None, increasing=False):
x = asarray(x)
dtype = _dtype(x)
if ndim(x) != 1:
raise ValueError("x must be a one-dimensional array")
x_shape = shape(x)
N = N or x_shape[0]
if N < 0:
raise ValueError("N must be nonnegative")
iota = lax.iota(dtype, N)
if not increasing:
iota = lax.sub(lax._const(iota, N - 1), iota)
return power(x[..., None], iota)
### Misc
@_wraps(onp.argmax)
def argmax(a, axis=None):
if axis is None:
a = ravel(a)
axis = 0
return _argminmax(max, a, axis)
@_wraps(onp.argmin)
def argmin(a, axis=None):
if axis is None:
a = ravel(a)
axis = 0
return _argminmax(min, a, axis)
# TODO(mattjj): redo this lowering with a call to variadic lax.reduce
def _argminmax(op, a, axis):
shape = [1] * a.ndim
shape[axis] = a.shape[axis]
idxs = lax.tie_in(a, arange(a.shape[axis])).reshape(shape)
maxval = iinfo(dtypes.canonicalize_dtype(idxs.dtype)).max
maxval = lax.tie_in(a, maxval)
mask_idxs = where(lax._eq_meet(a, op(a, axis, keepdims=True)), idxs, maxval)
return min(mask_idxs, axis)
@_wraps(onp.sort)
def sort(a, axis=-1, kind='quicksort', order=None):
if kind != 'quicksort':
warnings.warn("'kind' argument to sort is ignored.")
if order is not None:
raise ValueError("'order' argument to sort is not supported.")
if axis is None:
return lax.sort(a.ravel(), 0)
else:
return lax.sort(a, _canonicalize_axis(axis, ndim(a)))
@_wraps(onp.argsort)
def argsort(a, axis=-1, kind='quicksort', order=None):
if kind != 'quicksort':
warnings.warn("'kind' argument to argsort is ignored.")
if order is not None:
raise ValueError("'order' argument to argsort is not supported.")
if axis is None:
return argsort(a.ravel(), 0)
else:
axis = _canonicalize_axis(axis, ndim(a))
iota = lax.broadcasted_iota(onp.int64, shape(a), axis)
_, perm = lax.sort_key_val(a, iota, dimension=axis)
return perm
@_wraps(onp.roll)
def roll(a, shift, axis=None):
a = asarray(a)
a_shape = shape(a)
if axis is None:
return lax.reshape(roll(ravel(a), shift, axis=0), a_shape)
a_ndim = len(a_shape)
shift = asarray(shift)
axis = onp.asarray(axis)
b_shape = lax.broadcast_shapes(shift.shape, axis.shape, (1,))
if len(b_shape) != 1:
msg = "'shift' and 'axis' arguments to roll must be scalars or 1D arrays"
raise ValueError(msg)
if b_shape[0] > a_ndim:
raise ValueError("More shifts/axes than dimensions of input to roll.")
for x, i in zip(broadcast_to(shift, b_shape),
onp.broadcast_to(axis, b_shape)):
i = _canonicalize_axis(i, a_ndim)
x = remainder(x, (a_shape[i] or 1))
a = lax.concatenate((a, a), i)
a = lax.dynamic_slice_in_dim(a, a_shape[i] - x, a_shape[i], axis=i)
return a
@_wraps(onp.take)
def take(a, indices, axis=None, out=None, mode=None):
if out:
raise NotImplementedError("The 'out' argument to np.take is not supported.")
a = asarray(a)
indices = asarray(indices)
if axis is None:
a = ravel(a)
axis = 0
axis = _canonicalize_axis(axis, ndim(a))
if mode == "raise":
# TODO(phawkins): we have no way to report out of bounds errors yet.
raise NotImplementedError("The 'raise' mode to np.take is not supported.")
elif mode == "wrap":
indices = mod(indices, _constant_like(indices, a.shape[axis]))
elif mode != "clip" and mode is not None:
raise ValueError("Invalid mode '{}' for np.take".format(mode))
index_dims = len(shape(indices))
slice_sizes = list(shape(a))
slice_sizes[axis] = 1
dnums = lax.GatherDimensionNumbers(
offset_dims=tuple(
list(range(axis)) +
list(range(axis + index_dims, len(a.shape) + index_dims - 1))),
collapsed_slice_dims=(axis,),
start_index_map=(axis,))
return lax.gather(a, indices[..., None], dimension_numbers=dnums,
slice_sizes=tuple(slice_sizes))
def _normalize_index(index, axis_size):
"""Normalizes an index value in the range [-N, N) to the range [0, N)."""
return lax.select(
lax.lt(index, _constant_like(index, 0)),
lax.add(index, _constant_like(index, axis_size)),
index)
@partial(jit, static_argnums=(2,))
def _take_along_axis(arr, indices, axis):
if axis is None:
if ndim(indices) != 1:
msg = "take_along_axis indices must be 1D if axis=None, got shape {}"
raise ValueError(msg.format(indices.shape))
return take_along_axis(arr.ravel(), indices, 0)
rank = ndim(arr)
if rank != ndim(indices):
msg = "indices and arr must have the same number of dimensions; {} vs. {}"
raise ValueError(msg.format(ndim(indices), ndim(arr)))
axis = _canonicalize_axis(axis, rank)
def replace(tup, val):
lst = list(tup)
lst[axis] = val
return tuple(lst)
bcast_shape = lax.broadcast_shapes(replace(arr.shape, 1), replace(indices.shape, 1))
indices = broadcast_to(indices, replace(bcast_shape, indices.shape[axis]))
arr = broadcast_to(arr, replace(bcast_shape, arr.shape[axis]))
axis_size = arr.shape[axis]
arr_shape = replace(arr.shape, 1)
idx_shape = indices.shape
out_shape = lax.broadcast_shapes(idx_shape, arr_shape)
index_dims = [i for i, idx in enumerate(idx_shape) if i == axis or idx != 1]
gather_index_shape = tuple(onp.array(out_shape)[index_dims]) + (1,)
gather_indices = []
slice_sizes = []
offset_dims = []
start_index_map = []
collapsed_slice_dims = []
j = 0
for i in range(rank):
if i == axis:
indices = _normalize_index(indices, axis_size)
gather_indices.append(lax.reshape(indices, gather_index_shape))
slice_sizes.append(1)
start_index_map.append(i)
collapsed_slice_dims.append(i)
j += 1
elif idx_shape[i] != 1:
iota = lax.iota(_dtype(indices), out_shape[i])
iota = lax.tie_in(arr, iota)
iota = lax.broadcast_in_dim(iota, gather_index_shape, (j,))
gather_indices.append(iota)
slice_sizes.append(1)
start_index_map.append(i)
collapsed_slice_dims.append(i)
j += 1
else:
# If idx_shape[i] == 1, we can just take the entirety of the arr's axis
# and avoid forming an iota index.
offset_dims.append(i)
slice_sizes.append(arr_shape[i])
gather_indices = lax.concatenate(gather_indices, dimension=j)
dnums = lax.GatherDimensionNumbers(
offset_dims=tuple(offset_dims),
collapsed_slice_dims=tuple(collapsed_slice_dims),
start_index_map=tuple(start_index_map))
return lax.gather(arr, gather_indices, dnums, tuple(slice_sizes))
@_wraps(getattr(onp, "take_along_axis", None), update_doc=False)
def take_along_axis(arr, indices, axis):
return _take_along_axis(arr, indices, axis)
### Indexing
def _rewriting_take(arr, idx):
# Computes arr[idx].
# All supported cases of indexing can be implemented as an XLA gather,
# followed by an optional reverse and a reshape.
arr = asarray(arr)
treedef, static_idx, dynamic_idx = _split_index_for_jit(idx)
return _gather(arr, treedef, static_idx, dynamic_idx)
# TODO(phawkins): re-enable jit after fixing excessive recompilation for
# slice indexes (e.g., slice(0, 5, None), slice(10, 15, None), etc.).
# @partial(jit, static_argnums=(1, 2))
def _gather(arr, treedef, static_idx, dynamic_idx):
idx = _merge_static_and_dynamic_indices(treedef, static_idx, dynamic_idx)
indexer = _index_to_gather(shape(arr), idx) # shared with _scatter_update
y = arr
# Avoid calling gather if the slice shape is empty, both as a fast path and to
# handle cases like zeros(0)[array([], int32)].
if _prod(indexer.slice_shape) == 0:
return zeros(indexer.slice_shape, dtype=y.dtype)
# We avoid generating a gather when indexer.gather_indices.size is empty.
if indexer.gather_indices.size:
y = lax.gather(y, indexer.gather_indices, indexer.dnums,
indexer.gather_slice_shape)
# Reverses axes with negative strides.
if indexer.reversed_y_dims:
y = lax.rev(y, indexer.reversed_y_dims)
# This adds np.newaxis/None dimensions.
return lax.reshape(y, indexer.slice_shape)
_Indexer = collections.namedtuple("_Indexer", [
# The expected shape of the slice output.
"slice_shape",
# The slice shape to pass to lax.gather().
"gather_slice_shape",
# The gather indices to use.
"gather_indices",
# A GatherDimensionNumbers object describing the gather to perform.
"dnums",
# Slice dimensions that have negative strides, and so must be reversed after
# the gather.
"reversed_y_dims",
# For scatters, we must eliminate any axes created by `newaxis`, which
# are the following dimensions, which must be of size 1. For gathers, we
# simply reshape to `slice_shape` to introduce the new axes.
"newaxis_dims",
])
def _split_index_for_jit(idx):
"""Splits indices into necessarily-static and dynamic parts.
Used to pass indices into `jit`-ted function.
"""
# Convert list indices to tuples in cases (deprecated by NumPy.)
idx = _eliminate_deprecated_list_indexing(idx)
# Expand any (concrete) boolean indices. We can then use advanced integer
# indexing logic to handle them.
idx = _expand_bool_indices(idx)
leaves, treedef = pytree.flatten(idx)
dynamic = [None] * len(leaves)
static = [None] * len(leaves)
for i, x in enumerate(leaves):
if x is Ellipsis:
static[i] = x
elif isinstance(x, slice):
# slice objects aren't hashable.
static[i] = (x.start, x.stop, x.step)
else:
dynamic[i] = x
return treedef, tuple(static), dynamic
def _merge_static_and_dynamic_indices(treedef, static_idx, dynamic_idx):
"""Recombines indices that were split by _split_index_for_jit."""
idx = []
for s, d in zip(static_idx, dynamic_idx):
if d is not None:
idx.append(d)
elif isinstance(s, tuple):
idx.append(slice(s[0], s[1], s[2]))
else:
idx.append(s)
return treedef.unflatten(idx)
def _int(aval):
return not aval.shape and issubdtype(aval.dtype, integer)
def _index_to_gather(x_shape, idx):
# Remove ellipses and add trailing slice(None)s.
idx = _canonicalize_tuple_index(len(x_shape), idx)
# Check for advanced indexing:
# https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing
# Do the advanced indexing axes appear contiguously? If not, NumPy semantics
# move the advanced axes to the front.
advanced_axes_are_contiguous = False
advanced_indexes = None
# The positions of the advanced indexing axes in `idx`.
idx_advanced_axes = []
# The positions of the advanced indexes in x's shape.
# collapsed, after None axes have been removed. See below.
x_advanced_axes = None
if _is_advanced_int_indexer(idx):
idx_no_nones = [(i, d) for i, d in enumerate(idx) if d is not None]
advanced_pairs = (
(asarray(e), i, j) for j, (i, e) in enumerate(idx_no_nones)
if (isinstance(e, Sequence) or isinstance(e, ndarray)))
advanced_pairs = ((_normalize_index(e, x_shape[j]), i, j)
for e, i, j in advanced_pairs)
advanced_indexes, idx_advanced_axes, x_advanced_axes = zip(*advanced_pairs)
advanced_axes_are_contiguous = onp.all(onp.diff(idx_advanced_axes) == 1)
x_axis = 0 # Current axis in x.
y_axis = 0 # Current axis in y, before collapsing. See below.
collapsed_y_axis = 0 # Current axis in y, after collapsing.
# Scatter dimension numbers.
offset_dims = []
collapsed_slice_dims = []
start_index_map = []
gather_indices = zeros((0,), dtype=int32)
# We perform three transformations to y before the scatter op, in order:
# First, y is broadcast to slice_shape. In general `y` only need broadcast to
# the right shape.
slice_shape = []
# Next, y is squeezed to remove newaxis_dims. This removes np.newaxis/`None`
# indices, which the scatter cannot remove itself.
newaxis_dims = []
# Finally, we reverse reversed_y_dims to handle slices with negative strides.
reversed_y_dims = []
gather_slice_shape = []
for idx_pos, i in enumerate(idx):
# Handle the advanced indices here if:
# * the advanced indices were not contiguous and we are the start.
# * we are at the position of the first advanced index.
if (advanced_indexes is not None and
(advanced_axes_are_contiguous and idx_pos == idx_advanced_axes[0] or
not advanced_axes_are_contiguous and idx_pos == 0)):
advanced_indexes = broadcast_arrays(*advanced_indexes)
shape = advanced_indexes[0].shape
ndim = len(shape)
advanced_indexes = [
lax.convert_element_type(lax.reshape(a, shape + (1,)), int32)
for a in advanced_indexes]
# Broadcast gather_indices from [..., k] to [..., 1, 1, ..., 1, k].
gather_indices = lax.broadcast_in_dim(
gather_indices, onp.insert(gather_indices.shape, -1, shape),
tuple(range(gather_indices.ndim - 1)) + (gather_indices.ndim + ndim - 1,))
gather_indices = concatenate([gather_indices] + advanced_indexes, -1)
start_index_map.extend(x_advanced_axes)
collapsed_slice_dims.extend(x_advanced_axes)
slice_shape.extend(shape)
y_axis += ndim
collapsed_y_axis += ndim
# Per-index bookkeeping for advanced indexes.
if idx_pos in idx_advanced_axes:
x_axis += 1
gather_slice_shape.append(1)
continue
try:
abstract_i = core.get_aval(i)
except TypeError:
abstract_i = None
# Handle basic int indexes.
if (isinstance(abstract_i, ConcreteArray) or
isinstance(abstract_i, ShapedArray)) and _int(abstract_i):
i = _normalize_index(i, x_shape[x_axis])
i = lax.convert_element_type(i, int32)
i = broadcast_to(i, tuple(gather_indices.shape[:-1]) + (1,))
gather_indices = concatenate((gather_indices, i), -1)
collapsed_slice_dims.append(x_axis)
gather_slice_shape.append(1)
start_index_map.append(x_axis)
x_axis += 1
# Handle np.newaxis (None)
elif i is None:
slice_shape.append(1)
newaxis_dims.append(y_axis)
y_axis += 1
# Handle slice(None)
elif _is_slice_none(i):
slice_shape.append(x_shape[x_axis])
gather_slice_shape.append(x_shape[x_axis])
offset_dims.append(collapsed_y_axis)
collapsed_y_axis += 1
y_axis += 1
x_axis += 1
# Handle slice index (only static, otherwise an error is raised)
elif isinstance(i, slice):
if not _all(elt is None or type(core.get_aval(elt)) is ConcreteArray
for elt in (i.start, i.stop, i.step)):
msg = ("Array slice indices must have static start/stop/step to be used "
"with Numpy indexing syntax. Try lax.dynamic_slice/"
"dynamic_update_slice instead.")
raise IndexError(msg)
start, limit, stride, needs_rev = _static_idx(i, x_shape[x_axis])
if needs_rev:
reversed_y_dims.append(collapsed_y_axis)
if stride == 1:
i = lax.convert_element_type(start, int32)
i = broadcast_to(i, tuple(gather_indices.shape[:-1]) + (1,))
gather_indices = concatenate((gather_indices, i), -1)
slice_shape.append(limit - start)
gather_slice_shape.append(limit - start)
offset_dims.append(collapsed_y_axis)
start_index_map.append(x_axis)
else:
i = arange(start, limit, stride, dtype=int32)
size = i.shape[0]
slice_shape.append(size)
gather_slice_shape.append(1)
gather_indices_shape = tuple(gather_indices.shape[:-1]) + (size,)
i = lax.broadcast_in_dim(
i, shape=gather_indices_shape + (1,),
broadcast_dimensions=(len(gather_indices_shape) - 1,))
gather_indices = lax.broadcast_in_dim(
gather_indices,
shape=gather_indices_shape + (len(start_index_map),),
broadcast_dimensions=(
tuple(range(len(gather_indices_shape) - 1)) +
(len(gather_indices_shape),)))
gather_indices = concatenate(
(gather_indices, i), len(gather_indices_shape))
start_index_map.append(x_axis)
collapsed_slice_dims.append(x_axis)
collapsed_y_axis += 1
y_axis += 1
x_axis += 1
else:
if abstract_i and not (issubdtype(abstract_i.dtype, integer) or
issubdtype(abstract_i.dtype, bool_)):
msg = ("Indexer must have integer or boolean type, got indexer "
"with type {} at position {}, indexer value {}")
raise TypeError(msg.format(abstract_i.dtype.name, idx_pos, i))
msg = "Indexing mode not yet supported. Open a feature request!\n{}"
raise IndexError(msg.format(idx))
dnums = lax.GatherDimensionNumbers(
offset_dims = tuple(offset_dims),
collapsed_slice_dims = tuple(sorted(collapsed_slice_dims)),
start_index_map = tuple(start_index_map)
)
return _Indexer(
slice_shape=slice_shape,
newaxis_dims=tuple(newaxis_dims),
gather_slice_shape=gather_slice_shape,
reversed_y_dims=reversed_y_dims,
dnums=dnums,
gather_indices=gather_indices)
def _should_unpack_list_index(x):
"""Helper for _eliminate_deprecated_list_indexing."""
return (isinstance(x, ndarray) and onp.ndim(x) != 0
or isinstance(x, Sequence)
or isinstance(x, slice) or x is Ellipsis or x is None)
def _eliminate_deprecated_list_indexing(idx):
# "Basic slicing is initiated if the selection object is a non-array,
# non-tuple sequence containing slice objects, [Ellipses, or newaxis
# objects]". Detects this case and canonicalizes to a tuple. This case is
# deprecated by NumPy and exists for backward compatibility.
if not isinstance(idx, tuple):
if isinstance(idx, Sequence) and not isinstance(idx, ndarray):
if _any(_should_unpack_list_index(i) for i in idx):
idx = tuple(idx)
else:
idx = (idx,)
else:
idx = (idx,)
return idx
def _expand_bool_indices(idx):
"""Converts concrete bool indexes into advanced integer indexes."""
out = []
for i in idx:
try:
abstract_i = core.get_aval(i)
except TypeError:
abstract_i = None
if (isinstance(abstract_i, ShapedArray) and issubdtype(abstract_i.dtype, bool_)
or isinstance(i, list) and _all(not _shape(e) and issubdtype(_dtype(e), bool_)
for e in i)):
if isinstance(i, list):
i = array(i)
abstract_i = core.get_aval(i)
if not type(abstract_i) is ConcreteArray:
msg = ("Array boolean indices must be static (e.g. no dependence on an "
"argument to a jit or vmap function).")
raise IndexError(msg)
else:
out.extend(onp.where(i))
else:
out.append(i)
return tuple(out)
def _is_slice_none(idx):
"""Return True if idx is equal to slice(None), False otherwise."""
if isinstance(idx, slice):
return idx.start is None and idx.stop is None and idx.step is None
# TODO(mattjj): clean up this logic
def _is_advanced_int_indexer(idx):
"""Returns True if idx should trigger int array indexing, False otherwise."""
# https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing
assert isinstance(idx, tuple)
if _all(onp.ndim(elt) == 0 for elt in idx):
return False
return _all(e is None or e is Ellipsis or isinstance(e, slice)
or _is_int_arraylike(e) for e in idx)
def _is_int_arraylike(x):
"""Returns True if x is array-like with integer dtype, False otherwise."""
return (isinstance(x, int) and not isinstance(x, bool)
or issubdtype(getattr(x, "dtype", None), onp.integer)
or isinstance(x, (list, tuple)) and _all(_is_int_arraylike(e) for e in x))
def _canonicalize_tuple_index(arr_ndim, idx):
"""Helper to remove Ellipsis and add in the implicit trailing slice(None)."""
len_without_none = _sum(1 for e in idx if e is not None and e is not Ellipsis)
if len_without_none > arr_ndim:
msg = "Too many indices for array: {} non-None/Ellipsis indices for dim {}."
raise IndexError(msg.format(len_without_none, arr_ndim))
ellipses = (i for i, elt in enumerate(idx) if elt is Ellipsis)
ellipsis_index = next(ellipses, None)
if ellipsis_index is not None:
if next(ellipses, None) is not None:
msg = "Multiple ellipses (...) not supported: {}."
raise IndexError(msg.format(list(map(type, idx))))
colons = (slice(None),) * (arr_ndim - len_without_none)
idx = idx[:ellipsis_index] + colons + idx[ellipsis_index + 1:]
elif len_without_none < arr_ndim:
colons = (slice(None),) * (arr_ndim - len_without_none)
idx = tuple(idx) + colons
return idx
def _static_idx(idx, size):
"""Helper function to compute the static slice start/limit/stride values."""
assert isinstance(idx, slice)
start, stop, step = idx.indices(size)
if (step < 0 and stop >= start) or (step > 0 and start >= stop):
return 0, 0, 1, False # sliced to size zero
if step > 0:
return start, stop, step, False
else:
k = (start - stop - 1) % (-step)
return stop + k + 1, start + 1, -step, True
blackman = _wrap_numpy_nullary_function(onp.blackman)
bartlett = _wrap_numpy_nullary_function(onp.bartlett)
hamming = _wrap_numpy_nullary_function(onp.hamming)
hanning = _wrap_numpy_nullary_function(onp.hanning)
# TODO: lower `kaiser` via lax to allow non-constant beta values.
kaiser = _wrap_numpy_nullary_function(onp.kaiser)
def _gcd_cond_fn(xs):
x1, x2 = xs
return any(x2 != 0)
def _gcd_body_fn(xs):
x1, x2 = xs
x1, x2 = (where(x2 != 0, x2, x1),
where(x2 != 0, lax.rem(x1, x2), lax._const(x2, 0)))
return (where(x1 < x2, x2, x1), where(x1 < x2, x1, x2))
@_wraps(getattr(onp, "gcd", None))
def gcd(x1, x2):
if (not issubdtype(_dtype(x1), integer) or
not issubdtype(_dtype(x2), integer)):
raise ValueError("Arguments to gcd must be integers.")
x1, x2 = _promote_dtypes(lax.abs(x1), lax.abs(x2))
x1, x2 = broadcast_arrays(x1, x2)
gcd, _ = lax.while_loop(_gcd_cond_fn, _gcd_body_fn, (x1, x2))
return gcd
@_wraps(getattr(onp, "lcm", None))
def lcm(x1, x2):
x1, x2 = _promote_dtypes(x1, x2)
d = gcd(x1, x2)
return where(d == 0, lax._const(d, 0),
lax.div(lax.abs(multiply(x1, x2)), d))
@_wraps(onp.cov)
def cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None,
aweights=None):
msg = ("jax.numpy.cov not implemented for nontrivial {}. "
"Open a feature request at https://github.com/google/jax/issues !")
if y is not None: raise NotImplementedError(msg.format('y'))
# These next two are actually implemented, just not tested.
if fweights is not None: raise NotImplementedError(msg.format('fweights'))
if aweights is not None: raise NotImplementedError(msg.format('aweights'))
if m.ndim > 2:
raise ValueError("m has more than 2 dimensions") # same as numpy error
X = array(m, ndmin=2, dtype=dtypes.canonicalize_dtype(result_type(m, float_)))
if not rowvar and X.shape[0] != 1:
X = X.T
if X.shape[0] == 0:
return onp.array([]).reshape(0, 0)
if ddof is None:
ddof = 1 if bias == 0 else 0
w = None
if fweights is not None:
if onp.ndim(fweights) > 1:
raise RuntimeError("cannot handle multidimensional fweights")
if onp.shape(fweights)[0] != X.shape[1]:
raise RuntimeError("incompatible numbers of samples and fweights")
w = asarray(fweights)
if aweights is not None:
if onp.ndim(aweights) > 1:
raise RuntimeError("cannot handle multidimensional aweights")
if onp.shape(aweights)[0] != X.shape[1]:
raise RuntimeError("incompatible numbers of samples and aweights")
w = aweights if w is None else w * aweights
avg, w_sum = average(X, axis=1, weights=w, returned=True)
w_sum = w_sum[0]
if w is None:
f = X.shape[1] - ddof
elif ddof == 0:
f = w_sum
elif aweights is None:
f = w_sum - ddof
else:
f = w_sum - ddof * sum(w * aweights) / w_sum
X = X - avg[:, None]
X_T = X.T if w is None else (X * w).T
return true_divide(dot(X, X_T.conj()), f).squeeze()
@_wraps(onp.corrcoef)
def corrcoef(x, y=None, rowvar=True, bias=None, ddof=None):
c = cov(x, y, rowvar)
if len(shape(c)) == 0:
# scalar - this should yield nan for values (nan/nan, inf/inf, 0/0), 1 otherwise
return divide(c, c)
d = diag(c)
stddev = sqrt(real(d))
c = divide(c, stddev[:,None])
c = divide(c, stddev[None,:])
real_part = clip(real(c), -1, 1)
if iscomplexobj(c):
complex_part = clip(imag(c), -1, 1)
c = lax.complex(real_part, complex_part)
else:
c = real_part
return c
@_wraps(getattr(onp, "quantile", None))
def quantile(a, q, axis=None, out=None, overwrite_input=False,
interpolation="linear", keepdims=False):
if overwrite_input or out is not None:
msg = ("jax.numpy.quantile does not support overwrite_input=True or "
"out != None")
raise ValueError(msg)
if interpolation != "linear":
raise NotImplementedError("Only interpolation='linear' is implemented")
return _quantile(a, q, axis, keepdims)
@partial(jit, static_argnums=(2, 3))
def _quantile(a, q, axis, keepdims):
a = asarray(a)
if axis is None:
a = ravel(a)
axis = 0
elif isinstance(axis, tuple):
raise NotImplementedError("Tuple values for axis are not implemented")
else:
axis = _canonicalize_axis(axis, ndim(a))
q_ndim = ndim(q)
if q_ndim > 1:
raise ValueError("q must be have rank <= 1, got shape {}".format(shape(q)))
q = asarray(q)
if not issubdtype(a.dtype, floating) or not issubdtype(q.dtype, floating):
msg = "q and a arguments to quantile must be of float type, got {} and {}"
raise TypeError(msg.format(a.dtype, q.dtype))
# Promote q to at least float32 for precise interpolation.
q = lax.convert_element_type(q, promote_types(q.dtype, float32))
a_shape = shape(a)
a = lax.sort(a, dimension=axis)
n = a_shape[axis]
q = lax.mul(q, _constant_like(q, n - 1))
low = lax.floor(q)
high = lax.add(low, _constant_like(low, 1))
high_weight = lax.sub(q, low)
low_weight = lax.sub(_constant_like(high_weight, 1), high_weight)
low = lax.clamp(_constant_like(low, 0), low, _constant_like(low, n - 1))
high = lax.clamp(_constant_like(high, 0), high, _constant_like(high, n - 1))
low = lax.convert_element_type(low, int64)
high = lax.convert_element_type(high, int64)
slice_sizes = list(a_shape)
slice_sizes[axis] = 1
dnums = lax.GatherDimensionNumbers(
offset_dims=tuple(range(
q_ndim,
len(a_shape) + q_ndim if keepdims else len(a_shape) + q_ndim - 1)),
collapsed_slice_dims=() if keepdims else (axis,),
start_index_map=(axis,))
low = low[..., None]
high = high[..., None]
low_value = lax.gather(a, low, dimension_numbers=dnums,
slice_sizes=slice_sizes)
high_value = lax.gather(a, high, dimension_numbers=dnums,
slice_sizes=slice_sizes)
if q_ndim == 1:
low_weight = lax.broadcast_in_dim(low_weight, low_value.shape,
broadcast_dimensions=(0,))
high_weight = lax.broadcast_in_dim(high_weight, high_value.shape,
broadcast_dimensions=(0,))
return lax.convert_element_type(
lax.add(lax.mul(low_value.astype(q.dtype), low_weight),
lax.mul(high_value.astype(q.dtype), high_weight)), a.dtype)
@_wraps(onp.percentile)
def percentile(a, q, axis=None, out=None, overwrite_input=False,
interpolation="linear", keepdims=False):
q = true_divide(asarray(q), float32(100.0))
return quantile(a, q, axis=axis, out=out, overwrite_input=overwrite_input,
interpolation=interpolation, keepdims=keepdims)
@_wraps(onp.median)
def median(a, axis=None, out=None, overwrite_input=False, keepdims=False):
q = 0.5
return quantile(a, q, axis=axis, out=out, overwrite_input=overwrite_input,
keepdims=keepdims)
def _astype(arr, dtype):
lax._check_user_dtype_supported(dtype, "astype")
return lax.convert_element_type(arr, dtype)
### track unimplemented functions
def _not_implemented(fun):
@_wraps(fun)
def wrapped(*args, **kwargs):
msg = "Numpy function {} not yet implemented"
raise NotImplementedError(msg.format(fun))
return wrapped
# Build a set of all unimplemented NumPy functions.
for func in get_module_functions(onp):
if func.__name__ not in globals():
globals()[func.__name__] = _not_implemented(func)
### add method and operator overloads to arraylike classes
# We add operator overloads to DeviceArray and ShapedArray. These method and
# operator overloads mainly just forward calls to the corresponding lax_numpy
# functions, which can themselves handle instances from any of these classes.
def _swap_args(f):
return lambda x, y: f(y, x)
def _unimplemented_setitem(self, i, x):
msg = ("'{}' object does not support item assignment. JAX arrays are "
"immutable; perhaps you want jax.ops.index_update or "
"jax.ops.index_add instead?")
raise TypeError(msg.format(type(self)))
def _operator_round(number, ndigits=None):
out = round(number, decimals=ndigits or 0)
# If `ndigits` is None, for a builtin float round(7.5) returns an integer.
return out.astype(int_) if ndigits is None else out
_operators = {
"getitem": _rewriting_take,
"setitem": _unimplemented_setitem,
"neg": negative,
"pos": positive,
"eq": equal,
"ne": not_equal,
"lt": less,
"le": less_equal,
"gt": greater,
"ge": greater_equal,
"abs": abs,
"add": add,
"radd": add,
"sub": subtract,
"rsub": _swap_args(subtract),
"mul": multiply,
"rmul": multiply,
"div": divide,
"rdiv": _swap_args(divide),
"truediv": true_divide,
"rtruediv": _swap_args(true_divide),
"floordiv": floor_divide,
"rfloordiv": _swap_args(floor_divide),
"divmod": divmod,
"rdivmod": _swap_args(divmod),
"mod": mod,
"rmod": _swap_args(mod),
"pow": power,
"rpow": _swap_args(power),
"matmul": matmul,
"rmatmul": _swap_args(matmul),
"and": bitwise_and,
"rand": bitwise_and,
"or": bitwise_or,
"ror": bitwise_or,
"xor": bitwise_xor,
"rxor": bitwise_xor,
"invert": bitwise_not,
"lshift": left_shift,
"rshift": right_shift,
"round": _operator_round,
}
# These numpy.ndarray methods are just refs to an equivalent numpy function
_nondiff_methods = ["all", "any", "argmax", "argmin", "argpartition", "argsort",
"nonzero", "searchsorted", "round"]
_diff_methods = ["clip", "compress", "conj", "conjugate", "cumprod", "cumsum",
"diagonal", "dot", "max", "mean", "min", "prod", "ptp",
"ravel", "repeat", "sort", "squeeze", "std", "sum",
"swapaxes", "take", "tile", "trace", "transpose", "var"]
# Set up operator, method, and property forwarding on Tracer instances containing
# ShapedArray avals by following the forwarding conventions for Tracer.
# Forward operators using a single-underscore-prefix naming convention:
for operator_name, function in _operators.items():
setattr(ShapedArray, "_{}".format(operator_name), staticmethod(function))
# Forward methods and properties using core.aval_method and core.aval_property:
for method_name in _nondiff_methods + _diff_methods:
setattr(ShapedArray, method_name, core.aval_method(globals()[method_name]))
setattr(ShapedArray, "reshape", core.aval_method(_reshape_method))
setattr(ShapedArray, "flatten", core.aval_method(ravel))
setattr(ShapedArray, "T", core.aval_property(transpose))
setattr(ShapedArray, "real", core.aval_property(real))
setattr(ShapedArray, "imag", core.aval_property(imag))
setattr(ShapedArray, "astype", core.aval_method(_astype))
# Forward operators, methods, and properties on DeviceArray to lax_numpy
# functions (with no Tracers involved; this forwarding is direct)
for operator_name, function in _operators.items():
setattr(DeviceArray, "__{}__".format(operator_name), function)
for method_name in _nondiff_methods + _diff_methods:
setattr(DeviceArray, method_name, globals()[method_name])
setattr(DeviceArray, "reshape", _reshape_method)
setattr(DeviceArray, "flatten", ravel)
setattr(DeviceArray, "T", property(transpose))
setattr(DeviceArray, "real", property(real))
setattr(DeviceArray, "imag", property(imag))
setattr(DeviceArray, "astype", _astype)
# Extra methods that are handy
setattr(ShapedArray, "broadcast", core.aval_method(lax.broadcast))
setattr(ShapedArray, "broadcast_in_dim", core.aval_method(lax.broadcast_in_dim))
setattr(ShapedArray, "split", core.aval_method(split))
setattr(DeviceArray, "broadcast", lax.broadcast)
setattr(DeviceArray, "broadcast_in_dim", lax.broadcast_in_dim)
setattr(DeviceArray, "split", split)
@jit
def _unstack(x):
if x.ndim == 0:
raise ValueError("Argument to _unstack must be non-scalar")
return [lax.index_in_dim(x, i, keepdims=False) for i in range(x.shape[0])]
setattr(DeviceArray, "_unstack", _unstack)
|
jax-master
|
jax/numpy/lax_numpy.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from .lax_numpy import *
from . import fft
from . import linalg
|
jax-master
|
jax/numpy/__init__.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from functools import partial
import numpy as onp
import warnings
import textwrap
from jax import jit
from .. import lax
from .. import lax_linalg
from .. import dtypes
from .lax_numpy import _not_implemented
from .lax_numpy import _wraps
from . import lax_numpy as np
from ..api import custom_transforms, defjvp
from ..util import get_module_functions
_T = lambda x: np.swapaxes(x, -1, -2)
def _promote_arg_dtypes(*args):
"""Promotes `args` to a common inexact type."""
def _to_inexact_type(type):
return type if np.issubdtype(type, np.inexact) else np.float_
inexact_types = [_to_inexact_type(np._dtype(arg)) for arg in args]
dtype = dtypes.canonicalize_dtype(np.result_type(*inexact_types))
args = [lax.convert_element_type(arg, dtype) for arg in args]
if len(args) == 1:
return args[0]
else:
return args
@_wraps(onp.linalg.cholesky)
def cholesky(a):
a = _promote_arg_dtypes(np.asarray(a))
return lax_linalg.cholesky(a)
@_wraps(onp.linalg.svd)
def svd(a, full_matrices=True, compute_uv=True):
a = _promote_arg_dtypes(np.asarray(a))
return lax_linalg.svd(a, full_matrices, compute_uv)
# TODO(pfau): make this work for complex types
def _jvp_slogdet(g, ans, x):
jvp_sign = np.zeros(x.shape[:-2])
jvp_logdet = np.trace(solve(x, g), axis1=-1, axis2=-2)
return jvp_sign, jvp_logdet
@_wraps(onp.linalg.slogdet)
@custom_transforms
@jit
def slogdet(a):
a = _promote_arg_dtypes(np.asarray(a))
dtype = lax.dtype(a)
a_shape = np.shape(a)
if len(a_shape) < 2 or a_shape[-1] != a_shape[-2]:
msg = "Argument to slogdet() must have shape [..., n, n], got {}"
raise ValueError(msg.format(a_shape))
lu, pivot = lax_linalg.lu(a)
diag = np.diagonal(lu, axis1=-2, axis2=-1)
is_zero = np.any(diag == np.array(0, dtype=dtype), axis=-1)
parity = np.count_nonzero(pivot != np.arange(a_shape[-1]), axis=-1)
if np.iscomplexobj(a):
sign = np.prod(diag / np.abs(diag), axis=-1)
else:
sign = np.array(1, dtype=dtype)
parity = parity + np.count_nonzero(diag < 0, axis=-1)
sign = np.where(is_zero,
np.array(0, dtype=dtype),
sign * np.array(-2 * (parity % 2) + 1, dtype=dtype))
logdet = np.where(
is_zero, np.array(-np.inf, dtype=dtype),
np.sum(np.log(np.abs(diag)), axis=-1))
return sign, np.real(logdet)
defjvp(slogdet, _jvp_slogdet)
@_wraps(onp.linalg.det)
def det(a):
sign, logdet = slogdet(a)
return sign * np.exp(logdet)
@_wraps(onp.linalg.eig)
def eig(a):
a = _promote_arg_dtypes(np.asarray(a))
w, vl, vr = lax_linalg.eig(a)
return w, vr
@_wraps(onp.linalg.eigvals)
def eigvals(a):
w, _ = eig(a)
return w
@_wraps(onp.linalg.eigh)
def eigh(a, UPLO=None, symmetrize_input=True):
if UPLO is None or UPLO == "L":
lower = True
elif UPLO == "U":
lower = False
else:
msg = "UPLO must be one of None, 'L', or 'U', got {}".format(UPLO)
raise ValueError(msg)
a = _promote_arg_dtypes(np.asarray(a))
v, w = lax_linalg.eigh(a, lower=lower, symmetrize_input=symmetrize_input)
return w, v
@_wraps(onp.linalg.eigvalsh)
def eigvalsh(a, UPLO='L'):
w, _ = eigh(a, UPLO)
return w
@_wraps(onp.linalg.pinv, lax_description=textwrap.dedent("""\
It differs only in default value of `rcond`. In `numpy.linalg.pinv`, the
default `rcond` is `1e-15`. Here the default is
`10. * max(num_rows, num_cols) * np.finfo(dtype).eps`.
"""))
def pinv(a, rcond=None):
# ported from https://github.com/numpy/numpy/blob/v1.17.0/numpy/linalg/linalg.py#L1890-L1979
a = np.conj(a)
# copied from https://github.com/tensorflow/probability/blob/master/tensorflow_probability/python/math/linalg.py#L442
if rcond is None:
max_rows_cols = max(a.shape[-2:])
rcond = 10. * max_rows_cols * np.finfo(a.dtype).eps
rcond = np.asarray(rcond)
u, s, v = svd(a, full_matrices=False)
# Singular values less than or equal to ``rcond * largest_singular_value``
# are set to zero.
cutoff = rcond[..., np.newaxis] * np.amax(s, axis=-1, keepdims=True)
large = s > cutoff
s = np.divide(1, s)
s = np.where(large, s, 0)
vT = np.swapaxes(v, -1, -2)
uT = np.swapaxes(u, -1, -2)
res = np.matmul(vT, np.multiply(s[..., np.newaxis], uT))
return lax.convert_element_type(res, a.dtype)
@_wraps(onp.linalg.inv)
def inv(a):
if np.ndim(a) < 2 or a.shape[-1] != a.shape[-2]:
raise ValueError("Argument to inv must have shape [..., n, n], got {}."
.format(np.shape(a)))
return solve(
a, lax.broadcast(np.eye(a.shape[-1], dtype=lax.dtype(a)), a.shape[:-2]))
@partial(jit, static_argnums=(1, 2, 3))
def _norm(x, ord, axis, keepdims):
x = _promote_arg_dtypes(np.asarray(x))
x_shape = np.shape(x)
ndim = len(x_shape)
if axis is None:
# NumPy has an undocumented behavior that admits arbitrary rank inputs if
# `ord` is None: https://github.com/numpy/numpy/issues/14215
if ord is None:
return np.sqrt(np.sum(np.real(x * np.conj(x)), keepdims=keepdims))
axis = tuple(range(ndim))
elif isinstance(axis, tuple):
axis = tuple(np._canonicalize_axis(x, ndim) for x in axis)
else:
axis = (np._canonicalize_axis(axis, ndim),)
num_axes = len(axis)
if num_axes == 1:
if ord is None or ord == 2:
return np.sqrt(np.sum(np.real(x * np.conj(x)), axis=axis,
keepdims=keepdims))
elif ord == np.inf:
return np.amax(np.abs(x), axis=axis, keepdims=keepdims)
elif ord == -np.inf:
return np.amin(np.abs(x), axis=axis, keepdims=keepdims)
elif ord == 0:
return np.sum(x != 0, dtype=np.finfo(lax.dtype(x)).dtype,
axis=axis, keepdims=keepdims)
elif ord == 1:
# Numpy has a special case for ord == 1 as an optimization. We don't
# really need the optimization (XLA could do it for us), but the Numpy
# code has slightly different type promotion semantics, so we need a
# special case too.
return np.sum(np.abs(x), axis=axis, keepdims=keepdims)
else:
abs_x = np.abs(x)
ord = lax._const(abs_x, ord)
out = np.sum(abs_x ** ord, axis=axis, keepdims=keepdims)
return np.power(out, 1. / ord)
elif num_axes == 2:
row_axis, col_axis = axis
if ord is None or ord in ('f', 'fro'):
return np.sqrt(np.sum(np.real(x * np.conj(x)), axis=axis,
keepdims=keepdims))
elif ord == 1:
if not keepdims and col_axis > row_axis:
col_axis -= 1
return np.amax(np.sum(np.abs(x), axis=row_axis, keepdims=keepdims),
axis=col_axis, keepdims=keepdims)
elif ord == -1:
if not keepdims and col_axis > row_axis:
col_axis -= 1
return np.amin(np.sum(np.abs(x), axis=row_axis, keepdims=keepdims),
axis=col_axis, keepdims=keepdims)
elif ord == np.inf:
if not keepdims and row_axis > col_axis:
row_axis -= 1
return np.amax(np.sum(np.abs(x), axis=col_axis, keepdims=keepdims),
axis=row_axis, keepdims=keepdims)
elif ord == -np.inf:
if not keepdims and row_axis > col_axis:
row_axis -= 1
return np.amin(np.sum(np.abs(x), axis=col_axis, keepdims=keepdims),
axis=row_axis, keepdims=keepdims)
elif ord in ('nuc', 2, -2):
x = np.moveaxis(x, axis, (-2, -1))
if ord == 2:
reducer = np.amax
elif ord == -2:
reducer = np.amin
else:
reducer = np.sum
y = reducer(svd(x, compute_uv=False), axis=-1)
if keepdims:
result_shape = list(x_shape)
result_shape[axis[0]] = 1
result_shape[axis[1]] = 1
y = np.reshape(y, result_shape)
return y
else:
raise ValueError("Invalid order '{}' for matrix norm.".format(ord))
else:
raise ValueError(
"Invalid axis values ({}) for np.linalg.norm.".format(axis))
@_wraps(onp.linalg.norm)
def norm(x, ord=None, axis=None, keepdims=False):
return _norm(x, ord, axis, keepdims)
@_wraps(onp.linalg.qr)
def qr(a, mode="reduced"):
if mode in ("reduced", "r", "full"):
full_matrices = False
elif mode == "complete":
full_matrices = True
else:
raise ValueError("Unsupported QR decomposition mode '{}'".format(mode))
a = _promote_arg_dtypes(np.asarray(a))
q, r = lax_linalg.qr(a, full_matrices)
if mode == "r":
return r
return q, r
@_wraps(onp.linalg.solve)
@jit
def solve(a, b):
a, b = _promote_arg_dtypes(np.asarray(a), np.asarray(b))
a_shape = np.shape(a)
b_shape = np.shape(b)
a_ndims = len(a_shape)
b_ndims = len(b_shape)
if not (a_ndims >= 2 and a_shape[-1] == a_shape[-2] and b_ndims >= 1):
msg = ("The arguments to solve must have shapes a=[..., m, m] and "
"b=[..., m, k] or b=[..., m]; got a={} and b={}")
raise ValueError(msg.format(a_shape, b_shape))
lu, pivots = lax_linalg.lu(a)
dtype = lax.dtype(a)
m = a_shape[-1]
# Numpy treats the RHS as a (batched) vector if the number of dimensions
# differ by 1. Otherwise, broadcasting rules apply.
x = b[..., None] if a_ndims == b_ndims + 1 else b
batch_dims = lax.broadcast_shapes(lu.shape[:-2], x.shape[:-2])
x = np.broadcast_to(x, batch_dims + x.shape[-2:])
lu = np.broadcast_to(lu, batch_dims + lu.shape[-2:])
permutation = lax_linalg.lu_pivots_to_permutation(pivots, m)
permutation = np.broadcast_to(permutation, batch_dims + (m,))
iotas = np.ix_(*(lax.iota(np.int32, b) for b in batch_dims + (1,)))
x = x[iotas[:-1] + (permutation, slice(None))]
x = lax_linalg.triangular_solve(lu, x, left_side=True, lower=True,
unit_diagonal=True)
x = lax_linalg.triangular_solve(lu, x, left_side=True, lower=False)
return x[..., 0] if a_ndims == b_ndims + 1 else x
for func in get_module_functions(onp.linalg):
if func.__name__ not in globals():
globals()[func.__name__] = _not_implemented(func)
|
jax-master
|
jax/numpy/linalg.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as onp
from .. import lax
from ..lib import xla_client
from ..util import get_module_functions
from .lax_numpy import _not_implemented
from .lax_numpy import _wraps
from . import lax_numpy as np
def _promote_to_complex(arg):
dtype = np.result_type(arg, onp.complex64)
# XLA's FFT op only supports C64.
if dtype == onp.complex128:
dtype = onp.complex64
return lax.convert_element_type(arg, dtype)
def _fft_core(func_name, fft_type, a, s, axes, norm):
# TODO(skye): implement padding/cropping based on 's'.
full_name = "jax.np.fft." + func_name
if s is not None:
raise NotImplementedError("%s only supports s=None, got %s" % (full_name, s))
if norm is not None:
raise NotImplementedError("%s only supports norm=None, got %s" % (full_name, norm))
if s is not None and axes is not None and len(s) != len(axes):
# Same error as numpy.
raise ValueError("Shape and axes have different lengths.")
orig_axes = axes
if axes is None:
if s is None:
axes = range(a.ndim)
else:
axes = range(a.ndim - len(s), a.ndim)
# XLA doesn't support 0-rank axes.
if len(axes) == 0:
return a
if len(axes) != len(set(axes)):
raise ValueError(
"%s does not support repeated axes. Got axes %s." % (full_name, axes))
if len(axes) > 3:
# XLA does not support FFTs over more than 3 dimensions
raise ValueError(
"%s only supports 1D, 2D, and 3D FFTs. "
"Got axes %s with input rank %s." % (full_name, orig_axes, a.ndim))
# XLA only supports FFTs over the innermost axes, so rearrange if necessary.
if orig_axes is not None:
axes = tuple(range(a.ndim - len(axes), a.ndim))
a = np.moveaxis(a, orig_axes, axes)
if s is None:
s = [a.shape[axis] for axis in axes]
a = _promote_to_complex(a)
transformed = lax.fft(a, fft_type, s)
if orig_axes is not None:
transformed = np.moveaxis(transformed, axes, orig_axes)
return transformed
@_wraps(onp.fft.fftn)
def fftn(a, s=None, axes=None, norm=None):
return _fft_core('fftn', xla_client.FftType.FFT, a, s, axes, norm)
@_wraps(onp.fft.ifftn)
def ifftn(a, s=None, axes=None, norm=None):
return _fft_core('ifftn', xla_client.FftType.IFFT, a, s, axes, norm)
@_wraps(onp.fft.fft)
def fft(a, n=None, axis=-1, norm=None):
if isinstance(axis,list) or isinstance(axis,tuple):
raise ValueError(
"jax.np.fft.fft does not support multiple axes. "
"Please use jax.np.fft.fftn. "
"Got axis %s." % (list(axis))
)
if not axis is None:
axis = [axis]
return _fft_core('fft', xla_client.FftType.FFT, a, s=n, axes=axis, norm=norm)
@_wraps(onp.fft.ifft)
def ifft(a, n=None, axis=-1, norm=None):
if isinstance(axis,list) or isinstance(axis,tuple):
raise ValueError(
"jax.np.fft.ifft does not support multiple axes. "
"Please use jax.np.fft.ifftn. "
"Got axis %s." % (list(axis))
)
if not axis is None:
axis = [axis]
return _fft_core('ifft', xla_client.FftType.IFFT, a, s=n, axes=axis, norm=norm)
@_wraps(onp.fft.fft2)
def fft2(a, s=None, axes=(-2,-1), norm=None):
if len(axes) != 2:
raise ValueError(
"jax.np.fft.fft2 only supports 2 axes. "
"Got axes = %s." % (list(axes))
)
return _fft_core('fft', xla_client.FftType.FFT, a, s=s, axes=axes, norm=norm)
@_wraps(onp.fft.ifft2)
def ifft2(a, s=None, axes=(-2,-1), norm=None):
if len(axes) != 2:
raise ValueError(
"jax.np.fft.ifft2 only supports 2 axes. "
"Got axes = %s." % (list(axes))
)
return _fft_core('ifft', xla_client.FftType.IFFT, a, s=s, axes=axes, norm=norm)
for func in get_module_functions(onp.fft):
if func.__name__ not in globals():
globals()[func.__name__] = _not_implemented(func)
|
jax-master
|
jax/numpy/fft.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
"""Interface and utility functions to XLA.
This module wraps the XLA client(s) and builders to standardize their interfaces
and provide some automatic type mapping logic for converting between Numpy and
XLA. There are also a handful of related casting utilities.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from functools import partial
import os
import warnings
from absl import logging
from ..config import flags
from .. import util
from .. import dtypes
import numpy as onp # 'onp' rather than 'np' to distinguish from autograd.numpy
import six
import threading
try:
from . import tpu_client
except ImportError:
tpu_client = None
from . import version
from . import xla_client
FLAGS = flags.FLAGS
flags.DEFINE_string(
'jax_xla_backend', 'xla',
'Default is "xla" for the XLA service directly, '
'or "tpu_driver" for using high-performance access to Cloud TPU hardware.')
flags.DEFINE_string(
'jax_backend_target', 'local',
'Either "local" or "rpc:address" to connect to a remote service target.')
flags.DEFINE_string(
'jax_platform_name',
os.getenv('JAX_PLATFORM_NAME', ''),
'Platform name for XLA. The default is to attempt to use a GPU if '
'available, but fall back to CPU otherwise. To set the platform manually, '
'pass "cpu" for CPU or "gpu" for GPU.')
def get_compile_options(num_replicas=None, device_assignment=None):
"""Returns the compile options to use, as derived from flag values.
Args:
num_replicas: Optional int indicating the number of replicas for which to
compile (default inherited from xla_client.CompileOptions).
device_assignment: Optional tuple of integers indicating the assignment of
logical replicas to physical devices (default inherited from
xla_client.CompileOptions). Must be consistent with `num_replicas`.
"""
compile_options = None
if num_replicas is not None:
compile_options = compile_options or xla_client.CompileOptions()
compile_options.num_replicas = num_replicas
if device_assignment is not None:
logging.vlog(2, "get_compile_options: num_replicas=%s device_assignment=%s",
num_replicas, device_assignment)
# NOTE(mattjj): xla_client.DeviceAssignment.create expects a 2D ndarray
# indexed by replica number and computation per replica, respectively, while
# here we currently assume only one computation per replica, hence the
# second axis is always trivial.
if num_replicas is not None and num_replicas != len(device_assignment):
msg = "device_assignment does not match num_replicas: {} vs {}."
raise ValueError(msg.format(device_assignment, num_replicas))
compile_options = compile_options or xla_client.CompileOptions()
device_assignment = onp.array(device_assignment)
if device_assignment.ndim == 1:
device_assignment = device_assignment[:, None]
device_assignment = xla_client.DeviceAssignment.create(device_assignment)
assert num_replicas is None or device_assignment.replica_count() == num_replicas
compile_options.device_assignment = device_assignment
return compile_options
_backends = {}
def register_backend(name, factory):
_backends[name] = factory
def _get_local_backend(platform=None):
if not platform:
platform = FLAGS.jax_platform_name
# Canonicalize platform names.
cpu = 'cpu'
gpu = 'gpu'
if platform == 'Host':
platform = cpu
elif platform == 'CUDA':
platform = gpu
elif platform == '':
platform = None
backend = xla_client.get_local_backend(platform)
if backend is None:
raise RuntimeError("No local XLA backends found.")
if backend.platform == cpu and platform != cpu:
warnings.warn('No GPU/TPU found, falling back to CPU.')
return backend
register_backend('xla', _get_local_backend)
# memoize the TPU driver to be consistent with xla_client behavior
_tpu_backend = None
def _get_tpu_driver_backend(platform):
del platform
global _tpu_backend
if _tpu_backend is None:
backend_target = FLAGS.jax_backend_target
if backend_target is None:
raise ValueError('When using TPU Driver as the backend, you must specify '
'--jax_backend_target=<hostname>:8470.')
_tpu_backend = tpu_client.TpuBackend.create(worker=backend_target)
return _tpu_backend
if tpu_client:
register_backend('tpu_driver', _get_tpu_driver_backend)
_backend_lock = threading.Lock()
@util.memoize
def get_backend(platform=None):
# TODO(mattjj,skyewm): remove this input polymorphism after we clean up how
# 'backend' values are handled
if isinstance(platform, xla_client.Backend):
return platform
with _backend_lock:
backend = _backends.get(FLAGS.jax_xla_backend)
if backend is None:
msg = 'Unknown jax_xla_backend value "{}".'
raise ValueError(msg.format(FLAGS.jax_xla_backend))
return backend(platform)
def get_device_backend(device=None):
"""Returns the Backend associated with `device`, or the default Backend."""
platform = device.platform if device else None
return get_backend(platform)
def device_count(backend=None):
"""Returns the total number of devices.
On most platforms, this is the same as ``local_device_count()``. However, on
multi-host platforms, this will return the total number of devices across all
hosts.
Args:
backend: This is an experimental feature and the API is likely to change.
Optional, a string representing the xla backend. 'cpu', 'gpu', or 'tpu'.
Returns:
Number of devices.
"""
return int(get_backend(backend).device_count())
def local_device_count(backend=None):
"""Returns the number of devices on this host."""
return int(get_backend(backend).local_device_count())
def devices(backend=None):
"""Returns a list of all devices.
Each device is represented by a subclass of Device (e.g. CpuDevice,
GpuDevice). The length of the returned list is equal to
``device_count()``. Local devices can be identified by comparing
``Device.host_id`` to ``host_id()``.
Args:
backend: This is an experimental feature and the API is likely to change.
Optional, a string representing the xla backend. 'cpu', 'gpu', or 'tpu'.
Returns:
List of Device subclasses.
"""
return get_backend(backend).devices()
def local_devices(host_id=None, backend=None):
"""Returns a list of devices local to a given host (this host by default)."""
if host_id is None:
host_id = get_backend(backend).host_id()
return [d for d in devices(backend) if d.host_id == host_id]
def host_id(backend=None):
"""Returns the integer host ID of this host.
On most platforms, this will always be 0. This will vary on multi-host
platforms though.
Args:
backend: This is an experimental feature and the API is likely to change.
Optional, a string representing the xla backend. 'cpu', 'gpu', or 'tpu'.
Returns:
Integer host ID.
"""
return get_backend(backend).host_id()
def host_ids(backend=None):
"""Returns a list of all host IDs."""
return list(set(d.host_id for d in devices(backend)))
def host_count(backend=None):
"""Returns the number of hosts."""
return len(host_ids(backend))
### utility functions
@util.memoize
def dtype_to_etype(dtype):
"""Convert from dtype to canonical etype (reading FLAGS.jax_enable_x64)."""
return xla_client.dtype_to_etype(dtypes.canonicalize_dtype(dtype))
@util.memoize
def supported_numpy_dtypes():
return {dtypes.canonicalize_dtype(dtype)
for dtype in xla_client.XLA_ELEMENT_TYPE_TO_DTYPE.values()}
# TODO(mattjj,frostig): try to remove this function
def normalize_to_xla_dtypes(val):
"""Normalize dtypes in a value."""
if hasattr(val, '__array__') or onp.isscalar(val):
return onp.asarray(val,
dtype=dtypes.canonicalize_dtype(dtypes.result_type(val)))
elif isinstance(val, (tuple, list)):
return tuple(normalize_to_xla_dtypes(x) for x in val)
raise TypeError('Can\'t convert to XLA: {}'.format(val))
class _JaxComputationBuilder(xla_client.ComputationBuilder):
"""Base class implementing all of JaxComputationBuilder.
This class is intended to override and augment the interface of an XLA
ComputationBuilder to form JaxComputationBuilder
"""
# Method name case follows that of the XLA ComputationBuilder
# pylint: disable=invalid-name
def Build(self, *args, **kwargs):
return super(_JaxComputationBuilder, self).Build(
*args, **kwargs)
def NumpyArrayConstant(self, value, canonicalize_types=True):
if canonicalize_types:
value = normalize_to_xla_dtypes(value)
return super(_JaxComputationBuilder, self).Constant(value)
def ConstantLike(self, example_value, value, canonicalize_types=True):
example_value = onp.asarray(example_value)
return self.Constant(onp.array(value, dtype=example_value.dtype))
def Constant(self, py_val, canonicalize_types=True):
"""Translate constant `py_val` to a constant for this ComputationBuilder.
Args:
py_val: a Python value to be translated to a constant.
Returns:
A representation of the constant, either a ComputationDataHandle or None
"""
py_type = type(py_val)
if py_type in _constant_handlers:
return _constant_handlers[py_type](self, py_val, canonicalize_types)
else:
raise TypeError("No constant handler for type: {}".format(py_type))
# TODO(mattjj): remove when CrossReplicaSum is added to XLA:CPU
def CrossReplicaSum(self, operand, replica_groups):
"""Workaround for CrossReplicaSum not being implemented on some backends."""
if len(replica_groups[0]) == 1:
return operand
else:
return super(_JaxComputationBuilder, self).CrossReplicaSum(
operand, replica_groups)
# TODO(mattjj): remove when AllToAll is added to XLA:CPU
def AllToAll(self, operand, split_axis, concat_axis, replica_groups):
"""Workaround for AllToAll not being implemented on some backends."""
if len(replica_groups[0]) == 1:
return operand
else:
return super(_JaxComputationBuilder, self).AllToAll(
operand, split_axis, concat_axis, replica_groups)
def make_computation_builder(name):
return _JaxComputationBuilder(name)
def register_constant_handler(type_, handler_fun):
_constant_handlers[type_] = handler_fun
_constant_handlers = {}
def _ndarray_constant_handler(c, val, canonicalize_types=True):
"""Constant handler for ndarray literals, handling zero-size strides.
This function essentially calls c.NumpyArrayConstant(val) except it has
special handling of arrays with any strides of size zero: for those, it
generates appropriate calls to NumpyArrayConstant, Broadcast, and Transpose
to avoid staging in large literals that might arise from np.zeros or np.ones
or the output of lax.broadcast (which uses onp.broadcast_to which in turn
uses size-zero strides).
Args:
c: XLA client ComputationBuilder.
val: an ndarray.
Returns:
An XLA ComputationDataHandle / XlaOp representing the constant ndarray
staged into the XLA Computation.
"""
# TODO(mattjj): revise this to use c.BroadcastInDim rather than Transpose
if onp.any(onp.equal(0, val.strides)) and val.size > 0:
zero_stride_axes, = onp.where(onp.equal(0, val.strides))
other_axes, = onp.where(onp.not_equal(0, val.strides))
collapsed_val = val[tuple(0 if ax in zero_stride_axes else slice(None)
for ax in range(val.ndim))]
xla_val = c.Broadcast(
c.NumpyArrayConstant(collapsed_val, canonicalize_types),
onp.take(val.shape, zero_stride_axes))
permutation = onp.argsort(tuple(zero_stride_axes) + tuple(other_axes))
return c.Transpose(xla_val, permutation)
else:
return c.NumpyArrayConstant(val, canonicalize_types)
register_constant_handler(onp.ndarray, _ndarray_constant_handler)
def _scalar_constant_handler(c, val, canonicalize_types=True):
return c.NumpyArrayConstant(val, canonicalize_types)
for scalar_type in [onp.int8, onp.int16, onp.int32, onp.int64,
onp.uint8, onp.uint16, onp.uint32, onp.uint64,
onp.float16, onp.float32, onp.float64, onp.float128,
onp.bool_, onp.longlong]:
register_constant_handler(scalar_type, _scalar_constant_handler)
def _python_scalar_handler(dtype, c, val, canonicalize_dtypes=True):
return c.NumpyArrayConstant(dtype.type(val))
for ptype, dtype in dtypes.python_scalar_dtypes.items():
register_constant_handler(ptype, partial(_python_scalar_handler, dtype))
|
jax-master
|
jax/lib/xla_bridge.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
# This module is largely a wrapper around `jaxlib` that performs version
# checking on import.
import jaxlib
_minimum_jaxlib_version = (0, 1, 37)
try:
from jaxlib import version as jaxlib_version
except:
# jaxlib is too old to have version number.
msg = 'This version of jax requires jaxlib version >= {}.'
raise ImportError(msg.format('.'.join(map(str, _minimum_jaxlib_version))))
version = tuple(int(x) for x in jaxlib_version.__version__.split('.'))
# Check the jaxlib version before importing anything else from jaxlib.
def _check_jaxlib_version():
if version < _minimum_jaxlib_version:
msg = 'jaxlib is version {}, but this version of jax requires version {}.'
if version == (0, 1, 23):
msg += ('\n\nA common cause of this error is that you installed jaxlib '
'using pip, but your version of pip is too old to support '
'manylinux2010 wheels. Try running:\n\n'
'pip install --upgrade pip\n'
'pip install --upgrade jax jaxlib\n')
raise ValueError(msg.format('.'.join(map(str, version)),
'.'.join(map(str, _minimum_jaxlib_version))))
_check_jaxlib_version()
try:
from jaxlib import tpu_client
except:
tpu_client = None
from jaxlib import xla_client
from jaxlib import lapack
from jaxlib import pytree
from jaxlib import cusolver
try:
from jaxlib import cuda_prng
except ImportError:
cuda_prng = None
|
jax-master
|
jax/lib/__init__.py
|
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from .scatter import index, index_add, index_update, index_min, index_max, segment_sum
|
jax-master
|
jax/ops/__init__.py
|
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
# Helpers for indexed updates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
from functools import partial
import numpy as onp
from .. import lax
from ..api import jit
from ..numpy import lax_numpy as np
def _scatter_update(x, idx, y, scatter_op):
"""Helper for indexed updates.
Computes the value of x that would result from computing::
x[idx] op= y
except in a pure functional way, with no in-place updating.
Args:
x: ndarray to be updated.
idx: None, an integer, a slice, an ellipsis, an ndarray with integer dtype,
or a tuple of those indicating the locations of `x` into which to scatter-
update the values in `y`.
y: values to be scattered.
scatter_op: callable, one of lax.scatter, lax.scatter_add, lax.scatter_min,
or lax_scatter_max.
Returns:
An ndarray representing an updated `x` after performing the scatter-update.
"""
x = np.asarray(x)
y = np.asarray(y)
# XLA gathers and scatters are very similar in structure; the scatter logic
# is more or less a transpose of the gather equivalent.
treedef, static_idx, dynamic_idx = np._split_index_for_jit(idx)
return _scatter_impl(x, y, scatter_op, treedef, static_idx, dynamic_idx)
# TODO(phawkins): re-enable jit after fixing excessive recompilation for
# slice indexes (e.g., slice(0, 5, None), slice(10, 15, None), etc.).
# @partial(jit, static_argnums=(2, 3, 4))
def _scatter_impl(x, y, scatter_op, treedef, static_idx, dynamic_idx):
y = lax.convert_element_type(y, lax.dtype(x))
idx = np._merge_static_and_dynamic_indices(treedef, static_idx, dynamic_idx)
indexer = np._index_to_gather(np.shape(x), idx)
# Broadcast `y` to the slice output shape.
y = np.broadcast_to(y, tuple(indexer.slice_shape))
# Collapse any `None`/`np.newaxis` dimensions.
y = np.squeeze(y, axis=indexer.newaxis_dims)
if indexer.reversed_y_dims:
y = lax.rev(y, indexer.reversed_y_dims)
# Transpose the gather dimensions into scatter dimensions (cf.
# lax._gather_transpose_rule)
dnums = lax.ScatterDimensionNumbers(
update_window_dims=indexer.dnums.offset_dims,
inserted_window_dims=indexer.dnums.collapsed_slice_dims,
scatter_dims_to_operand_dims=indexer.dnums.start_index_map
)
return scatter_op(x, indexer.gather_indices, y, dnums)
class _Indexable(object):
"""Helper object for building indexes for indexed update functions.
This is a singleton object that overrides the :code:`__getitem__` method
to return the index it is passed.
>>> jax.ops.index[1:2, 3, None, ..., ::2]
(slice(1, 2, None), 3, None, Ellipsis, slice(None, None, 2))
"""
__slots__ = ()
def __getitem__(self, index):
return index
#: Index object singleton
index = _Indexable()
def index_add(x, idx, y):
"""Pure equivalent of :code:`x[idx] += y`.
Returns the value of `x` that would result from the
NumPy-style :mod:`indexed assignment <numpy.doc.indexing>`::
x[idx] += y
Note the `index_add` operator is pure; `x` itself is
not modified, instead the new value that `x` would have taken is returned.
Unlike the NumPy code :code:`x[idx] += y`, if multiple indices refer to the
same location the updates will be summed. (NumPy would only apply the last
update, rather than summing the updates.) The order in which conflicting
updates are applied is implementation-defined and may be nondeterministic
(e.g., due to concurrency on some hardware platforms).
Args:
x: an array with the values to be updated.
idx: a Numpy-style index, consisting of `None`, integers, `slice` objects,
ellipses, ndarrays with integer dtypes, or a tuple of the above. A
convenient syntactic sugar for forming indices is via the
:data:`jax.ops.index` object.
y: the array of updates. `y` must be broadcastable to the shape of the
array that would be returned by `x[idx]`.
Returns:
An array.
>>> x = jax.numpy.ones((5, 6))
>>> jax.ops.index_add(x, jax.ops.index[2:4, 3:], 6.)
array([[1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1.],
[1., 1., 1., 7., 7., 7.],
[1., 1., 1., 7., 7., 7.],
[1., 1., 1., 1., 1., 1.]], dtype=float32)
"""
return _scatter_update(x, idx, y, lax.scatter_add)
def index_min(x, idx, y):
"""Pure equivalent of :code:`x[idx] = minimum(x[idx], y)`.
Returns the value of `x` that would result from the
NumPy-style :mod:`indexed assignment <numpy.doc.indexing>`::
x[idx] = minimum(x[idx], y)
Note the `index_min` operator is pure; `x` itself is
not modified, instead the new value that `x` would have taken is returned.
Unlike the NumPy code :code:`x[idx] = minimum(x[idx], y)`, if multiple indices
refer to the same location the final value will be the overall min. (NumPy
would only look at the last update, rather than all of the updates.)
Args:
x: an array with the values to be updated.
idx: a Numpy-style index, consisting of `None`, integers, `slice` objects,
ellipses, ndarrays with integer dtypes, or a tuple of the above. A
convenient syntactic sugar for forming indices is via the
:data:`jax.ops.index` object.
y: the array of updates. `y` must be broadcastable to the shape of the
array that would be returned by `x[idx]`.
Returns:
An array.
>>> x = jax.numpy.ones((5, 6))
>>> jax.ops.index_minimum(x, jax.ops.index[2:4, 3:], 0.)
array([[1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1.],
[1., 1., 1., 0., 0., 0.],
[1., 1., 1., 0., 0., 0.],
[1., 1., 1., 1., 1., 1.]], dtype=float32)
"""
return _scatter_update(x, idx, y, lax.scatter_min)
def index_max(x, idx, y):
"""Pure equivalent of :code:`x[idx] = maximum(x[idx], y)`.
Returns the value of `x` that would result from the
NumPy-style :mod:`indexed assignment <numpy.doc.indexing>`::
x[idx] = maximum(x[idx], y)
Note the `index_max` operator is pure; `x` itself is
not modified, instead the new value that `x` would have taken is returned.
Unlike the NumPy code :code:`x[idx] = maximum(x[idx], y)`, if multiple indices
refer to the same location the final value will be the overall max. (NumPy
would only look at the last update, rather than all of the updates.)
Args:
x: an array with the values to be updated.
idx: a Numpy-style index, consisting of `None`, integers, `slice` objects,
ellipses, ndarrays with integer dtypes, or a tuple of the above. A
convenient syntactic sugar for forming indices is via the
:data:`jax.ops.index` object.
y: the array of updates. `y` must be broadcastable to the shape of the
array that would be returned by `x[idx]`.
Returns:
An array.
>>> x = jax.numpy.ones((5, 6))
>>> jax.ops.index_max(x, jax.ops.index[2:4, 3:], 6.)
array([[1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1.],
[1., 1., 1., 6., 6., 6.],
[1., 1., 1., 6., 6., 6.],
[1., 1., 1., 1., 1., 1.]], dtype=float32)
"""
return _scatter_update(x, idx, y, lax.scatter_max)
def index_update(x, idx, y):
"""Pure equivalent of :code:`x[idx] = y`.
Returns the value of `x` that would result from the
NumPy-style :mod:`indexed assignment <numpy.doc.indexing>`::
x[idx] = y
Note the `index_update` operator is pure; `x` itself is
not modified, instead the new value that `x` would have taken is returned.
Unlike NumPy's :code:`x[idx] = y`, if multiple indices refer to the same
location it is undefined which update is chosen; JAX may choose the order of
updates arbitrarily and nondeterministically (e.g., due to concurrent
updates on some hardware platforms).
Args:
x: an array with the values to be updated.
idx: a Numpy-style index, consisting of `None`, integers, `slice` objects,
ellipses, ndarrays with integer dtypes, or a tuple of the above. A
convenient syntactic sugar for forming indices is via the
:data:`jax.ops.index` object.
y: the array of updates. `y` must be broadcastable to the shape of the
array that would be returned by `x[idx]`.
Returns:
An array.
>>> x = jax.numpy.ones((5, 6))
>>> jax.ops.index_update(x, jax.ops.index[::2, 3:], 6.)
array([[1., 1., 1., 6., 6., 6.],
[1., 1., 1., 1., 1., 1.],
[1., 1., 1., 6., 6., 6.],
[1., 1., 1., 1., 1., 1.],
[1., 1., 1., 6., 6., 6.]], dtype=float32)
"""
return _scatter_update(x, idx, y, lax.scatter)
def segment_sum(data, segment_ids, num_segments=None):
"""Computes the sum within segments of an array.
Similar to TensorFlow's segment_sum:
https://www.tensorflow.org/api_docs/python/tf/math/segment_sum
Args:
data: an array with the values to be summed.
segment_ids: an array with integer dtype that indicates the segments of
`data` (along its leading axis) to be summed. Values can be repeated and
need not be sorted. Values outside of the range [0, num_segments) are
wrapped into that range by applying np.mod.
num_segments: optional, an int with positive value indicating the number of
segments. The default is ``max(segment_ids % data.shape[0]) + 1`` but
since `num_segments` determines the size of the output, a static value
must be provided to use `segment_sum` in a `jit`-compiled function.
Returns:
An array with shape :code:`(num_segments,) + data.shape[1:]` representing the
segment sums.
"""
if num_segments is None:
num_segments = np.max(np.mod(segment_ids, data.shape[0])) + 1
num_segments = int(num_segments)
out = np.zeros((num_segments,) + data.shape[1:], dtype=data.dtype)
segment_ids = np.mod(segment_ids, num_segments)
return index_add(out, segment_ids, data)
|
jax-master
|
jax/ops/scatter.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from . import linalg
from . import ndimage
from . import special
from . import stats
|
jax-master
|
jax/scipy/__init__.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from functools import partial
import scipy.linalg
from jax import jit
from .. import lax
from .. import lax_linalg
from ..numpy.lax_numpy import _wraps
from ..numpy import lax_numpy as np
from ..numpy import linalg as np_linalg
_T = lambda x: np.swapaxes(x, -1, -2)
@partial(jit, static_argnums=(1,))
def _cholesky(a, lower):
a = np_linalg._promote_arg_dtypes(np.asarray(a))
l = lax_linalg.cholesky(a if lower else np.conj(_T(a)), symmetrize_input=False)
return l if lower else np.conj(_T(l))
@_wraps(scipy.linalg.cholesky)
def cholesky(a, lower=False, overwrite_a=False, check_finite=True):
del overwrite_a, check_finite
return _cholesky(a, lower)
@_wraps(scipy.linalg.cho_factor)
def cho_factor(a, lower=False, overwrite_a=False, check_finite=True):
return (cholesky(a, lower=lower), lower)
@partial(jit, static_argnums=(2,))
def _cho_solve(c, b, lower):
c, b = np_linalg._promote_arg_dtypes(np.asarray(c), np.asarray(b))
c_shape = np.shape(c)
b_shape = np.shape(b)
c_ndims = len(c_shape)
b_ndims = len(b_shape)
if not (c_ndims >= 2 and c_shape[-1] == c_shape[-2] and
(c_ndims == b_ndims or c_ndims == b_ndims + 1)):
msg = ("The arguments to solve must have shapes a=[..., m, m] and "
"b=[..., m, k] or b=[..., m]; got a={} and b={}")
raise ValueError(msg.format(c_shape, b_shape))
# TODO(phawkins): triangular_solve only supports matrices on the RHS, so we
# add a dummy dimension. Extend it to support vectors and simplify this.
b = b if c_ndims == b_ndims else b[..., None]
b = lax_linalg.triangular_solve(c, b, left_side=True, lower=lower,
transpose_a=not lower, conjugate_a=not lower)
b = lax_linalg.triangular_solve(c, b, left_side=True, lower=lower,
transpose_a=lower, conjugate_a=lower)
return b[..., 0] if c_ndims != b_ndims else b
@_wraps(scipy.linalg.cho_solve, update_doc=False)
def cho_solve(c_and_lower, b, overwrite_b=False, check_finite=True):
del overwrite_b, check_finite
c, lower = c_and_lower
return _cho_solve(c, b, lower)
@_wraps(scipy.linalg.svd)
def svd(a, full_matrices=True, compute_uv=True, overwrite_a=False,
check_finite=True, lapack_driver='gesdd'):
del overwrite_a, check_finite, lapack_driver
a = np_linalg._promote_arg_dtypes(np.asarray(a))
return lax_linalg.svd(a, full_matrices, compute_uv)
@_wraps(scipy.linalg.det)
def det(a, overwrite_a=False, check_finite=True):
del overwrite_a, check_finite
return np_linalg.det(a)
@_wraps(scipy.linalg.eigh)
def eigh(a, b=None, lower=True, eigvals_only=False, overwrite_a=False,
overwrite_b=False, turbo=True, eigvals=None, type=1,
check_finite=True):
del overwrite_a, overwrite_b, turbo, check_finite
if b is not None:
raise NotImplementedError("Only the b=None case of eigh is implemented")
if type != 1:
raise NotImplementedError("Only the type=1 case of eigh is implemented.")
if eigvals is not None:
raise NotImplementedError(
"Only the eigvals=None case of eigh is implemented.")
a = np_linalg._promote_arg_dtypes(np.asarray(a))
v, w = lax_linalg.eigh(a, lower=lower)
if eigvals_only:
return w
else:
return w, v
@_wraps(scipy.linalg.inv)
def inv(a, overwrite_a=False, check_finite=True):
del overwrite_a, check_finite
return np_linalg.inv(a)
@_wraps(scipy.linalg.lu_factor)
def lu_factor(a, overwrite_a=False, check_finite=True):
del overwrite_a, check_finite
a = np_linalg._promote_arg_dtypes(np.asarray(a))
return lax_linalg.lu(a)
@partial(jit, static_argnums=(3,))
def _lu_solve(lu, pivots, b, trans):
lu_shape = np.shape(lu)
b_shape = np.shape(b)
if len(lu_shape) != 2 or lu_shape[0] != lu_shape[1]:
raise ValueError("LU decomposition must be a square matrix, got shape {}"
.format(lu_shape))
if len(b_shape) < 1:
raise ValueError("b matrix must have rank >= 1, got shape {}"
.format(b_shape))
if b_shape[0] != lu_shape[0]:
raise ValueError("Dimension of LU decomposition matrix (shape {}) must "
"match leading axis of b array (shape {})"
.format(lu_shape, b_shape))
m = lu_shape[0]
permutation = lax_linalg.lu_pivots_to_permutation(np.array(pivots), m)
x = np.reshape(b, (m, -1))
if trans == 0:
x = x[permutation, :]
x = lax_linalg.triangular_solve(lu, x, left_side=True, lower=True,
unit_diagonal=True)
x = lax_linalg.triangular_solve(lu, x, left_side=True, lower=False)
elif trans == 1 or trans == 2:
conj = trans == 2
x = lax_linalg.triangular_solve(lu, x, left_side=True, lower=False,
transpose_a=True, conjugate_a=conj)
x = lax_linalg.triangular_solve(lu, x, left_side=True, lower=True,
unit_diagonal=True, transpose_a=True,
conjugate_a=conj)
x = x[np.argsort(permutation), :]
else:
raise ValueError("'trans' value must be 0, 1, or 2, got {}".format(trans))
return lax.reshape(x, b_shape)
@_wraps(scipy.linalg.lu_solve)
def lu_solve(lu_and_piv, b, trans=0, overwrite_b=False, check_finite=True):
del overwrite_b, check_finite
lu, pivots = lu_and_piv
return _lu_solve(lu, pivots, b, trans)
@partial(jit, static_argnums=(1,))
def _lu(a, permute_l):
a = np_linalg._promote_arg_dtypes(np.asarray(a))
lu, pivots = lax_linalg.lu(a)
dtype = lax.dtype(a)
m, n = np.shape(a)
permutation = lax_linalg.lu_pivots_to_permutation(pivots, m)
p = np.real(np.array(permutation == np.arange(m)[:, None], dtype=dtype))
k = min(m, n)
l = np.tril(lu, -1)[:, :k] + np.eye(m, k, dtype=dtype)
u = np.triu(lu)[:k, :]
if permute_l:
return np.matmul(p, l), u
else:
return p, l, u
@_wraps(scipy.linalg.lu, update_doc=False)
def lu(a, permute_l=False, overwrite_a=False, check_finite=True):
del overwrite_a, check_finite
return _lu(a, permute_l)
@partial(jit, static_argnums=(1, 2))
def _qr(a, mode, pivoting):
if pivoting:
raise NotImplementedError(
"The pivoting=True case of qr is not implemented.")
if mode in ("full", "r"):
full_matrices = True
elif mode == "economic":
full_matrices = False
else:
raise ValueError("Unsupported QR decomposition mode '{}'".format(mode))
a = np_linalg._promote_arg_dtypes(np.asarray(a))
q, r = lax_linalg.qr(a, full_matrices)
if mode == "r":
return r
return q, r
@_wraps(scipy.linalg.qr)
def qr(a, overwrite_a=False, lwork=None, mode="full", pivoting=False,
check_finite=True):
del overwrite_a, lwork, check_finite
return _qr(a, mode, pivoting)
@partial(jit, static_argnums=(2, 3))
def _solve(a, b, sym_pos, lower):
if not sym_pos:
return np_linalg.solve(a, b)
a, b = np_linalg._promote_arg_dtypes(np.asarray(a), np.asarray(b))
return cho_solve(cho_factor(a, lower=lower), b)
@_wraps(scipy.linalg.solve)
def solve(a, b, sym_pos=False, lower=False, overwrite_a=False, overwrite_b=False,
debug=False, check_finite=True):
del overwrite_a, overwrite_b, debug, check_finite
return _solve(a, b, sym_pos, lower)
@partial(jit, static_argnums=(2, 3, 4))
def _solve_triangular(a, b, trans, lower, unit_diagonal):
if trans == 0 or trans == "N":
transpose_a, conjugate_a = False, False
elif trans == 1 or trans == "T":
transpose_a, conjugate_a = True, False
elif trans == 2 or trans == "C":
transpose_a, conjugate_a = True, True
else:
raise ValueError("Invalid 'trans' value {}".format(trans))
a, b = np_linalg._promote_arg_dtypes(np.asarray(a), np.asarray(b))
# lax_linalg.triangular_solve only supports matrix 'b's at the moment.
b_is_vector = np.ndim(a) == np.ndim(b) + 1
if b_is_vector:
b = b[..., None]
out = lax_linalg.triangular_solve(a, b, left_side=True, lower=lower,
transpose_a=transpose_a,
conjugate_a=conjugate_a,
unit_diagonal=unit_diagonal)
if b_is_vector:
return out[..., 0]
else:
return out
@_wraps(scipy.linalg.solve_triangular)
def solve_triangular(a, b, trans=0, lower=False, unit_diagonal=False,
overwrite_b=False, debug=None, check_finite=True):
del overwrite_b, debug, check_finite
return _solve_triangular(a, b, trans, lower, unit_diagonal)
@_wraps(scipy.linalg.tril)
def tril(m, k=0):
return np.tril(m, k)
@_wraps(scipy.linalg.triu)
def triu(m, k=0):
return np.triu(m, k)
|
jax-master
|
jax/scipy/linalg.py
|
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
import itertools
import operator
import textwrap
import scipy.ndimage
from ..numpy import lax_numpy as np
from ..numpy.lax_numpy import _wraps
from ..util import safe_zip as zip
_nonempty_prod = functools.partial(functools.reduce, operator.mul)
_nonempty_sum = functools.partial(functools.reduce, operator.add)
_INDEX_FIXERS = {
'constant': lambda index, size: index,
'nearest': lambda index, size: np.clip(index, 0, size - 1),
'wrap': lambda index, size: index % size,
}
def _nearest_indices_and_weights(coordinate):
index = np.around(coordinate).astype(np.int32)
weight = coordinate.dtype.type(1)
return [(index, weight)]
def _linear_indices_and_weights(coordinate):
lower = np.floor(coordinate)
upper = np.ceil(coordinate)
l_index = lower.astype(np.int32)
u_index = upper.astype(np.int32)
one = coordinate.dtype.type(1)
l_weight = one - (coordinate - lower)
u_weight = one - l_weight # handles the edge case lower==upper
return [(l_index, l_weight), (u_index, u_weight)]
@_wraps(scipy.ndimage.map_coordinates, lax_description=textwrap.dedent("""\
Only linear interpolation (``order=1``) and modes ``'constant'``,
``'nearest'`` and ``'wrap'`` are currently supported. Note that
interpolation near boundaries differs from the scipy function, because we
fixed an outstanding bug (https://github.com/scipy/scipy/issues/2640);
this function interprets the ``mode`` argument as documented by SciPy, but
not as implemented by SciPy.
"""))
def map_coordinates(
input, coordinates, order, mode='constant', cval=0.0,
):
input = np.asarray(input)
coordinates = [np.asarray(c, input.dtype) for c in coordinates]
cval = np.asarray(cval, input.dtype)
if len(coordinates) != input.ndim:
raise ValueError('coordinates must be a sequence of length input.ndim, but '
'{} != {}'.format(len(coordinates), input.ndim))
index_fixer = _INDEX_FIXERS.get(mode)
if index_fixer is None:
raise NotImplementedError(
'jax.scipy.ndimage.map_coordinates does not yet support mode {}. '
'Currently supported modes are {}.'.format(mode, set(_INDEX_FIXERS)))
if mode == 'constant':
is_valid = lambda index, size: (0 <= index) & (index < size)
else:
is_valid = lambda index, size: True
if order == 0:
interp_fun = _nearest_indices_and_weights
elif order == 1:
interp_fun = _linear_indices_and_weights
else:
raise NotImplementedError(
'jax.scipy.ndimage.map_coordinates currently requires order<=1')
valid_1d_interpolations = []
for coordinate, size in zip(coordinates, input.shape):
interp_nodes = interp_fun(coordinate)
valid_interp = []
for index, weight in interp_nodes:
fixed_index = index_fixer(index, size)
valid = is_valid(index, size)
valid_interp.append((fixed_index, valid, weight))
valid_1d_interpolations.append(valid_interp)
outputs = []
for items in itertools.product(*valid_1d_interpolations):
indices, validities, weights = zip(*items)
if any(valid is not True for valid in validities):
all_valid = functools.reduce(operator.and_, validities)
contribution = np.where(all_valid, input[indices], cval)
else:
contribution = input[indices]
outputs.append(_nonempty_prod(weights) * contribution)
result = _nonempty_sum(outputs)
return result
|
jax-master
|
jax/scipy/ndimage.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as onp
import scipy.special as osp_special
from .. import lax
from ..api import custom_transforms, defjvp
from ..numpy import lax_numpy as np
from ..numpy.lax_numpy import (_wraps, asarray, _reduction_dims, _constant_like,
_promote_args_inexact)
@_wraps(osp_special.gammaln)
def gammaln(x):
x, = _promote_args_inexact("gammaln", x)
return lax.lgamma(x)
@_wraps(osp_special.betaln)
def betaln(x, y):
x, y = _promote_args_inexact("betaln", x, y)
return lax.lgamma(x) + lax.lgamma(y) - lax.lgamma(x + y)
@_wraps(osp_special.digamma, update_doc=False)
def digamma(x):
x, = _promote_args_inexact("digamma", x)
return lax.digamma(x)
@_wraps(osp_special.erf)
def erf(x):
x, = _promote_args_inexact("erf", x)
return lax.erf(x)
@_wraps(osp_special.erfc, update_doc=False)
def erfc(x):
x, = _promote_args_inexact("erfc", x)
return lax.erfc(x)
@_wraps(osp_special.erfinv)
def erfinv(x):
x, = _promote_args_inexact("erfinv", x)
return lax.erf_inv(x)
@_wraps(osp_special.logit, update_doc=False)
@custom_transforms
def logit(x):
x = asarray(x)
return lax.log(lax.div(x, lax.sub(lax._const(x, 1), x)))
defjvp(logit, lambda g, ans, x: g / (x * (1 - x)))
@_wraps(osp_special.expit, update_doc=False)
@custom_transforms
def expit(x):
x = asarray(x)
one = lax._const(x, 1)
return lax.div(one, lax.add(one, lax.exp(lax.neg(x))))
defjvp(expit, lambda g, ans, x: g * ans * (lax._const(ans, 1) - ans))
@_wraps(osp_special.logsumexp)
def logsumexp(a, axis=None, b=None, keepdims=False, return_sign=False):
if b is not None or return_sign:
raise NotImplementedError("Only implemented for b=None, return_sign=False")
dims = _reduction_dims(a, axis)
shape = lax.subvals(onp.shape(a), zip(dims, (1,) * len(dims)))
dimadd = lambda x: lax.reshape(x, shape)
amax = lax.reduce(a, _constant_like(a, -onp.inf), lax.max, dims)
amax = lax.select(lax.is_finite(amax), amax, lax.full_like(amax, 0))
amax_singletons = dimadd(amax)
out = lax.add(lax.log(lax.reduce(lax.exp(lax.sub(a, amax_singletons)),
_constant_like(a, 0), lax.add, dims)), amax)
return dimadd(out) if keepdims else out
@_wraps(osp_special.xlogy)
def xlogy(x, y):
x, y = _promote_args_inexact("xlogy", x, y)
return lax._safe_mul(x, lax.log(y))
@_wraps(osp_special.xlog1py, update_doc=False)
def xlog1py(x, y):
x, y = _promote_args_inexact("xlog1py", x, y)
return lax._safe_mul(x, lax.log1p(y))
@_wraps(osp_special.entr)
def entr(x):
x, = _promote_args_inexact("entr", x)
return lax.select(lax.lt(x, _constant_like(x, 0)),
lax.full_like(x, -onp.inf),
lax.neg(xlogy(x, x)))
@_wraps(osp_special.multigammaln, update_doc=False)
def multigammaln(a, d):
a, = _promote_args_inexact("multigammaln", a)
d = lax.convert_element_type(d, lax.dtype(a))
constant = lax.mul(lax.mul(lax.mul(_constant_like(a, 0.25), d),
lax.sub(d, _constant_like(a, 1))),
lax.log(_constant_like(a, onp.pi)))
res = np.sum(gammaln(np.expand_dims(a, axis=-1) -
lax.div(np.arange(d), _constant_like(a, 2))),
axis=-1)
return res + constant
# Normal distributions
# Functions "ndtr" and "ndtri" are derived from calculations made in:
# https://root.cern.ch/doc/v608/SpecFuncCephesInv_8cxx_source.html
# In the following email exchange, the author gives his consent to redistribute
# derived works under an Apache 2.0 license.
#
# From: Stephen Moshier <steve@moshier.net>
# Date: Sat, Jun 9, 2018 at 2:36 PM
# Subject: Re: Licensing cephes under Apache (BSD-like) license.
# To: rif <rif@google.com>
#
#
#
# Hello Rif,
#
# Yes, Google may distribute Cephes files under the Apache 2 license.
#
# If clarification is needed, I do not favor BSD over other free licenses.
# I would agree that Apache 2 seems to cover the concern you mentioned
# about sublicensees.
#
# Best wishes for good luck with your projects!
# Steve Moshier
#
#
#
# On Thu, 31 May 2018, rif wrote:
#
# > Hello Steve.
# > My name is Rif. I work on machine learning software at Google.
# >
# > Your cephes software continues to be incredibly useful and widely used. I
# > was wondering whether it would be permissible for us to use the Cephes code
# > under the Apache 2.0 license, which is extremely similar in permissions to
# > the BSD license (Wikipedia comparisons). This would be quite helpful to us
# > in terms of avoiding multiple licenses on software.
# >
# > I'm sorry to bother you with this (I can imagine you're sick of hearing
# > about this by now), but I want to be absolutely clear we're on the level and
# > not misusing your important software. In former conversation with Eugene
# > Brevdo (ebrevdo@google.com), you wrote "If your licensing is similar to BSD,
# > the formal way that has been handled is simply to add a statement to the
# > effect that you are incorporating the Cephes software by permission of the
# > author." I wanted to confirm that (a) we could use the Apache license, (b)
# > that we don't need to (and probably you don't want to) keep getting
# > contacted about individual uses, because your intent is generally to allow
# > this software to be reused under "BSD-like" license, and (c) you're OK
# > letting incorporators decide whether a license is sufficiently BSD-like?
# >
# > Best,
# >
# > rif
# >
# >
# >
# log_ndtr uses different functions over the ranges
# (-infty, lower](lower, upper](upper, infty)
# Lower bound values were chosen by examining where the support of ndtr
# appears to be zero, relative to scipy's (which is always 64bit). They were
# then made more conservative just to be safe. (Conservative means use the
# expansion more than we probably need to.)
_LOGNDTR_FLOAT64_LOWER = onp.array(-20, onp.float64)
_LOGNDTR_FLOAT32_LOWER = onp.array(-10, onp.float32)
# Upper bound values were chosen by examining for which values of 'x'
# Log[cdf(x)] is 0, after which point we need to use the approximation
# Log[cdf(x)] = Log[1 - cdf(-x)] approx -cdf(-x). We chose a value slightly
# conservative, meaning we use the approximation earlier than needed.
_LOGNDTR_FLOAT64_UPPER = onp.array(8, onp.float64)
_LOGNDTR_FLOAT32_UPPER = onp.array(5, onp.float32)
def ndtr(x):
r"""Normal distribution function.
Returns the area under the Gaussian probability density function, integrated
from minus infinity to x:
.. math::
\begin{align}
\mathrm{ndtr}(x) =&
\ \frac{1}{\sqrt{2 \pi}}\int_{-\infty}^{x} e^{-\frac{1}{2}t^2} dt \\
=&\ \frac{1}{2} (1 + \mathrm{erf}(\frac{x}{\sqrt{2}})) \\
=&\ \frac{1}{2} \mathrm{erfc}(\frac{x}{\sqrt{2}})
\end{align}
Args:
x: An array of type `float32`, `float64`.
Returns:
An array with `dtype=x.dtype`.
Raises:
TypeError: if `x` is not floating-type.
"""
x = np.asarray(x)
dtype = lax.dtype(x)
if dtype not in (np.float32, np.float64):
raise TypeError(
"x.dtype={} is not supported, see docstring for supported types."
.format(dtype))
return _ndtr(x)
def _ndtr(x):
"""Implements ndtr core logic."""
dtype = lax.dtype(x).type
half_sqrt_2 = dtype(0.5) * onp.sqrt(2., dtype=dtype)
w = x * half_sqrt_2
z = lax.abs(w)
y = lax.select(lax.lt(z, half_sqrt_2),
dtype(1.) + lax.erf(w),
lax.select(lax.gt(w, dtype(0.)),
dtype(2.) - lax.erfc(z),
lax.erfc(z)))
return dtype(0.5) * y
def ndtri(p):
r"""The inverse of the CDF of the Normal distribution function.
Returns `x` such that the area under the PDF from :math:`-\infty` to `x` is equal
to `p`.
A piece-wise rational approximation is done for the function.
This is a based on the implementation in netlib.
Args:
p: an array of type `float32`, `float64`.
Returns:
an array with `dtype=p.dtype`.
Raises:
TypeError: if `p` is not floating-type.
"""
x = np.asarray(p)
dtype = lax.dtype(p)
if dtype not in (np.float32, np.float64):
raise TypeError(
"x.dtype={} is not supported, see docstring for supported types."
.format(dtype))
return _ndtri(p)
def _ndtri(p):
"""Implements ndtri core logic."""
# Constants used in piece-wise rational approximations. Taken from the cephes
# library:
# https://root.cern.ch/doc/v608/SpecFuncCephesInv_8cxx_source.html
p0 = list(reversed([-5.99633501014107895267E1,
9.80010754185999661536E1,
-5.66762857469070293439E1,
1.39312609387279679503E1,
-1.23916583867381258016E0]))
q0 = list(reversed([1.0,
1.95448858338141759834E0,
4.67627912898881538453E0,
8.63602421390890590575E1,
-2.25462687854119370527E2,
2.00260212380060660359E2,
-8.20372256168333339912E1,
1.59056225126211695515E1,
-1.18331621121330003142E0]))
p1 = list(reversed([4.05544892305962419923E0,
3.15251094599893866154E1,
5.71628192246421288162E1,
4.40805073893200834700E1,
1.46849561928858024014E1,
2.18663306850790267539E0,
-1.40256079171354495875E-1,
-3.50424626827848203418E-2,
-8.57456785154685413611E-4]))
q1 = list(reversed([1.0,
1.57799883256466749731E1,
4.53907635128879210584E1,
4.13172038254672030440E1,
1.50425385692907503408E1,
2.50464946208309415979E0,
-1.42182922854787788574E-1,
-3.80806407691578277194E-2,
-9.33259480895457427372E-4]))
p2 = list(reversed([3.23774891776946035970E0,
6.91522889068984211695E0,
3.93881025292474443415E0,
1.33303460815807542389E0,
2.01485389549179081538E-1,
1.23716634817820021358E-2,
3.01581553508235416007E-4,
2.65806974686737550832E-6,
6.23974539184983293730E-9]))
q2 = list(reversed([1.0,
6.02427039364742014255E0,
3.67983563856160859403E0,
1.37702099489081330271E0,
2.16236993594496635890E-1,
1.34204006088543189037E-2,
3.28014464682127739104E-4,
2.89247864745380683936E-6,
6.79019408009981274425E-9]))
dtype = lax.dtype(p).type
shape = np.shape(p)
def _create_polynomial(var, coeffs):
"""Compute n_th order polynomial via Horner's method."""
coeffs = onp.array(coeffs, dtype)
if not coeffs.size:
return np.zeros_like(var)
return coeffs[0] + _create_polynomial(var, coeffs[1:]) * var
maybe_complement_p = np.where(p > dtype(-onp.expm1(-2.)), dtype(1.) - p, p)
# Write in an arbitrary value in place of 0 for p since 0 will cause NaNs
# later on. The result from the computation when p == 0 is not used so any
# number that doesn't result in NaNs is fine.
sanitized_mcp = np.where(
maybe_complement_p <= dtype(0.),
np.full(shape, dtype(0.5)),
maybe_complement_p)
# Compute x for p > exp(-2): x/sqrt(2pi) = w + w**3 P0(w**2)/Q0(w**2).
w = sanitized_mcp - dtype(0.5)
ww = lax.square(w)
x_for_big_p = w + w * ww * (_create_polynomial(ww, p0)
/ _create_polynomial(ww, q0))
x_for_big_p *= -dtype(onp.sqrt(2. * onp.pi))
# Compute x for p <= exp(-2): x = z - log(z)/z - (1/z) P(1/z) / Q(1/z),
# where z = sqrt(-2. * log(p)), and P/Q are chosen between two different
# arrays based on whether p < exp(-32).
z = lax.sqrt(dtype(-2.) * lax.log(sanitized_mcp))
first_term = z - lax.log(z) / z
second_term_small_p = (
_create_polynomial(dtype(1.) / z, p2) /
_create_polynomial(dtype(1.) / z, q2) / z)
second_term_otherwise = (
_create_polynomial(dtype(1.) / z, p1) /
_create_polynomial(dtype(1.) / z, q1) / z)
x_for_small_p = first_term - second_term_small_p
x_otherwise = first_term - second_term_otherwise
x = np.where(sanitized_mcp > dtype(onp.exp(-2.)),
x_for_big_p,
np.where(z >= dtype(8.0), x_for_small_p, x_otherwise))
x = np.where(p > dtype(1. - onp.exp(-2.)), x, -x)
infinity = np.full(shape, dtype(onp.inf))
x_nan_replaced = np.where(
p <= dtype(0.0), -infinity, np.where(p >= dtype(1.0), infinity, x))
return x_nan_replaced
@custom_transforms
def log_ndtr(x, series_order=3):
r"""Log Normal distribution function.
For details of the Normal distribution function see `ndtr`.
This function calculates :math:`\log(\mathrm{ndtr}(x))` by either calling
:math:`\log(\mathrm{ndtr}(x))` or using an asymptotic series. Specifically:
- For `x > upper_segment`, use the approximation `-ndtr(-x)` based on
:math:`\log(1-x) \approx -x, x \ll 1`.
- For `lower_segment < x <= upper_segment`, use the existing `ndtr` technique
and take a log.
- For `x <= lower_segment`, we use the series approximation of `erf` to compute
the log CDF directly.
The `lower_segment` is set based on the precision of the input:
.. math::
\begin{align}
\mathit{lower\_segment} =&
\ \begin{cases}
-20 & x.\mathrm{dtype}=\mathit{float64} \\
-10 & x.\mathrm{dtype}=\mathit{float32} \\
\end{cases} \\
\mathit{upper\_segment} =&
\ \begin{cases}
8& x.\mathrm{dtype}=\mathit{float64} \\
5& x.\mathrm{dtype}=\mathit{float32} \\
\end{cases}
\end{align}
When `x < lower_segment`, the `ndtr` asymptotic series approximation is:
.. math::
\begin{align}
\mathrm{ndtr}(x) =&\ \mathit{scale} * (1 + \mathit{sum}) + R_N \\
\mathit{scale} =&\ \frac{e^{-0.5 x^2}}{-x \sqrt{2 \pi}} \\
\mathit{sum} =&\ \sum_{n=1}^N {-1}^n (2n-1)!! / (x^2)^n \\
R_N =&\ O(e^{-0.5 x^2} (2N+1)!! / |x|^{2N+3})
\end{align}
where :math:`(2n-1)!! = (2n-1) (2n-3) (2n-5) ... (3) (1)` is a
`double-factorial
<https://en.wikipedia.org/wiki/Double_factorial>`_ operator.
Args:
x: an array of type `float32`, `float64`.
series_order: Positive Python integer. Maximum depth to
evaluate the asymptotic expansion. This is the `N` above.
Returns:
an array with `dtype=x.dtype`.
Raises:
TypeError: if `x.dtype` is not handled.
TypeError: if `series_order` is a not Python `integer.`
ValueError: if `series_order` is not in `[0, 30]`.
"""
if not isinstance(series_order, int):
raise TypeError("series_order must be a Python integer.")
if series_order < 0:
raise ValueError("series_order must be non-negative.")
if series_order > 30:
raise ValueError("series_order must be <= 30.")
x = np.asarray(x)
dtype = lax.dtype(x)
if dtype == np.float64:
lower_segment = _LOGNDTR_FLOAT64_LOWER
upper_segment = _LOGNDTR_FLOAT64_UPPER
elif dtype == np.float32:
lower_segment = _LOGNDTR_FLOAT32_LOWER
upper_segment = _LOGNDTR_FLOAT32_UPPER
else:
raise TypeError("x.dtype={} is not supported.".format(onp.dtype(dtype)))
# The basic idea here was ported from:
# https://root.cern.ch/doc/v608/SpecFuncCephesInv_8cxx_source.html
# We copy the main idea, with a few changes
# * For x >> 1, and X ~ Normal(0, 1),
# Log[P[X < x]] = Log[1 - P[X < -x]] approx -P[X < -x],
# which extends the range of validity of this function.
# * We use one fixed series_order for all of 'x', rather than adaptive.
# * Our docstring properly reflects that this is an asymptotic series, not a
# Taylor series. We also provided a correct bound on the remainder.
# * We need to use the max/min in the _log_ndtr_lower arg to avoid nan when
# x=0. This happens even though the branch is unchosen because when x=0
# the gradient of a select involves the calculation 1*dy+0*(-inf)=nan
# regardless of whether dy is finite. Note that the minimum is a NOP if
# the branch is chosen.
return np.where(
lax.gt(x, upper_segment),
-_ndtr(-x), # log(1-x) ~= -x, x << 1
np.where(lax.gt(x, lower_segment),
lax.log(_ndtr(lax.max(x, lower_segment))),
_log_ndtr_lower(lax.min(x, lower_segment),
series_order)))
def _log_ndtr_lower(x, series_order):
"""Asymptotic expansion version of `Log[cdf(x)]`, appropriate for `x<<-1`."""
dtype = lax.dtype(x).type
x_2 = lax.square(x)
# Log of the term multiplying (1 + sum)
log_scale = -dtype(0.5) * x_2 - lax.log(-x) - dtype(0.5 * onp.log(2. * onp.pi))
return log_scale + lax.log(_log_ndtr_asymptotic_series(x, series_order))
def _log_ndtr_asymptotic_series(x, series_order):
"""Calculates the asymptotic series used in log_ndtr."""
dtype = lax.dtype(x).type
if series_order <= 0:
return onp.array(1, dtype)
x_2 = lax.square(x)
even_sum = np.zeros_like(x)
odd_sum = np.zeros_like(x)
x_2n = x_2 # Start with x^{2*1} = x^{2*n} with n = 1.
for n in range(1, series_order + 1):
y = onp.array(_double_factorial(2 * n - 1), dtype) / x_2n
if n % 2:
odd_sum += y
else:
even_sum += y
x_2n *= x_2
return dtype(1.) + even_sum - odd_sum
def _double_factorial(n):
"""The double factorial function for small Python integer `n`."""
return onp.prod(onp.arange(n, 1, -2))
_norm_logpdf_constant = onp.log(onp.sqrt(2 * onp.pi))
def _norm_logpdf(x):
neg_half = _constant_like(x, -0.5)
log_normalizer = _constant_like(x, _norm_logpdf_constant)
return lax.sub(lax.mul(neg_half, lax.square(x)), log_normalizer)
defjvp(log_ndtr,
lambda g, ans, x: lax.mul(g, lax.exp(lax.sub(_norm_logpdf(x), ans))))
@_wraps(osp_special.i0e)
def i0e(x):
return lax.bessel_i0e(x)
@_wraps(osp_special.i1e)
def i1e(x):
return lax.bessel_i1e(x)
|
jax-master
|
jax/scipy/special.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as onp
import scipy.stats as osp_stats
from ... import lax
from ...numpy.lax_numpy import _promote_args_inexact, _constant_like, _wraps
@_wraps(osp_stats.laplace.logpdf, update_doc=False)
def logpdf(x, loc=0, scale=1):
x, loc, scale = _promote_args_inexact("laplace.logpdf", x, loc, scale)
two = _constant_like(x, 2)
linear_term = lax.div(lax.abs(lax.sub(x, loc)), scale)
return lax.neg(lax.add(linear_term, lax.log(lax.mul(two, scale))))
@_wraps(osp_stats.laplace.pdf, update_doc=False)
def pdf(x, loc=0, scale=1):
return lax.exp(logpdf(x, loc, scale))
@_wraps(osp_stats.laplace.cdf, update_doc=False)
def cdf(x, loc=0, scale=1):
x, loc, scale = _promote_args_inexact("laplace.cdf", x, loc, scale)
half = _constant_like(x, 0.5)
one = _constant_like(x, 1)
zero = _constant_like(x, 0)
diff = lax.div(lax.sub(x, loc), scale)
return lax.select(lax.le(diff, zero),
lax.mul(half, lax.exp(diff)),
lax.sub(one, lax.mul(half, lax.exp(lax.neg(diff)))))
|
jax-master
|
jax/scipy/stats/laplace.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as onp
import scipy.stats as osp_stats
from ... import lax
from ...numpy import lax_numpy as np
from ..special import gammaln, xlogy
def _is_simplex(x):
x_sum = np.sum(x, axis=-1)
return np.all(x > 0, axis=-1) & (x_sum <= 1) & (x_sum > 1 - 1e-6)
@np._wraps(osp_stats.dirichlet.logpdf, update_doc=False)
def logpdf(x, alpha):
args = (onp.ones((0,), lax.dtype(x)), onp.ones((1,), lax.dtype(alpha)))
to_dtype = lax.dtype(osp_stats.dirichlet.logpdf(*args))
x, alpha = [lax.convert_element_type(arg, to_dtype) for arg in (x, alpha)]
one = np._constant_like(x, 1)
normalize_term = np.sum(gammaln(alpha), axis=-1) - gammaln(np.sum(alpha, axis=-1))
log_probs = lax.sub(np.sum(xlogy(lax.sub(alpha, one), x), axis=-1), normalize_term)
return np.where(_is_simplex(x), log_probs, -np.inf)
@np._wraps(osp_stats.dirichlet.pdf, update_doc=False)
def pdf(x, alpha):
return lax.exp(logpdf(x, alpha))
|
jax-master
|
jax/scipy/stats/dirichlet.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as onp
import scipy.stats as osp_stats
from ... import lax
from ...numpy.lax_numpy import _promote_args_inexact, _wraps, where, inf
@_wraps(osp_stats.expon.logpdf, update_doc=False)
def logpdf(x, loc=0, scale=1):
x, loc, scale = _promote_args_inexact("expon.logpdf", x, loc, scale)
log_scale = lax.log(scale)
linear_term = lax.div(lax.sub(x, loc), scale)
log_probs = lax.neg(lax.add(linear_term, log_scale))
return where(lax.lt(x, loc), -inf, log_probs)
@_wraps(osp_stats.expon.pdf, update_doc=False)
def pdf(x, loc=0, scale=1):
return lax.exp(logpdf(x, loc, scale))
|
jax-master
|
jax/scipy/stats/expon.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as onp
import scipy.stats as osp_stats
from ... import lax
from ...numpy.lax_numpy import _promote_dtypes_inexact, _constant_like, _wraps
from ...numpy.lax_numpy import dot, subtract, einsum
from ...numpy.linalg import det, inv
@_wraps(osp_stats.multivariate_normal.logpdf, update_doc=False)
def logpdf(x, mean, cov):
x, mean, cov = _promote_dtypes_inexact(x, mean, cov)
two = _constant_like(x, 2)
dim = _constant_like(x, mean.shape[0])
det_sig = det(cov).astype(cov.dtype)
log_normalizer = lax.log(lax.mul(lax.pow(_constant_like(x, 2 * onp.pi), dim),
det_sig))
x_shape = x.shape[:-1]
if x_shape:
x_2d = x.reshape((-1, mean.shape[0]))
quadratic = einsum("ij,jk,ik->i", subtract(x_2d, mean), inv(cov),
subtract(x_2d, mean)).reshape(x_shape).astype(cov.dtype)
else:
quadratic = dot(dot(subtract(x, mean), inv(cov)), subtract(x, mean).T).astype(cov.dtype)
return lax.div(lax.neg(lax.add(log_normalizer, quadratic)), two)
@_wraps(osp_stats.multivariate_normal.pdf, update_doc=False)
def pdf(x, mean, cov):
return lax.exp(logpdf(x, mean, cov))
|
jax-master
|
jax/scipy/stats/multivariate_normal.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import scipy.stats as osp_stats
from ... import lax
from ...numpy import lax_numpy as np
from ..special import xlogy, gammaln
@np._wraps(osp_stats.poisson.logpmf, update_doc=False)
def logpmf(k, mu, loc=0):
k, mu, loc = np._promote_args_inexact("poisson.logpmf", k, mu, loc)
zero = np._constant_like(k, 0)
x = lax.sub(k, loc)
log_probs = xlogy(x, mu) - gammaln(x + 1) - mu
return np.where(lax.lt(x, zero), -np.inf, log_probs)
@np._wraps(osp_stats.poisson.pmf, update_doc=False)
def pmf(k, mu, loc=0):
return np.exp(logpmf(k, mu, loc))
|
jax-master
|
jax/scipy/stats/poisson.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as onp
import scipy.stats as osp_stats
from ... import lax
from ...numpy.lax_numpy import (_promote_args_inexact, _constant_like, _wraps,
where, inf, logical_or)
from ..special import betaln
@_wraps(osp_stats.beta.logpdf, update_doc=False)
def logpdf(x, a, b, loc=0, scale=1):
x, a, b, loc, scale = _promote_args_inexact("beta.logpdf", x, a, b, loc, scale)
one = _constant_like(x, 1)
shape_term = lax.neg(betaln(a, b))
y = lax.div(lax.sub(x, loc), scale)
log_linear_term = lax.add(lax.mul(lax.sub(a, one), lax.log(y)),
lax.mul(lax.sub(b, one), lax.log1p(lax.neg(y))))
log_probs = lax.sub(lax.add(shape_term, log_linear_term), lax.log(scale))
return where(logical_or(lax.gt(x, lax.add(loc, scale)),
lax.lt(x, loc)), -inf, log_probs)
@_wraps(osp_stats.beta.pdf, update_doc=False)
def pdf(x, a, b, loc=0, scale=1):
return lax.exp(logpdf(x, a, b, loc, scale))
|
jax-master
|
jax/scipy/stats/beta.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as onp
import scipy.stats as osp_stats
from ... import lax
from ... import numpy as np
from ...numpy.lax_numpy import _promote_args_inexact, _constant_like, _wraps
from .. import special
@_wraps(osp_stats.norm.logpdf, update_doc=False)
def logpdf(x, loc=0, scale=1):
x, loc, scale = _promote_args_inexact("norm.logpdf", x, loc, scale)
two = _constant_like(x, 2)
scale_sqrd = lax.pow(scale, two)
log_normalizer = lax.log(lax.mul(_constant_like(x, 2 * onp.pi), scale_sqrd))
quadratic = lax.div(lax.pow(lax.sub(x, loc), two), scale_sqrd)
return lax.div(lax.neg(lax.add(log_normalizer, quadratic)), two)
@_wraps(osp_stats.norm.pdf, update_doc=False)
def pdf(x, loc=0, scale=1):
return lax.exp(logpdf(x, loc, scale))
@_wraps(osp_stats.norm.cdf, update_doc=False)
def cdf(x, loc=0, scale=1):
x, loc, scale = _promote_args_inexact("norm.cdf", x, loc, scale)
return special.ndtr(lax.div(lax.sub(x, loc), scale))
@_wraps(osp_stats.norm.logcdf, update_doc=False)
def logcdf(x, loc=0, scale=1):
x, loc, scale = _promote_args_inexact("norm.logcdf", x, loc, scale)
return special.log_ndtr(lax.div(lax.sub(x, loc), scale))
@_wraps(osp_stats.norm.ppf, update_doc=False)
def ppf(q, loc=0, scale=1):
return np.array(special.ndtri(q) * scale + loc, 'float64')
|
jax-master
|
jax/scipy/stats/norm.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from . import bernoulli
from . import poisson
from . import beta
from . import cauchy
from . import dirichlet
from . import expon
from . import gamma
from . import laplace
from . import multivariate_normal
from . import norm
from . import pareto
from . import t
from . import uniform
|
jax-master
|
jax/scipy/stats/__init__.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as onp
import scipy.stats as osp_stats
from ... import lax
from ...numpy.lax_numpy import _promote_args_inexact, _constant_like, _wraps, inf, where
@_wraps(osp_stats.pareto.logpdf, update_doc=False)
def logpdf(x, b, loc=0, scale=1):
x, b, loc, scale = _promote_args_inexact("pareto.logpdf", x, b, loc, scale)
one = _constant_like(x, 1)
scaled_x = lax.div(lax.sub(x, loc), scale)
normalize_term = lax.log(lax.div(scale, b))
log_probs = lax.neg(lax.add(normalize_term, lax.mul(lax.add(b, one), lax.log(scaled_x))))
return where(lax.lt(x, lax.add(loc, scale)), -inf, log_probs)
@_wraps(osp_stats.pareto.pdf, update_doc=False)
def pdf(x, b, loc=0, scale=1):
return lax.exp(logpdf(x, b, loc, scale))
|
jax-master
|
jax/scipy/stats/pareto.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as onp
import scipy.stats as osp_stats
from ... import lax
from ...numpy.lax_numpy import _promote_args_inexact, _constant_like, _wraps
@_wraps(osp_stats.cauchy.logpdf, update_doc=False)
def logpdf(x, loc=0, scale=1):
x, loc, scale = _promote_args_inexact("cauchy.logpdf", x, loc, scale)
one = _constant_like(x, 1)
pi = _constant_like(x, onp.pi)
scaled_x = lax.div(lax.sub(x, loc), scale)
normalize_term = lax.log(lax.mul(pi, scale))
return lax.neg(lax.add(normalize_term, lax.log1p(lax.mul(scaled_x, scaled_x))))
@_wraps(osp_stats.cauchy.pdf, update_doc=False)
def pdf(x, loc=0, scale=1):
return lax.exp(logpdf(x, loc, scale))
|
jax-master
|
jax/scipy/stats/cauchy.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import scipy.stats as osp_stats
from ... import lax
from ...numpy.lax_numpy import (_constant_like, _promote_args_inexact, _wraps,
where, inf, logical_or)
@_wraps(osp_stats.uniform.logpdf, update_doc=False)
def logpdf(x, loc=0, scale=1):
x, loc, scale = _promote_args_inexact("uniform.logpdf", x, loc, scale)
log_probs = lax.neg(lax.log(scale))
return where(logical_or(lax.gt(x, lax.add(loc, scale)),
lax.lt(x, loc)),
-inf, log_probs)
@_wraps(osp_stats.uniform.pdf, update_doc=False)
def pdf(x, loc=0, scale=1):
return lax.exp(logpdf(x, loc, scale))
|
jax-master
|
jax/scipy/stats/uniform.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as onp
import scipy.stats as osp_stats
from ... import lax
from ...numpy import lax_numpy as np
from ..special import xlogy, xlog1py
@np._wraps(osp_stats.bernoulli.logpmf, update_doc=False)
def logpmf(k, p, loc=0):
k, p, loc = np._promote_args_inexact("bernoulli.logpmf", k, p, loc)
zero = np._constant_like(k, 0)
one = np._constant_like(k, 1)
x = lax.sub(k, loc)
log_probs = xlogy(x, p) + xlog1py(lax.sub(one, x), -p)
return np.where(np.logical_or(lax.lt(x, zero), lax.gt(x, one)),
-np.inf, log_probs)
@np._wraps(osp_stats.bernoulli.pmf, update_doc=False)
def pmf(k, p, loc=0):
return np.exp(pmf(k, p, loc))
|
jax-master
|
jax/scipy/stats/bernoulli.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as onp
import scipy.stats as osp_stats
from ... import lax
from ...numpy.lax_numpy import _promote_args_inexact, _constant_like, _wraps
@_wraps(osp_stats.t.logpdf, update_doc=False)
def logpdf(x, df, loc=0, scale=1):
x, df, loc, scale = _promote_args_inexact("t.logpdf", x, df, loc, scale)
two = _constant_like(x, 2)
scaled_x = lax.div(lax.sub(x, loc), scale)
df_over_two = lax.div(df, two)
df_plus_one_over_two = lax.add(df_over_two, _constant_like(x, 0.5))
normalize_term_const = lax.mul(lax.mul(scale, scale), _constant_like(x, onp.pi))
normalize_term_tmp = lax.div(lax.log(lax.mul(normalize_term_const, df)), two)
normalize_term = lax.sub(lax.add(lax.lgamma(df_over_two), normalize_term_tmp),
lax.lgamma(df_plus_one_over_two))
quadratic = lax.div(lax.mul(scaled_x, scaled_x), df)
return lax.neg(lax.add(normalize_term, lax.mul(df_plus_one_over_two, lax.log1p(quadratic))))
@_wraps(osp_stats.t.pdf, update_doc=False)
def pdf(x, df, loc=0, scale=1):
return lax.exp(logpdf(x, df, loc, scale))
|
jax-master
|
jax/scipy/stats/t.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as onp
import scipy.stats as osp_stats
from ... import lax
from ...numpy.lax_numpy import (_promote_args_inexact, _constant_like, _wraps,
where, inf)
from ..special import gammaln
@_wraps(osp_stats.gamma.logpdf, update_doc=False)
def logpdf(x, a, loc=0, scale=1):
x, a, loc, scale = _promote_args_inexact("gamma.logpdf", x, a, loc, scale)
one = _constant_like(x, 1)
y = lax.div(lax.sub(x, loc), scale)
log_linear_term = lax.sub(lax.mul(lax.sub(a, one), lax.log(y)), y)
shape_terms = lax.add(gammaln(a), lax.log(scale))
log_probs = lax.sub(log_linear_term, shape_terms)
return where(lax.lt(x, loc), -inf, log_probs)
@_wraps(osp_stats.gamma.pdf, update_doc=False)
def pdf(x, a, loc=0, scale=1):
return lax.exp(logpdf(x, a, loc, scale))
|
jax-master
|
jax/scipy/stats/gamma.py
|
# TODO:
# make pip installable
# should be able to set a list of default names, and if you don't pass in a name,
# it will pick a name at random from the list
import os
import logging
import random
from tpunicorn.tpu import get_tpu
class TPUMaker:
def __init__(self, debug_mode=True):
# set defaults
self.namelist = []
self.tf_version = "1.15.2"
self.preemptible_v8s = False
self.logger = logging.getLogger(__name__)
self.logger.setLevel(logging.DEBUG) if debug_mode else self.logger.setLevel(logging.INFO)
self.project = None
self.zone = None
def make_tpu(self, size, name=None, tf_version=None, accelerator_type="v3", preemptible=True, zone=None,
project=None):
project = self.project if project is None else project
assert project is not None, "Please set default project with maketpu setproject projectname, or pass in a " \
"project to maketpu.\n e.g, maketpu test 8 --project <projectname>"
zone = self.zone if zone is None else zone
assert zone is not None, "Please set default zone with maketpu setzone zonename, or pass in a " \
"zone to maketpu.\n e.g, maketpu test 8 --zone <zonename>"
# if making a v-8, set preemptible to false if this is the project's default
if not self.preemptible_v8s and size == 8:
preemptible = False
self.logger.debug(
"Setting preemptible to false, as this project's does not have access to preemptible v-8s")
if preemptible:
p = "--preemptible"
else:
p = ""
# if no name is specified, pick one at random from the namelist
if name is None:
name = self.get_name()
tf_version = self.tf_version if tf_version is None else tf_version
command = f"gcloud compute tpus create {name} --zone {zone} --project {project} --network default --version {tf_version} --accelerator-type {accelerator_type}-{size} {p}"
self.logger.info(command)
os.system(command)
def add_to_namelist(self, name):
self.namelist.append(name)
def set_project(self, project_name):
self.project = project_name
def set_zone(self, zone):
self.zone = zone
def tpu_exists(self, name):
if get_tpu(name, project=self.project, silent=True) is None:
return False
else:
return True
def get_name(self):
self.logger.debug("getting name")
if self.namelist:
available_names = self.namelist
name = random.choice(available_names)
x = 0
while True:
x += 1
self.logger.debug(available_names)
if not available_names:
raise Exception("All tpu names in default namelist already exist - please pass a name to "
"maketpu or update default namelist")
if self.tpu_exists(name):
self.logger.debug(f'TPU {name} exists')
available_names.remove(name)
name = random.choice(available_names)
self.logger.debug(f'trying {name}')
else:
break
self.logger.debug(f"got name {name}")
return name
else:
raise Exception("No name specified and default namelist is empty")
if __name__ == "__main__":
t = TPUMaker()
t.set_project("youdreamof-1543654322305")
t.set_zone("europe-west4-a")
t.namelist = ["test"]
t.tf_version = "2.4.0"
t.make_tpu(32)
|
DALLE-mtf-main
|
make_tpu.py
|
from functools import partial
import mesh_tensorflow as mtf
import tensorflow.compat.v1 as tf
from tensorflow.python.tpu import tpu_config, tpu_estimator
from tensorflow_estimator.python.estimator import estimator as estimator_lib
import argparse
from src.utils import *
from src.model_fns import vae_model_fn
from src.input_fns import vae_input_fn
def parse_args():
# Parse command line arguments
parser = argparse.ArgumentParser()
parser.add_argument("--tpu", type=str, help="Name of TPU to train on, if any.")
parser.add_argument("--gpu_ids", nargs="+", type=str, default=["device:GPU:0"],
help="If training on GPU, can specify your GPU names in a list - i.e 'device:GPU:0 device:GPU:1'")
parser.add_argument("--model", type=str, default=None, help="JSON file that contains model parameters.")
parser.add_argument("--new", action="store_true", help="If set, deletes previous checkpoint, if it exists, and "
"starts a new training run")
args = parser.parse_args()
assert args.model is not None, "Model must be set"
return args
def main():
# parse args and params
args = parse_args()
logging = setup_logging(args)
params = fetch_model_params(args.model)
assert params["model_type"].lower() == "vae", f'model_type {params["model_type"]} not recognized'
# get current step
current_step = int(estimator_lib._load_global_step_from_checkpoint_dir(params["model_path"]))
logging.info(f"Current step: {current_step}")
# Confirm deletion of checkpoint files if --new flag is set
if args.new:
maybe_remove_gs_or_filepath(params["model_path"])
# Add to params:
mesh_shape = mtf.convert_to_shape(params["mesh_shape"])
params["num_cores"] = mesh_shape.size
params["use_tpu"] = True if not args.tpu is None else False
params["gpu_ids"] = args.gpu_ids
# Set up TPUs and Estimator
if args.tpu == "colab":
tpu_cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver() if params["use_tpu"] else None
else:
tpu_cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver(args.tpu) if params[
"use_tpu"] else None
config = tpu_config.RunConfig(
cluster=tpu_cluster_resolver,
model_dir=params["model_path"],
save_checkpoints_steps=None, # Disable the default saver
save_checkpoints_secs=None, # Disable the default saver
log_step_count_steps=params["iterations"],
save_summary_steps=params["iterations"],
tpu_config=tpu_config.TPUConfig(
num_shards=mesh_shape.size,
iterations_per_loop=params["iterations"],
num_cores_per_replica=1,
experimental_host_call_every_n_steps=100,
per_host_input_for_training=tpu_config.InputPipelineConfig.BROADCAST))
estimator = tpu_estimator.TPUEstimator(
use_tpu=params["use_tpu"],
model_fn=vae_model_fn,
config=config,
train_batch_size=params["train_batch_size"],
eval_batch_size=params["eval_batch_size"],
predict_batch_size=params["predict_batch_size"],
params=params)
has_predict_or_eval_steps = params["predict_steps"] > 0 or params["eval_steps"] > 0
if has_predict_or_eval_steps:
# Eval and train - stop and predict and/or eval every checkpoint
while current_step < params["train_steps"]:
next_checkpoint = min(current_step + args.steps_per_checkpoint, params["train_steps"])
estimator.train(input_fn=partial(vae_input_fn, eval=False),
max_steps=next_checkpoint)
current_step = next_checkpoint
logging.info(f"Current step: {current_step}")
if params["predict_steps"] > 0:
raise NotImplementedError
if params["eval_steps"] > 0:
logging.info(f"Starting eval")
estimator.evaluate(input_fn=partial(vae_input_fn, eval=True),
max_steps=next_checkpoint)
return
else:
# Else, just train
while current_step < params["train_steps"]:
# Else, don't stop and restart
estimator.train(input_fn=partial(vae_input_fn, eval=False),
max_steps=params["train_steps"])
if __name__ == "__main__":
tf.disable_v2_behavior()
main()
|
DALLE-mtf-main
|
train_vae.py
|
from functools import partial
import mesh_tensorflow as mtf
import tensorflow.compat.v1 as tf
from tensorflow.python.tpu import tpu_config, tpu_estimator
from tensorflow_estimator.python.estimator import estimator as estimator_lib
import argparse
from src.utils import *
from src.model_fns import dalle_model_fn
from src.input_fns import dalle_input_fn
from src.data import get_tokenizer
def parse_args():
# Parse command line arguments
parser = argparse.ArgumentParser()
parser.add_argument("--tpu", type=str, help="Name of TPU to train on, if any.")
parser.add_argument("--gpu_ids", nargs="+", type=str, default=["device:GPU:0"],
help="If training on GPU, can specify your GPU names in a list - i.e 'device:GPU:0 device:GPU:1'")
parser.add_argument("--model", type=str, default=None, help="JSON file that contains model parameters.")
parser.add_argument("--new", action="store_true", help="If set, deletes previous checkpoint, if it exists, and "
"starts a new training run")
args = parser.parse_args()
assert args.model is not None, "Model must be set"
return args
def main():
# parse args and params
args = parse_args()
logging = setup_logging(args)
params = fetch_model_params(args.model)
params["vae_params"] = fetch_model_params(params["vae_model"])
assert params["model_type"].lower() == "dalle", f'model_type {params["model_type"]} not recognized'
# Confirm deletion of checkpoint files if --new flag is set
if args.new:
maybe_remove_gs_or_filepath(params["model_path"])
# get current step
current_step = int(estimator_lib._load_global_step_from_checkpoint_dir(params["model_path"]))
logging.info(f"Current step: {current_step}")
# Add to params:
mesh_shape = mtf.convert_to_shape(params["mesh_shape"])
params["num_cores"] = mesh_shape.size
params["use_tpu"] = True if not args.tpu is None else False
params["gpu_ids"] = args.gpu_ids
tokenizer = get_tokenizer(params["tokenizer"])
assert len(tokenizer) == params["text_vocab_size"], f"tokenizer vocab size {len(tokenizer)} must equal model vocab size {params['text_vocab_size']}"
params["padding_id"] = tokenizer.encode(tokenizer.pad_token)[0]
# Set up TPUs and Estimator
if args.tpu == "colab":
tpu_cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver() if params["use_tpu"] else None
else:
tpu_cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver(args.tpu) if params[
"use_tpu"] else None
config = tpu_config.RunConfig(
cluster=tpu_cluster_resolver,
model_dir=params["model_path"],
save_checkpoints_steps=None, # Disable the default saver
save_checkpoints_secs=None, # Disable the default saver
log_step_count_steps=params["iterations"],
save_summary_steps=params["iterations"],
tpu_config=tpu_config.TPUConfig(
num_shards=mesh_shape.size,
iterations_per_loop=params["iterations"],
num_cores_per_replica=1,
experimental_host_call_every_n_steps=100,
per_host_input_for_training=tpu_config.InputPipelineConfig.BROADCAST))
estimator = tpu_estimator.TPUEstimator(
use_tpu=params["use_tpu"],
model_fn=dalle_model_fn,
config=config,
train_batch_size=params["train_batch_size"],
eval_batch_size=params["eval_batch_size"],
predict_batch_size=params["predict_batch_size"],
params=params)
has_predict_or_eval_steps = params["predict_steps"] > 0 or params["eval_steps"] > 0
if has_predict_or_eval_steps:
# Eval and train - stop and predict and/or eval every checkpoint
while current_step < params["train_steps"]:
next_checkpoint = min(current_step + args.steps_per_checkpoint, params["train_steps"])
estimator.train(input_fn=partial(dalle_input_fn, eval=False),
max_steps=next_checkpoint)
current_step = next_checkpoint
if params["predict_steps"] > 0:
raise NotImplementedError
if params["eval_steps"] > 0:
raise NotImplementedError
return
else:
# Else, just train
while current_step < params["train_steps"]:
# Else, don't stop and restart
estimator.train(input_fn=partial(dalle_input_fn, eval=False),
max_steps=params["train_steps"])
if __name__ == "__main__":
tf.disable_v2_behavior()
main()
|
DALLE-mtf-main
|
train_dalle.py
|
from functools import partial
import tensorflow.compat.v1 as tf
from tensorflow.python.tpu import tpu_config, tpu_estimator
from tensorflow_estimator.python.estimator import estimator as estimator_lib
import argparse
from src.utils import *
from src.model_fns_tf import vae_model_fn
from src.input_fns import vae_input_fn
def parse_args():
# Parse command line arguments
parser = argparse.ArgumentParser()
parser.add_argument("--tpu", type=str, help="Name of TPU to train on, if any.")
parser.add_argument("--gpu_ids", nargs="+", type=str, default=["device:GPU:0"],
help="If training on GPU, can specify your GPU names in a list - i.e 'device:GPU:0 device:GPU:1'")
parser.add_argument("--model", type=str, default=None, help="JSON file that contains model parameters.")
parser.add_argument("--new", action="store_true", help="If set, deletes previous checkpoint, if it exists, and "
"starts a new training run")
args = parser.parse_args()
assert args.model is not None, "Model must be set"
return args
def main():
# parse args and params
args = parse_args()
logging = setup_logging(args)
params = fetch_model_params(args.model)
assert params["model_type"].lower() == "vae", f'model_type {params["model_type"]} not recognized'
# Confirm deletion of checkpoint files if --new flag is set
if args.new:
maybe_remove_gs_or_filepath(params["model_path"])
# get current step
current_step = int(estimator_lib._load_global_step_from_checkpoint_dir(params["model_path"]))
logging.info(f"Current step: {current_step}")
# Add to params:
params["use_tpu"] = True if not args.tpu is None else False
params["gpu_ids"] = args.gpu_ids
# Set up TPUs and Estimator
if args.tpu == "colab":
tpu_cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver() if params["use_tpu"] else None
else:
tpu_cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver(args.tpu) if params[
"use_tpu"] else None
config = tpu_config.RunConfig(
cluster=tpu_cluster_resolver,
model_dir=params["model_path"],
save_checkpoints_steps=params["steps_per_checkpoint"],
log_step_count_steps=params["iterations"],
save_summary_steps=params["iterations"],
tpu_config=tpu_config.TPUConfig(
iterations_per_loop=params["iterations"],
num_cores_per_replica=1,
experimental_host_call_every_n_steps=100,
per_host_input_for_training=tpu_config.InputPipelineConfig.BROADCAST))
estimator = tpu_estimator.TPUEstimator(
use_tpu=params["use_tpu"],
model_fn=vae_model_fn,
config=config,
train_batch_size=params["train_batch_size"],
eval_batch_size=params["eval_batch_size"],
predict_batch_size=params["predict_batch_size"],
params=params)
has_predict_or_eval_steps = params["predict_steps"] > 0 or params["eval_steps"] > 0
if has_predict_or_eval_steps:
# Eval and train - stop and predict and/or eval every checkpoint
while current_step < params["train_steps"]:
next_checkpoint = min(current_step + params["steps_per_checkpoint"], params["train_steps"])
estimator.train(input_fn=partial(vae_input_fn, eval=False),
max_steps=next_checkpoint)
current_step = next_checkpoint
logging.info(f"Current step: {current_step}")
if params["predict_steps"] > 0:
raise NotImplementedError
if params["eval_steps"] > 0:
logging.info(f"Starting eval")
estimator.evaluate(input_fn=partial(vae_input_fn, eval=True),
steps=params["eval_steps"])
return
else:
# Else, just train
while current_step < params["train_steps"]:
# Else, don't stop and restart
estimator.train(input_fn=partial(vae_input_fn, eval=False),
max_steps=params["train_steps"])
if __name__ == "__main__":
tf.disable_v2_behavior()
main()
|
DALLE-mtf-main
|
train_vae_tf.py
|
import tensorflow.compat.v1 as tf
import tensorflow.compat.v2 as tf2
from tensorflow.python.tpu import tpu_estimator
from .optimizers import get_optimizer
from .vae_tf import DiscreteVAE
from .utils import scalar_summary, mode_to_str, create_host_call
def vae_model_fn(features, labels, mode, params):
# Build mtf_features & seq length dict for getting number of microbatches
# We need to pack inputs into a dict to pass into serialize_training_step
H = W = params["dataset"]["image_size"] # TODO: check equal
mode_str = mode_to_str(mode)
batch_size = params[f"{mode_str}_batch_size"]
n_channels = params.get("input_channels", 3)
model = DiscreteVAE(
num_tokens=params["num_tokens"],
dim=params["n_embd"],
hidden_dim=params["hidden_dim"],
input_channels=n_channels,
convblocks=params.get("convblocks", [(3, 64), (3, 128), (3, 256)]),
recompute_grad=params.get("recompute_grad", False),
use_bf16=params.get("use_bf16", False),
stack_factor=params.get("stack_factor", 1),
dimensions=H
)
if mode == tf.estimator.ModeKeys.PREDICT:
raise NotImplementedError
train_gumbel = params.get("train_gumbel_hard", True)
eval_gumbel = params.get("eval_gumbel_hard", True)
# We're not predicting, so we better be training or evaluating
assert (mode == tf.estimator.ModeKeys.TRAIN or mode == tf.estimator.ModeKeys.EVAL)
gumbel = train_gumbel if mode == tf.estimator.ModeKeys.TRAIN else eval_gumbel
if params.get("temp_anneal_steps", None):
warmup_frac = tf.cast(tf.train.get_global_step(), tf.float32) / params["temp_anneal_steps"]
warmup_frac = tf.minimum(warmup_frac, tf.constant(1.0))
temp = params["temp_start"] - warmup_frac * (params["temp_start"] - params["temp"])
else:
temp = params.get("temp", 1.0)
# TODO: add back in microbatching
if params.get("use_bf16", False):
with tf.tpu.bfloat16_scope():
with tf.variable_scope("vae"):
loss, reconstruction = model.forward(features, return_recon_loss=True, temperature=temp, hard_gumbel=gumbel)
loss = tf.cast(loss, tf.float32)
reconstruction = tf.cast(reconstruction, tf.float32)
else:
with tf.variable_scope("vae"):
loss, reconstruction = model.forward(features, return_recon_loss=True, temperature=temp, hard_gumbel=gumbel)
optimizer = tf.train.AdamOptimizer(
learning_rate=params["lr"]
)
optimizer = tf.tpu.CrossShardOptimizer(optimizer)
global_step = tf.train.get_or_create_global_step()
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
train_op = optimizer.minimize(loss, global_step)
def host_call_fn(gs, loss, input, reconstruction):
gs = gs[0]
loss = tf.math.reduce_mean(loss)
denormalize = lambda x: (x + 1) / 2
with tf2.summary.create_file_writer(params['model_path']).as_default():
tf2.summary.scalar('loss', loss, step=gs)
tf2.summary.image('input_image', denormalize(input), step=gs)
tf2.summary.image('reconstruction_image', denormalize(reconstruction), step=gs)
return tf.summary.all_v2_summary_ops()
def metric_fn(gs, loss, input, reconstruction):
gs = gs[0]
loss = tf.math.reduce_mean(loss)
denormalize = lambda x: (x + 1) / 2
with tf2.summary.create_file_writer(params['model_path']).as_default():
loss_op = tf.metrics.mean(loss)
with tf2.summary.record_if(loss_op[0] < tf.constant(1e-9)):
tf2.summary.image('eval/input_image', denormalize(input), step=gs)
tf2.summary.image('eval/reconstruction_image', denormalize(reconstruction), step=gs)
with tf.control_dependencies(tf.summary.all_v2_summary_ops()):
dummy_op = tf.no_op()
return {"_loss": loss_op,
"zzz_dummy": (tf.constant(0), dummy_op)}
# To log the loss, current learning rate, and epoch for Tensorboard, the
# summary op needs to be run on the host CPU via host_call. host_call
# expects [batch_size, ...] Tensors, thus reshape to introduce a batch
# dimension. These Tensors are implicitly concatenated to
# [params['batch_size']].
gs_t = tf.reshape(global_step, [1])
loss_t = tf.reshape(loss, [1])
host_call = (host_call_fn, [gs_t, loss_t, features, reconstruction])
metric = (metric_fn, [gs_t, loss_t, features, reconstruction])
return tpu_estimator.TPUEstimatorSpec(
mode,
loss=loss,
host_call=host_call if mode == tf.estimator.ModeKeys.TRAIN else None,
train_op=train_op,
eval_metrics=metric)
|
DALLE-mtf-main
|
src/model_fns_tf.py
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import re
import mesh_tensorflow as mtf
import tensorflow.compat.v1 as tf
from .utils import scalar_summary
def clip_by_global_norm(grads, clip_norm):
"""Clip the grads by global norm."""
global_norm = mtf.sqrt(mtf.add_n([mtf.reduce_sum(mtf.square(t)) for t in grads if t is not None]))
multiplier = clip_norm / mtf.maximum(global_norm, clip_norm)
clipped_grads = [None if t is None else t * multiplier for t in grads]
return clipped_grads, global_norm
def get_optimizer(mesh, loss, params, variable_dtype, inp_var_grads=None):
"""Creates and returns an optimizer training op."""
global_step = tf.train.get_or_create_global_step()
# set defaults
end_step = params.get("lr_decay_end", params["train_steps"])
lr_decay = params.get("lr_decay", "cosine")
warmup_steps = params.get("warmup_steps", 3000)
gradient_clipping = params.get("gradient_clipping", 1.0)
optimizer_name = params.get("optimizer", "adam")
learning_rate = tf.constant(value=params["lr"], shape=[], dtype=variable_dtype.slice_dtype)
clip_value = mtf.constant(mesh, gradient_clipping, dtype=variable_dtype.slice_dtype)
if inp_var_grads is None:
var_grads = mtf.gradients([loss], [v.outputs[0] for v in mesh.graph.trainable_variables])
else:
var_grads = inp_var_grads
valid_grads_vars = list(filter(lambda grad_var: grad_var[0] is not None, zip(var_grads, mesh.graph.trainable_variables)))
valid_vars = [var for grad, var in valid_grads_vars]
valid_grad = [grad for grad, var in valid_grads_vars]
tf.logging.info([v for v in zip(var_grads, [v.outputs[0] for v in mesh.graph.trainable_variables])])
# Cast to full precision
var_grads_fp = [mtf.cast(v, variable_dtype.slice_dtype) for v in valid_grad]
if lr_decay == "linear":
learning_rate = tf.train.polynomial_decay(
learning_rate,
global_step,
end_step,
end_learning_rate=params["lr"] * 0.1, # Decrease to 10% of initial LR according to GPT-3 paper
power=1.0,
cycle=False)
elif lr_decay == "cosine":
learning_rate = tf.train.cosine_decay(
learning_rate,
global_step,
end_step,
alpha=0.1 # Alpha is min lr value as a fraction of init lr.
)
if warmup_steps > 0:
global_steps_int = tf.cast(global_step, tf.int32)
warmup_steps_int = tf.constant(warmup_steps, dtype=tf.int32)
dtype = variable_dtype.slice_dtype
global_steps_float = tf.cast(global_steps_int, dtype)
warmup_steps_float = tf.cast(warmup_steps_int, dtype)
warmup_percent_done = global_steps_float / warmup_steps_float
warmup_learning_rate = learning_rate * warmup_percent_done
is_warmup = tf.cast(global_steps_int < warmup_steps_int, dtype)
learning_rate = ((1.0 - is_warmup) * learning_rate +
is_warmup * warmup_learning_rate)
learning_rate = mtf.import_fully_replicated(mesh, learning_rate, mtf.Shape([]), name="learning_rate")
scalar_summary("lr", learning_rate)
if optimizer_name.lower() == "adam":
optimizer = mtf.optimize.AdamWeightDecayOptimizer(
learning_rate=learning_rate,
weight_decay_rate=params.get("weight_decay", 0.0),
beta_1=params.get("beta_1", 0.9),
beta_2=params.get("beta_2", 0.999),
epsilon=params.get("epsilon", 1e-6),
exclude_from_weight_decay=["norm", "bias"]
)
elif optimizer_name.lower() == "adafactor":
optimizer = mtf.optimize.AdafactorOptimizer(
learning_rate=learning_rate,
decay_rate=params.get("weight_decay", 0.0),
beta1=params.get("beta_1", 0.9),
epsilon1=params.get("epsilon_1", 1e-30),
epsilon2=params.get("epsilon_2", 1e-3)
)
else:
raise ValueError(f"{optimizer_name} not recognized")
if gradient_clipping is not None:
(var_grads_fp, _) = clip_by_global_norm(var_grads_fp, clip_norm=clip_value)
update_ops = optimizer.apply_grads(var_grads_fp, valid_vars)
return learning_rate, update_ops, var_grads_fp
# class AdamWeightDecayOptimizer(mtf.optimize.Optimizer):
# """A basic Adam optimizer that includes "correct" L2 weight decay."""
# def __init__(self,
# learning_rate,
# weight_decay_rate=0.0,
# beta_1=0.9,
# beta_2=0.999,
# epsilon=1e-6,
# exclude_from_weight_decay=None,
# variable_dtype=None):
# """Constructs a AdamWeightDecayOptimizer."""
# self.learning_rate = learning_rate
# self.weight_decay_rate = weight_decay_rate
# self.beta_1 = beta_1
# self.beta_2 = beta_2
# self.epsilon = epsilon
# self.exclude_from_weight_decay = exclude_from_weight_decay
# self.variable_dtype = variable_dtype
# def apply_grad(self, grad, var):
# """See base class."""
# if grad is None:
# tf.logging.warning("Gradient is None for variable %s" % var.name)
# return []
# grad = mtf.to_float(grad)
# assignments = []
# m = mtf.get_variable(
# var.mesh, var.name + "/adam_m", var.shape,
# initializer=tf.zeros_initializer(),
# # master_dtype=self.variable_dtype.master_dtype,
# # slice_dtype=self.variable_dtype.slice_dtype,
# # activation_dtype=self.variable_dtype.activation_dtype,
# trainable=False)
# v = mtf.get_variable(
# var.mesh, var.name + "/adam_v", var.shape,
# initializer=tf.zeros_initializer(),
# # master_dtype=self.variable_dtype.master_dtype,
# # slice_dtype=self.variable_dtype.slice_dtype,
# # activation_dtype=self.variable_dtype.activation_dtype,
# trainable=False)
# # Standard Adam update.
# next_m = self.beta_1 * m + (1.0 - self.beta_1) * grad
# next_v = self.beta_2 * v + (1.0 - self.beta_2) * mtf.square(grad)
# update = next_m / (mtf.sqrt(next_v) + self.epsilon)
# # Just adding the square of the weights to the loss function is *not*
# # the correct way of using L2 regularization/weight decay with Adam,
# # since that will interact with the m and v parameters in strange ways.
# #
# # Instead we want to decay the weights in a manner that doesn't interact
# # with the m/v parameters. This is equivalent to adding the square
# # of the weights to the loss with plain (non-momentum) SGD.
# if self._do_use_weight_decay(var.name):
# update += mtf.to_float(var.value) * self.weight_decay_rate
# update_with_lr = self.learning_rate * update
# var_update = mtf.assign_sub(var, update_with_lr)
# assignments.extend(
# [var_update,
# mtf.assign(m, next_m),
# mtf.assign(v, next_v)])
# return assignments
# def _do_use_weight_decay(self, param_name):
# """Whether to use L2 weight decay for `param_name`."""
# if not self.weight_decay_rate:
# return False
# if self.exclude_from_weight_decay:
# for r in self.exclude_from_weight_decay:
# if re.search(r, param_name) is not None:
# return False
# return True
|
DALLE-mtf-main
|
src/optimizers.py
|
import tensorflow.compat.v1 as tf
def crop_center_and_resize(img, size):
s = tf.shape(img)
w, h = s[0], s[1]
c = tf.maximum(w, h)
wn, hn = h / c, w / c
result = tf.image.crop_and_resize(tf.expand_dims(img, 0),
[[(1 - wn) / 2, (1 - hn) / 2, wn, hn]],
[0], [size, size])
return tf.squeeze(result, 0)
def decode_img(img, size, channels=3):
# convert the compressed string to a 3D uint8 tensor
img = tf.image.decode_jpeg(img, channels=channels)
# resize the image to the desired size
img = crop_center_and_resize(img, size)
img = (tf.cast(img, tf.float32) - 127.5) / 127.5
return img
def configure_for_performance(ds, params, eval=False):
if not eval:
ds = ds.shuffle(buffer_size=params["batch_size"] * 5)
ds = ds.batch(params["batch_size"], drop_remainder=True)
ds = ds.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)
return ds
def truncate_or_pad_label(label, params):
# pad by sequence length and gather the first sequence length items
# definitely a more efficient way to do this
label = tf.pad(label, [[0, params["text_seq_len"]]], constant_values=params["padding_id"])
label = tf.gather(label, tf.range(params["text_seq_len"]))
label = tf.reshape(label, [params["text_seq_len"]])
return label
def read_labeled_tfrecord(params):
def read_fn(example):
features = {
"image": tf.FixedLenFeature([], tf.string),
"caption": tf.VarLenFeature(tf.int64),
}
example = tf.parse_single_example(example, features)
label = tf.sparse.to_dense(example["caption"], example["caption"].dense_shape[0])
image = decode_img(example["image"], params["dataset"]["image_size"], params["n_channels"])
label = truncate_or_pad_label(label, params)
label = tf.cast(label, tf.int32)
return image, label # returns a dataset of (image, label) pairs
return read_fn
def read_tfrecord(params):
def read_fn(example):
features = {
"image": tf.FixedLenFeature([], tf.string),
}
example = tf.parse_single_example(example, features)
image = decode_img(example["image"], params["dataset"]["image_size"], params["n_channels"])
return image, image # returns image twice because they expect 2 returns
return read_fn
def vae_input_fn(params, eval=False):
path = params["dataset"]["train_path"] if not eval else params["dataset"]["eval_path"]
if "tfrecords" in params["dataset"] and params["dataset"]["tfrecords"]:
files = tf.io.gfile.glob(path)
file_count = len(files)
tf.logging.info(path)
tf.logging.info(f'FILE COUNT: {file_count}')
dataset = tf.data.Dataset.from_tensor_slices(files)
if not eval:
dataset = dataset.shuffle(file_count, reshuffle_each_iteration=False)
dataset = dataset.apply(
tf.data.experimental.parallel_interleave(tf.data.TFRecordDataset, cycle_length=4, sloppy=False))
parse_fn = read_tfrecord(params)
dataset = dataset.map(parse_fn, num_parallel_calls=tf.data.experimental.AUTOTUNE)
dataset = configure_for_performance(dataset, params, eval)
return dataset.repeat()
else:
files = tf.data.Dataset.list_files(path, shuffle=False)
image_count = len(tf.io.gfile.glob(path))
tf.logging.info(path)
tf.logging.info(f'IMAGE COUNT: {image_count}')
if not eval:
files = files.shuffle(image_count, reshuffle_each_iteration=False)
img_size = params["dataset"]["image_size"]
def _process_path(file_path):
img = tf.io.read_file(file_path)
img = decode_img(img, img_size)
# TODO: figure out if we can do away with the fake labels
return img, img
dataset = files.map(_process_path, num_parallel_calls=tf.data.experimental.AUTOTUNE)
dataset = configure_for_performance(dataset, params, eval)
return dataset.repeat()
def dalle_input_fn(params, eval=False):
path = params["dataset"]["train_path"] if not eval else params["dataset"]["eval_path"]
files = tf.io.gfile.glob(path)
file_count = len(files)
tf.logging.info(path)
tf.logging.info(f'FILE COUNT: {file_count}')
dataset = tf.data.Dataset.from_tensor_slices(files)
if not eval:
dataset = dataset.shuffle(file_count, reshuffle_each_iteration=False)
dataset = dataset.apply(tf.data.experimental.parallel_interleave(tf.data.TFRecordDataset, cycle_length=4, sloppy=False))
parse_fn = read_labeled_tfrecord(params)
dataset = dataset.map(parse_fn, num_parallel_calls=tf.data.experimental.AUTOTUNE)
dataset = configure_for_performance(dataset, params, eval)
return dataset.repeat()
|
DALLE-mtf-main
|
src/input_fns.py
|
import mesh_tensorflow as mtf
import tensorflow.compat.v1 as tf
from tensorflow.python.tpu import tpu_estimator
import mesh_tensorflow.transformer as mtf_transformer
from .optimizers import get_optimizer
from .utils import mode_to_str, get_graph_info, create_host_call, simd_mesh_setup, scalar_summary
from .dalle_mtf import DALLE
from .vae_tf import DiscreteVAE
def initialize_vae_weights(checkpoint_path, scope="vae"):
"""
Initialize the vae model from the checkpoint.
This function will be called after the graph has been constructed.
"""
vars_to_restore = tf.get_collection(
tf.GraphKeys.GLOBAL_VARIABLES, scope=scope)
ckpt_vars = [
name for name, _ in tf.train.list_variables(checkpoint_path)]
tf.logging.info(f"RESTORING {len(vars_to_restore)} VAE VARS FROM CHECKPOINT: ")
tf.logging.info(f"CHECKPOINT PATH: {checkpoint_path}")
tf.logging.info(f"CHECKPOINT VARS:")
tf.logging.info(ckpt_vars)
vae_load_dict = {}
for var in vars_to_restore:
var_name = var.name.split(":")[0]
tf.logging.info(var_name)
tf.logging.info(var)
vae_load_dict[var_name] = var
# Initialize vae weights
tf.train.init_from_checkpoint(checkpoint_path, vae_load_dict)
def load_vae_model(params, mode_str):
vae_checkpoint_path = params.get("vae_checkpoint_path")
vae_params = params.get("vae_params")
assert vae_params is not None, "vae model config must be supplied"
if vae_checkpoint_path is None:
vae_checkpoint_path = tf.train.latest_checkpoint(vae_params["model_path"])
assert vae_checkpoint_path is not None, "pretrained vae needed for training"
D = params["dataset"]["image_size"]
vae_model = DiscreteVAE(
num_tokens=vae_params["num_tokens"],
dim=vae_params["dim"],
hidden_dim=vae_params["hidden_dim"],
input_channels=vae_params.get("input_channels", 3),
convblocks=params.get("vae_params").get("convblocks", [(3, 64), (3, 128), (3, 256)]),
stack_factor=params.get("vae_params").get("stack_factor", 1),
dimensions=D
)
return vae_model, vae_checkpoint_path
def dalle_model_fn(features, labels, mode, params):
# since we can simply infer labels here based on the input - features here are the text input,
# and labels are the image input
global_step = tf.train.get_global_step() # Get global step
mode_str = mode_to_str(mode)
# load vae in tensorflow graph before mtf
vae, vae_checkpoint_path = load_vae_model(params, mode_str)
initialize_vae_weights(vae_checkpoint_path)
H = W = params["dataset"]["image_size"]
image_seq_len = (vae.H // (2 ** len(vae.convblocks))) ** 2 // (vae.stack_factor ** 2) # TODO: check this is correct
batch_size = params[f"{mode_str}_batch_size"]
n_channels = params.get("input_channels", 3)
with tf.variable_scope("vae"):
vae_logits = vae.forward(features, return_logits=True)
# TODO: using argmax sampling for now, but is that optimal?
tokens = tf.math.argmax(vae_logits, -1)
img_tokens_reshaped = tf.cast(tf.reshape(tokens, (batch_size, image_seq_len)), tf.int32)
# Construct mtf graph + mesh from params
graph = mtf.Graph()
mesh_shape = mtf.convert_to_shape(params["mesh_shape"])
layout_rules = mtf.convert_to_layout_rules(params["layout"])
# Mesh setup
if params["use_tpu"]:
var_placer, mesh_impl = simd_mesh_setup(params, mesh_shape, layout_rules)
else:
var_placer = None
gpu_ids = params["gpu_ids"]
mesh_impl = mtf.placement_mesh_impl.PlacementMeshImpl(
mesh_shape, layout_rules, gpu_ids)
# Build mtf mesh object
mesh = mtf.Mesh(graph, "my_mesh", var_placer)
model = DALLE(
n_embd=params["n_embd"],
text_vocab_size=params["text_vocab_size"],
image_vocab_size=params["image_vocab_size"],
text_seq_len=params["text_seq_len"],
image_seq_len=image_seq_len,
n_layers=params["n_layers"],
n_heads=params["n_heads"],
batch_size=batch_size,
bf_16=params["bf_16"],
mode=mode_str,
params=params,
)
# Build mtf_features & seq length dict for getting number of microbatches
# We need to pack inputs into a dict to pass into serialize_training_step
features_dict = {"image_inputs": features,
"text_inputs": labels}
mtf_features = {}
for key, x in features_dict.items():
if x is not None:
if key == "text_inputs":
text_tokens = tf.reshape(x, [batch_size, params["text_seq_len"]])
x = tf.concat((text_tokens, img_tokens_reshaped + model.text_vocab_size), axis=1)
mtf_shape = mtf.Shape([model.dimensions["batch_dim"], model.dimensions["total_seq_dim"]])
mtf_features["tokens"] = mtf.import_fully_replicated(mesh, x, mtf_shape, name=key)
if key == "image_inputs":
mtf_shape = mtf.Shape([
model.dimensions["batch_dim"],
mtf.Dimension("img_height_dim", vae.H),
mtf.Dimension("img_width_dim", vae.W),
mtf.Dimension("img_channel_dim", vae.num_ch),
])
x = tf.reshape(x, [batch_size, H, W, n_channels]) # NHWC
mtf_features["image_inputs"] = mtf.import_fully_replicated(mesh, x, mtf_shape, name=key)
scalar_summary("input_image", mtf_features["image_inputs"])
if mode == tf.estimator.ModeKeys.PREDICT:
raise NotImplementedError
# We're not predicting, so we better be training or evaluating
assert (mode == tf.estimator.ModeKeys.TRAIN or mode == tf.estimator.ModeKeys.EVAL)
if mode == tf.estimator.ModeKeys.TRAIN:
# Gets number of microbatches per batch for serialized training
# if param tokens_per_mb_per_replica = None, this defaults to 1 and no microbatching is performed
num_microbatches = int(mtf_transformer.utils.serialize_num_microbatches(batch_dim=model.dimensions["batch_dim"],
sequence_length=model.total_seq_dim,
mesh_shape=mesh_shape,
layout_rules=layout_rules,
tokens_per_microbatch_per_replica=
params[
"tokens_per_mb_per_replica"]))
else:
num_microbatches = 1
params["num_microbatches"] = num_microbatches # Add num microbatches to params
if num_microbatches > 1:
# For serialize_training_step we need to modify the model to output results in a dict
def serialized_fn(mtf_features):
loss, loss_batch = model.forward(mtf_features, return_loss=True)
return {"loss": loss, "loss_batch": loss_batch}
# Serialize the training step - Gradients are accumulated locally and reduced once.
var_grads, output_dict = mtf.serialize_training_step(mtf_features, serialized_fn, model.dimensions["batch_dim"],
num_microbatches)
loss = output_dict["loss"]
loss_batch = output_dict["loss_batch"]
else:
loss, loss_batch = model.forward(mtf_features, return_loss=True)
del loss_batch # TODO: may need this for some metrics - otherwise, remove from output
if mode == tf.estimator.ModeKeys.TRAIN:
# In TRAIN mode, get optimizer
if num_microbatches > 1:
# If we are splitting the batch into microbatches, var grads are created in the serialize_training_step fn
# So we pass them in here
_, update_ops, var_grads = get_optimizer(mesh, loss, params, variable_dtype=model.variable_dtype,
inp_var_grads=var_grads)
else:
# Otherwise, they are created in the get_optimizer fn, so we leave inp_var_grads blank
_, update_ops, var_grads = get_optimizer(mesh, loss, params, variable_dtype=model.variable_dtype)
# Log summaries to tensorboard
scalar_summary("loss", loss)
# Gets & prints info about no. trainable vars in the model & dimension names
get_graph_info(graph)
# 'lowers' mtf tensors into a tf graph - this enables us to export results as tf tensors
lowering = mtf.Lowering(graph, {mesh: mesh_impl}, autostack=False)
tf_loss = lowering.export_to_tf_tensor(loss)
tf_loss = tf.cast(tf_loss, tf.float32)
if mode == tf.estimator.ModeKeys.TRAIN:
# Use our patched version until mtf updates theirs
host_call = create_host_call(params['model_path'])
mtf.utils.remove_summaries()
# Creates train_op
tf_update_ops = [lowering.lowered_operation(op) for op in update_ops]
tf_update_ops.append(tf.assign_add(global_step, 1)) # Need to manually increment global_step
train_op = tf.group(tf_update_ops)
with mtf.utils.outside_all_rewrites():
# Copy master variables to slices. Must be called first.
restore_hook = mtf.MtfRestoreHook(lowering)
if mode == tf.estimator.ModeKeys.TRAIN:
# Set up the checkpoint server and return the TPUEstimatorSpec
saver = tf.train.Saver(
tf.global_variables(),
sharded=True,
max_to_keep=params.get("max_checkpoints", 5),
keep_checkpoint_every_n_hours=2,
defer_build=False,
save_relative_paths=True)
tf.add_to_collection(tf.GraphKeys.SAVERS, saver)
saver_listener = mtf.MtfCheckpointSaverListener(lowering)
saver_hook = tf.train.CheckpointSaverHook(
params["model_path"],
save_steps=params["steps_per_checkpoint"],
saver=saver,
listeners=[saver_listener])
return tpu_estimator.TPUEstimatorSpec(
tf.estimator.ModeKeys.TRAIN,
loss=tf_loss,
host_call=host_call,
train_op=train_op,
training_hooks=[restore_hook, saver_hook])
elif mode == tf.estimator.ModeKeys.EVAL:
return tpu_estimator.TPUEstimatorSpec(
tf.estimator.ModeKeys.EVAL,
evaluation_hooks=[restore_hook],
loss=tf_loss,
eval_metrics=None)
|
DALLE-mtf-main
|
src/model_fns.py
|
import mesh_tensorflow as mtf
import mesh_tensorflow.transformer as mtf_transformer
import tensorflow.compat.v1 as tf
from math import sqrt
from collections import defaultdict
import math
from .ops import pad, exists, get_variable_dtype
from .layers import gumbel_softmax, mse_loss, norm
class DiscreteVAE:
def __init__(self,
num_tokens,
batch_size,
dimensions,
dim=512,
hidden_dim=64,
input_channels=3,
num_layers=3,
params=None,
bf_16=True):
self.num_tokens = num_tokens
self.batch_dim = mtf.Dimension("batch_dim", batch_size)
self.dim = mtf.Dimension("dim", dim)
self.hdim = mtf.Dimension("hdim", hidden_dim)
self.hdim2 = mtf.Dimension("hdim2", hidden_dim)
self.tokens_dim = mtf.Dimension("tokens_dim", num_tokens)
self.channels_dim = mtf.Dimension("channels_dim", input_channels)
self.H = self.W = dimensions
self.height_dim = mtf.Dimension("height_dim", self.H)
self.width_dim = mtf.Dimension("width_dim", self.W)
self.dimensions = {
"batch_dim": self.batch_dim,
"dim": self.dim,
"hdim": self.hdim,
"hdim2": self.hdim2,
"tokens_dim": self.tokens_dim,
"channels_dim": self.channels_dim,
"height_dim": self.height_dim,
"width_dim": self.width_dim
}
self.conv2d = mtf.layers.conv2d
self.conv2dtranspose = mtf.layers.conv2d_transpose
self.activation = mtf.relu
self.embedding = mtf.layers.embedding
self.bf_16 = bf_16
self.variable_dtype = get_variable_dtype(bf_16)
if params is None: # extra params
params = {}
self.params = defaultdict(lambda: None, params)
self.num_layers = num_layers
def encoder_block(self, n, is_last=False):
def fn(x):
hdim = self.hdim if n % 2 == 0 else self.hdim2
x = self.conv2d(x, hdim, (4, 4), (2, 2), padding="SAME", name=f"conv{n}",
variable_dtype=self.variable_dtype)
x = self.activation(x, name=f"enc_activ{n}")
if is_last:
x = self.conv2d(x, self.tokens_dim, (1, 1), (1, 1), variable_dtype=self.variable_dtype, name="final_conv")
tf.logging.info("compressed shape: ")
tf.logging.info(x.shape)
return x
return fn
def decoder_block(self, n, is_last=False):
def fn(x):
hdim = self.hdim if n % 2 == 0 else self.hdim2
x = self.conv2dtranspose(x, hdim, (4, 4), (2, 2), padding="SAME", name=f"convtranspose{n}",
variable_dtype=self.variable_dtype)
x = self.activation(x, name=f"dec_activ{n}")
if is_last:
x = self.conv2d(x, self.channels_dim, (1, 1), (1, 1), variable_dtype=self.variable_dtype, name="final_conv")
return x
return fn
def encoder(self, x):
with tf.variable_scope("encoder"):
for n in range(self.num_layers):
is_last = n == self.num_layers - 1
block_fn = self.encoder_block(n, is_last)
if self.params.get("recompute_grad", False) and (self.mode == "train"):
x = mtf.recompute_grad(block_fn, [x])
else:
x = block_fn(x)
return x
def decoder(self, x):
with tf.variable_scope("decoder"):
for n in range(self.num_layers):
is_last = n == self.num_layers - 1
block_fn = self.decoder_block(n, is_last)
if self.params.get("recompute_grad", False) and (self.mode == "train"):
x = mtf.recompute_grad(block_fn, [x])
else:
x = block_fn(x)
return x
def decode(self, img_seq):
image_embeds = self.embedding(img_seq, self.tokens_dim, self.dim, variable_dtype=self.variable_dtype,
name="embedding")
n_dim = image_embeds.shape[1]
n = n_dim.size
h = w = int(sqrt(n))
h_dim = mtf.Dimension("h", h)
w_dim = mtf.Dimension("w", w)
out_shape = mtf.Shape([image_embeds.shape[0], image_embeds.shape[-1], h_dim, w_dim])
image_embeds = mtf.einsum([img_seq], output_shape=out_shape, reduced_dims=[n_dim], name="embd_rearrange")
images = self.decoder(image_embeds)
return images
def forward(self, features, return_recon_loss=False, return_logits=False, hard_gumbel=True):
if isinstance(features, dict):
img = features["inputs"]
else:
img = features
logits = self.encoder(img)
if return_logits:
return logits # return logits for getting hard image indices for DALL-E training
soft_one_hot = gumbel_softmax(logits, self.tokens_dim, temperature=1., hard=hard_gumbel)
embedding_weights = mtf.layers.embedding_weights(logits.mesh, self.tokens_dim, self.dim,
variable_dtype=tf.float32, name="embedding")
out_shape = mtf.Shape \
([soft_one_hot.shape[0], soft_one_hot.shape[1], soft_one_hot.shape[2], embedding_weights.shape[1]])
sampled = mtf.einsum([soft_one_hot, embedding_weights],
output_shape=out_shape, name="codebook_einsum")
out = self.decoder(sampled)
denormalize = lambda x: (x + 1) / 2
if not return_recon_loss:
return denormalize(out)
loss = mse_loss(mtf.cast(img, out.dtype), out)
return loss, denormalize(out)
class DALLE:
def __init__(self, n_embd, text_vocab_size=12800, image_vocab_size=512, text_seq_len=256, image_seq_len=1024,
n_layers=6, n_heads=8, batch_size=32, bf_16=True, attn_mask=None, mode="train",
is_incremental_inference=False, context=None, loss_fn=None, params=None, eos_token_id=None,
activation_fn=None):
self.n_embd = n_embd
self.text_vocab_size = text_vocab_size
self.image_vocab_size = image_vocab_size
self.text_seq_len = text_seq_len
self.image_seq_len = image_seq_len
self.total_seq_dim = text_seq_len + image_seq_len
self.n_layers = n_layers
self.n_heads = n_heads
self.attn_mask = attn_mask
self.total_tokens = text_vocab_size + image_vocab_size + 1 # extra for EOS
self.eos_token_id = self.total_tokens - 1 if eos_token_id is None else eos_token_id
self.dimensions = {"embed_dim": mtf.Dimension("embed_dim", n_embd),
"text_vocab_dim": mtf.Dimension("vocab_dim", text_vocab_size),
"image_vocab_dim": mtf.Dimension("vocab_dim", image_vocab_size),
"final_vocab_dim": mtf.Dimension("vocab_dim", self.total_tokens),
"total_seq_dim": mtf.Dimension("total_seq_dim", self.total_seq_dim),
"embed_seq_dim": mtf.Dimension("embed_seq_dim", self.total_seq_dim),
"memory_len_dim": mtf.Dimension("memory_len_dim", self.total_seq_dim),
"heads_dim": mtf.Dimension("heads", n_heads),
"kv_dim": mtf.Dimension("kv_dim", n_embd // n_heads),
"batch_dim": mtf.Dimension("batch_dim", batch_size)}
self.bf_16 = bf_16
self.variable_dtype = get_variable_dtype(bf_16)
self.mode = mode
self.context = context
self.is_incremental_inference = is_incremental_inference
if loss_fn is None:
loss_fn = mtf.layers.softmax_cross_entropy_with_logits
self.loss_fn = loss_fn
if activation_fn is None:
activation_fn = mtf.relu
self.activation_fn = activation_fn
if self.is_incremental_inference:
assert self.context is not None, "must have context in incremental inference"
if params is None: # extra params
params = {}
self.params = defaultdict(lambda: None, params)
def embedding(self, x, name):
embd_dim = self.dimensions["embed_dim"]
vocab_dim = self.dimensions["final_vocab_dim"]
with tf.variable_scope(name):
wte = mtf.get_variable(x.mesh, "wte",
mtf.Shape([vocab_dim, embd_dim]),
initializer=tf.random_normal_initializer(stddev=0.02),
master_dtype=self.variable_dtype.master_dtype,
slice_dtype=self.variable_dtype.slice_dtype,
activation_dtype=self.variable_dtype.activation_dtype)
# Text embedding
x = mtf.gather(wte, x, vocab_dim)
embed_dropout = self.params.get("embed_dropout", 0)
if embed_dropout > 0 and self.mode == "train":
x = mtf.dropout(x, rate=embed_dropout, name="wte_dropout")
return x
def positional_embedding(self, x, name):
with tf.variable_scope(name):
# Positional embedding
wpe = mtf.get_variable(x.mesh, "wpe",
mtf.Shape([self.dimensions["embed_seq_dim"], self.dimensions["embed_dim"]]),
initializer=tf.random_normal_initializer(stddev=0.01),
master_dtype=self.variable_dtype.master_dtype,
slice_dtype=self.variable_dtype.slice_dtype,
activation_dtype=self.variable_dtype.activation_dtype)
position_indices = mtf.range(x.mesh, self.dimensions["total_seq_dim"], tf.int64) if not \
self.is_incremental_inference else (self.context.position - 1)
pos_emb = mtf.gather(wpe, position_indices, wpe.shape[0])
embed_dropout = self.params.get("embed_dropout", 0)
if embed_dropout > 0 and self.mode == "train":
pos_emb = mtf.dropout(pos_emb, rate=embed_dropout, name="wte_dropout")
x += pos_emb
return x
def get_attn_mask(self, mesh, nd, ns):
if not exists(self.attn_mask):
i = mtf.range(mesh, nd, tf.int32) + ns.size - nd.size
j = mtf.range(mesh, ns, tf.int32)
i, j = map(lambda t: mtf.broadcast(t, [nd, ns]), (i, j))
self.attn_mask = mtf.cast(mtf.less(i, j), self.variable_dtype.activation_dtype) * -1e10
return self.attn_mask
def attention(self, x, n_state, mask, attention_type="global", name="attn"):
# x :: [batch, seq, n_embd]
batch_dim, seq_dim, embd_dim = x_shape = x.shape
assert n_state.size % self.n_heads == 0, "n_state must be divisible by n_heads"
with tf.variable_scope(name):
# Compute attention inputs
mtfparams = mtf.transformer.attention.attention_params_simple(
x.mesh,
io_dim=self.dimensions["embed_dim"],
kv_dim=self.dimensions["kv_dim"],
heads_dim=self.dimensions["heads_dim"],
variable_dtype=self.variable_dtype
)
q = mtfparams.compute_q(x)
k = mtfparams.compute_k(x)
v = mtfparams.compute_v(x)
if self.is_incremental_inference:
one_hot = mtf.one_hot(self.context.position - 1, seq_dim, dtype=self.variable_dtype.master_dtype)
inv_one_hot = 1.0 - one_hot
old_k, old_v = self.context.get_states(2)
k = old_k * inv_one_hot + k * one_hot
v = old_v * inv_one_hot + v * one_hot
if exists(self.context):
self.context.record_new_states([k, v])
with tf.variable_scope("attention"):
if attention_type == "local":
# `local_attention_1d` has built in autoregressive masking, so we don't need mask_attn_weights.
radius = self.params.get("local_attention_radius", 256)
if self.is_incremental_inference:
q *= one_hot
a = mtf_transformer.attention.local_attention_1d(
q, k, v,
length_dim=k.shape[1],
key_dim=self.dimensions["kv_dim"],
value_dim=self.dimensions["kv_dim"],
radius=radius,
length_dim_num_splits=1,
fully_autoregressive=True,
attention_kwargs={},
)
if self.is_incremental_inference:
a = mtf.gather(a, self.context.position - 1, seq_dim)
elif attention_type == "global":
if exists(mask):
if not self.is_incremental_inference:
broadcasted_mask = mtf.broadcast(mask,
[batch_dim, self.dimensions["heads_dim"], mask.shape[-2],
mask.shape[-1]]) # TODO: not sure this is correct
else:
# In the incremental case, a custom mask needs to be built that masks out all key/values that are greater than the current position
mask = mtf.gather(mask, self.context.position - 1, seq_dim)
broadcasted_mask = mtf.broadcast(mask,
[batch_dim, self.dimensions["heads_dim"], mask.shape[-1]])
k = mtf.replace_dimensions(k, k.shape[1], self.dimensions["memory_len_dim"])
v = mtf.replace_dimensions(v, v.shape[1], self.dimensions["memory_len_dim"])
attn_dropout_rate = self.params.get("attention_dropout", 0) if self.mode == "train" else 0
a = mtf_transformer.attention.attention(
q, k, v,
memory_length_dim=self.dimensions["memory_len_dim"],
key_dim=self.dimensions["kv_dim"],
value_dim=self.dimensions["kv_dim"],
bias=broadcasted_mask,
dropout_rate=attn_dropout_rate
)
else:
raise NotImplementedError("Unknown attention type {}!".format(attention_type))
with tf.variable_scope("compute_output"):
a = mtfparams.compute_output(a, x_shape)
with tf.variable_scope("compute_output_bias"):
b = mtf.get_variable(x.mesh, "o_b", [embd_dim], initializer=tf.constant_initializer(0),
master_dtype=self.variable_dtype.master_dtype,
slice_dtype=self.variable_dtype.slice_dtype,
activation_dtype=self.variable_dtype.activation_dtype)
a += b
residual_dropout = self.params.get("residual_dropout", 0)
if self.mode == "train" and residual_dropout > 0:
a = mtf.dropout(a, rate=residual_dropout, name="res_dropout")
return a
def mlp(self, x, n_state, name="mlp"):
residual_dropout = self.params.get("residual_dropout", 0)
with tf.variable_scope(name):
h = self.activation_fn(self.linear(x, n_state, name="mlp_linear_1"))
h2 = self.linear(h, x.shape[-1], name="mlp_linear_2", scale=True)
if self.mode == "train" and residual_dropout > 0:
h2 = mtf.dropout(h2, rate=residual_dropout, name="mlp_dropout")
return h2
def block(self, mask, name):
def fn(x):
with tf.variable_scope(name):
intermediate_size = x.shape[-1].size * 4 # Grab last dimension from input
x += self.attention(self.layer_norm(x, "norm_1"), x.shape[-1], name="attn", mask=mask)
# Define intermediate layer of mlp - to split
dim_intermediate_expanded = mtf.Dimension("intermediate_expanded", intermediate_size)
x += self.mlp(self.layer_norm(x, "norm_2"), dim_intermediate_expanded, name="mlp")
return x
return fn
def transformer(self, x, mask):
for layer in range(self.n_layers):
# attn blocks
block_fn = self.block(mask, f"layer_{layer}")
# If true and in train mode, enable gradient checkpointing
if self.params.get("recompute_grad", False) and (self.mode == "train"):
x = mtf.recompute_grad(block_fn, [x])
else:
x = block_fn(x)
return x
def _loss(self, logits, labels):
with tf.variable_scope("loss_final"):
loss_batch = self.loss_fn(logits=logits, targets=labels,
vocab_dim=logits.shape[-1], z_loss=0.0)
with tf.variable_scope("reduce_mean_final"):
loss = mtf.reduce_mean(loss_batch)
loss /= self.params.get("num_microbatches", 1)
# Convert to train dtype
loss = mtf.cast(loss, self.variable_dtype.slice_dtype)
return loss, loss_batch # loss batch must be returned for metric fns
def linear(self, x, new_dim, w_init_stdev=0.02, params=None, scale=False, name="linear"):
# nf = number of features
scale_type = self.params.get("scale_type", "scale_by_depth")
if scale_type == "scale_by_depth" and scale:
# Scale by sqrt(num_layers), only happens at the final projection before a res block output
w_init_stdev = w_init_stdev * (1. / math.sqrt(self.n_layers))
if scale_type == "scale_by_in": # Scale by sqrt(num_input_features)
w_init_stdev = w_init_stdev * (1. / math.sqrt(x.shape[-1].size))
return mtf.layers.dense(x, new_dims=[new_dim], reduced_dims=[x.shape[-1]], name=name, use_bias=True,
kernel_initializer=tf.random_normal_initializer(stddev=w_init_stdev),
variable_dtype=self.variable_dtype)
def layer_norm(self, x, name="layer_norm", axis=None, epsilon=1e-5):
"""Normalize to mean = 0, std = 1, then do a diagonal affine transform."""
if axis is None:
axis = x.shape[-1]
with tf.variable_scope(name):
g = mtf.get_variable(x.mesh, "g", [axis], initializer=tf.constant_initializer(1),
master_dtype=self.variable_dtype.master_dtype,
slice_dtype=self.variable_dtype.slice_dtype,
activation_dtype=self.variable_dtype.activation_dtype)
b = mtf.get_variable(x.mesh, "b", [axis], initializer=tf.constant_initializer(0),
master_dtype=self.variable_dtype.master_dtype,
slice_dtype=self.variable_dtype.slice_dtype,
activation_dtype=self.variable_dtype.activation_dtype)
x = norm(x, axis, epsilon)
x = x * g + b
return x
def to_logits(self, x):
with tf.variable_scope("to_logits"):
logits = self.linear(self.layer_norm(x), self.dimensions["final_vocab_dim"], name="linear_out")
# Go to full precision for the logits
return mtf.cast(logits, tf.float32)
def forward(self, features, return_loss=True, return_logits=False):
inputs = features["tokens"]
tokens = self.positional_embedding(self.embedding(inputs, "embedding"), "positional_embedding")
mask = self.get_attn_mask(tokens.mesh, tokens.shape[1], self.dimensions["memory_len_dim"])
out = self.transformer(tokens, mask=mask)
logits = self.to_logits(out)
if not return_loss:
return logits
labels = pad(inputs, [0, 1], dim_name="total_seq_dim", pad_value=self.eos_token_id)
indices = mtf.range(labels.mesh, mtf.Dimension("range", labels.shape[1].size - 1), tf.int32, name="labels_indices") + 1
labels = mtf.gather(labels, indices, dim=labels.shape[1])
labels = mtf.rename_dimension(labels, "range", "total_seq_dim")
loss, loss_batch = self._loss(logits, labels)
if return_logits and return_loss:
# Cast back to checkpoint dtype
logits = mtf.cast(logits, self.variable_dtype.master_dtype)
return loss, loss_batch, logits
return loss, loss_batch
|
DALLE-mtf-main
|
src/dalle_mtf/models.py
|
from .models import DALLE, DiscreteVAE
|
DALLE-mtf-main
|
src/dalle_mtf/__init__.py
|
import mesh_tensorflow as mtf
from mesh_tensorflow.ops import Operation, Dimension, Shape, Tensor, mtf_slice
import tensorflow.compat.v1 as tf
class CustomPadOperation(Operation):
"""tf.pad.
Similar to tf.pad but we only pad along one axis given by pad_dim_name
with values specified by paddings. paddings is a list of two
values, giving the padding value before and after pad_dim.
"""
def __init__(self, x, paddings, pad_dim_name, pad_value=0, name=None):
super(CustomPadOperation, self).__init__([x], name=name or "pad")
assert len(paddings) == 2
input_shape = self._inputs[0].shape
dim_names = [dim.name for dim in x.shape.dims]
if pad_dim_name not in dim_names:
raise ValueError("Padding dim name %s not found in input." % pad_dim_name)
self._paddings = paddings
self._axis = axis = dim_names.index(pad_dim_name)
output_size = input_shape.dims[axis].size + sum(paddings)
self._output_dim = Dimension(pad_dim_name, output_size)
output_shape = Shape(
input_shape.dims[:axis] +
[self._output_dim] + input_shape.dims[axis + 1:])
self._outputs = [Tensor(self, output_shape, x.dtype)]
self._splittable_dims, self._unsplittable_dims = (
self._initialize_splittable_and_unsplittable_dims(
"splittable", [pad_dim_name]))
self.pad_value = pad_value
def gradient(self, grad_ys):
slice_dim_name = self._output_dim.name
slice_size = self._inputs[0].shape.dims[self._axis].size
return [mtf_slice(grad_ys[0], self._paddings[0],
slice_size, slice_dim_name)]
def lower(self, lowering):
mesh_impl = lowering.mesh_impl(self)
if mesh_impl.tensor_dimension_to_mesh_axis(self._output_dim) is not None:
raise ValueError("can't pad along split axis")
inputs = self._inputs[0]
ndims = self._inputs[0].shape.ndims
axis = self._axis
paddings = [[0, 0]] * axis + [self._paddings] + [[0, 0]] * (ndims - axis - 1)
def slicewise_fn(x, paddings):
return tf.pad(x, paddings, constant_values=self.pad_value, name="pad")
y = mesh_impl.slicewise(
slicewise_fn, lowering.tensors[inputs], paddings)
lowering.set_tensor_lowering(self.outputs[0], y)
def pad(x, paddings, dim_name, pad_value=0, name=None):
"""Pad operation.
Args:
x: a Tensor
paddings: list of integers of size 2, padding size before and after for dim.
dim_name: string, name for the padding dim
name: an optional string
pad_value: constant value to pad with
Returns:
a Tensor
"""
return CustomPadOperation(
x, paddings, dim_name, pad_value=pad_value, name=name).outputs[0]
# helpers
def exists(x):
return x is not None
def get_variable_dtype(bf_16=True):
# Trainable variable precision
# Store checkpoints in master type, train in slice type, compute in activation type
if bf_16:
return mtf.VariableDType(master_dtype=tf.bfloat16, slice_dtype=tf.float32, activation_dtype=tf.bfloat16)
else:
return mtf.VariableDType(master_dtype=tf.float32, slice_dtype=tf.float32, activation_dtype=tf.float32)
|
DALLE-mtf-main
|
src/dalle_mtf/ops.py
|
import mesh_tensorflow as mtf
import tensorflow.compat.v1 as tf
def gumbel_softmax(logits, dim, temperature=1, hard=True):
with tf.name_scope(name="gumbel_softmax"):
smol_val = 1e-9
logits = mtf.cast(logits, tf.float32)
g = -mtf.log(-mtf.log(
mtf.random_uniform(
logits.mesh,
logits.shape,
minval=smol_val,
maxval=1.,
dtype=logits.dtype)))
logits += g * temperature
sample = mtf.softmax(logits, dim, name="gumbel_softmax_softmax")
if hard:
sample_hard = mtf.cast(mtf.one_hot(mtf.argmax(sample, dim), dim), sample.dtype)
sample = mtf.stop_gradient(sample_hard - sample) + sample
return sample
def mse_loss(prediction, target):
return mtf.reduce_mean(mtf.square(prediction - target))
def norm(x, axis, epsilon=1e-8):
x -= mtf.reduce_mean(x, reduced_dim=axis, name="norm_reduce_mean_u")
s = mtf.reduce_mean(mtf.square(x), reduced_dim=axis, name="norm_reduce_mean_s")
return x * mtf.rsqrt(s + epsilon)
|
DALLE-mtf-main
|
src/dalle_mtf/layers.py
|
from .utils import *
|
DALLE-mtf-main
|
src/utils/__init__.py
|
import json
from collections import defaultdict
from urllib.parse import urlparse
from shutil import rmtree
import os
import tensorflow.compat.v1 as tf
import tensorflow.compat.v2 as tf2
import mesh_tensorflow as mtf
import logging
import sys
from mesh_tensorflow.ops import Operation, Tensor
def fetch_model_params(model):
model_path = model if model.endswith(".json") else f"./configs/{model}.json"
with open(model_path) as f:
params = json.load(f)
return defaultdict(lambda: None, params)
def yes_or_no(question):
while True:
reply = str(input(question + ' (y/n): ')).lower().strip()
if reply[:1] == 'y':
return True
if reply[:1] == 'n':
return False
def mode_to_str(mode):
if mode == tf.estimator.ModeKeys.PREDICT:
return "predict"
elif mode == tf.estimator.ModeKeys.EVAL:
return "eval"
elif mode == tf.estimator.ModeKeys.TRAIN:
return "train"
else:
raise ValueError(f"Invalid mode {mode}")
def remove_gs_or_filepath(path):
parsed_url = urlparse(path)
if parsed_url.scheme == "gs":
os.system(f"gsutil rm -rf {path}")
return
rmtree(path)
def maybe_remove_gs_or_filepath(path):
if yes_or_no(f"Are you sure you want to remove '{path}' to start afresh?"):
remove_gs_or_filepath(path)
else:
exit()
def get_n_trainable_vars(graph):
"""
Gets number of trainable vars in a MTF model.
:param graph: Mesh-Tensorflow graph
:return: None
"""
total_parameters = 0
for variable in graph.trainable_variables:
shape = variable.shape.dims
variable_parameters = 1
for dim in shape:
variable_parameters *= dim.size
total_parameters += variable_parameters
print(f"\n\nN PARAMS:\n{total_parameters:,}\n\n")
def print_dim_names(graph):
"""
Print names of all Dimensions
:param graph: Mesh-Tensorflow graph
:return: None
"""
all_dim_names = []
for variable in graph.all_variables:
names = variable.shape.dimension_names
all_dim_names.append(names)
# Print all dim names in graph & write to file
all_dim_names = [item for sublist in all_dim_names for item in sublist] # Flatten all dims
unique_dims = list(set(all_dim_names))
print("ALL DIM NAMES:")
for dim_name in unique_dims:
print(dim_name)
print('\n')
def get_graph_info(graph):
"""
Wrapper fn that calculates number of trainable vars in an MTF graph & prints all dim_names to file
:param graph: Mesh-Tensorflow graph
:return: None
"""
get_n_trainable_vars(graph)
print_dim_names(graph)
def create_host_call(model_dir):
"""Construct a host_call writing scalar summaries.
Borrowed from t2t.
Args:
model_dir: String containing path to train
Returns:
(fn, args) Pair to be called by TPUEstimator as the host_call.
"""
graph = tf.get_default_graph()
# A list of (name, lowered tensor) tuples
summaries = graph.get_collection(mtf.utils.SCALAR_SUMMARIES_COLLECTION_KEY)
def maybe_cast(tensor):
# assert tensor.shape.is_compatible_with([]), tensor.name
if tensor.dtype == tf.int64:
return tf.to_int32(tensor)
if tensor.dtype == tf.bfloat16:
return tf.cast(tensor, tf.float32)
return tensor
reshaped_tensors = []
for _, t in summaries:
try:
t = tf.reshape(maybe_cast(t), [1])
except:
pass
reshaped_tensors.append(t)
# When no supported summaries are found, don't create host_call. Otherwise,
# TPU outfeed queue would enqueue global_step while host_call doesn't dequeue
# it, eventually causing hang.
if not reshaped_tensors:
return None
def host_call_fn(global_step, *args):
"""Training host call. Creates scalar summaries for training metrics."""
# This function is executed on the CPU and should not directly reference
# any Tensors in the rest of the `model_fn`. To pass Tensors from the
# model to the `model_fn`, provide as part of the `host_call`.
global_step = tf.cast(global_step[0], tf.int64)
with tf2.summary.create_file_writer(model_dir).as_default():
# We cannot directly use any tensor from summaries, because each
# tensor here must be a concat of multiple tensors from all shards.
# Therefore, we rely on the assumption that args wil have the same
# length as summaries, and all tensors in args will have the same
# order of self._tup_summaries.
assert len(args) == len(summaries)
for i, tensor in enumerate(args):
name = summaries[i][0]
if not "image" in name:
tf2.summary.scalar(name, tf.reduce_mean(tensor), step=global_step)
else:
tf2.summary.image(name, tensor, step=global_step)
return tf.summary.all_v2_summary_ops()
global_step_t = tf.reshape(tf.to_int32(tf.train.get_global_step()), [1])
return host_call_fn, [global_step_t] + reshaped_tensors
def simd_mesh_setup(params, mesh_shape, layout_rules):
"""Constructs SimdMesh function - instructions on how to evenly split tensors across all TPU cores"""
num_hosts = params["context"].num_hosts
host_placement_fn = params["context"].tpu_host_placement_function
device_list = [host_placement_fn(host_id=i) for i in range(num_hosts)]
tf.logging.info(f"device_list = {device_list}")
# TODO: Better estimation of replica cache size?
replica_cache_size = 300 * 1000000 # 300M per replica
# Worker 0 caches all the TPU binaries
worker0_mem = replica_cache_size * params["context"].num_replicas
devices_memory_usage = [worker0_mem] + [0] * (num_hosts - 1)
var_placer = mtf.utils.BalancedVariablePlacer(device_list, devices_memory_usage)
mesh_devices = [""] * mesh_shape.size
mesh_impl = mtf.simd_mesh_impl.SimdMeshImpl(
mesh_shape, layout_rules, mesh_devices, params["context"].device_assignment)
return var_placer, mesh_impl
def setup_logging(args, logdir="logs"):
os.makedirs(logdir, exist_ok=True)
tf.logging.set_verbosity(logging.INFO)
tf.get_logger().propagate = False # Remove double log on console
name = os.path.splitext(os.path.basename(args.model))[0]
handlers = [
logging.FileHandler(f"logs/{name}.log"),
logging.StreamHandler(sys.stdout)
]
logger = logging.getLogger("tensorflow")
logger.handlers = handlers
return logger
class ScalarSummaryOperation(Operation):
"""Similar to tf.Print."""
def __init__(self, name, x):
super(ScalarSummaryOperation, self).__init__(
[x], x.mesh, name=name)
self._outputs = [Tensor(self, x.shape, x.dtype)]
def lower(self, lowering):
lowered_input = lowering.tensors[self.inputs[0]].to_laid_out_tensor()
tf.add_to_collection(mtf.utils.SCALAR_SUMMARIES_COLLECTION_KEY,
(self.name, lowered_input.tensor_list[0]))
lowering.set_tensor_lowering(
self.outputs[0], lowered_input)
def gradient(self, grad_ys):
return grad_ys
def scalar_summary(name, x):
"""Call tf.summary.scalar.
Caveat - summaries do not generally work on TPU - they need to be rewritten
into a host call.
TODO(noam): provide a pointer to code for this.
Args:
name: a string
x: a 0-dimensional Tensor
Returns:
a Tensor which is identical in value to x
"""
return ScalarSummaryOperation(name, x)
|
DALLE-mtf-main
|
src/utils/utils.py
|
import math
import tensorflow.compat.v1 as tf
from .layers import gumbel_softmax, mse_loss
# hacked up recompute grad which handles variable scopes properly and to handle bf16
def recompute_grad(f, bf16=False):
@tf.custom_gradient
def inner(*args, **kwargs):
result = tf.stop_gradient(f(*args, **kwargs))
scope = tf.get_default_graph().get_name_scope()
def grad(dresult, variables=None):
with tf.GradientTape() as t:
t.watch(args)
if variables is not None:
t.watch(variables)
# we need to outsmart XLA here to force a control dependency
zero_with_control_dependency = tf.reduce_mean(dresult[0] * 1e-30)
new_args = []
for a in args:
if a.dtype.is_floating:
new_args.append(a + tf.cast(zero_with_control_dependency, a.dtype))
else:
new_args.append(a)
with tf.control_dependencies([dresult]):
if bf16:
with tf.tpu.bfloat16_scope():
with tf.variable_scope(scope, reuse=True):
result = f(*new_args, **kwargs)
else:
with tf.variable_scope(scope, reuse=True):
result = f(*new_args, **kwargs)
kw_vars = []
if variables is not None:
kw_vars = list(variables)
grads = t.gradient(result, list(new_args) + kw_vars, output_gradients=[dresult])
return grads[:len(new_args)], grads[len(new_args):]
return result, grad
return inner
class DiscreteVAE:
def __init__(self,
num_tokens,
dimensions,
convblocks,
dim=512,
hidden_dim=64,
input_channels=3,
recompute_grad=False,
use_bf16=False,
stack_factor=1,
):
self.num_tokens = num_tokens
self.dim = dim
self.hdim = hidden_dim
self.hdim2 = hidden_dim
self.num_tokens = num_tokens
self.num_ch = input_channels
self.H = self.W = dimensions
self.height_dim = self.H
self.width_dim = self.W
self.conv2d = tf.layers.conv2d
self.conv2dtranspose = tf.layers.conv2d_transpose
self.activation = tf.nn.relu
self.dense = tf.layers.dense
self.norm = tf.layers.batch_normalization
# list of (stacked, channels) with implicit stride 2, conv between groups
self.convblocks = convblocks
self.recompute_grad = recompute_grad
self.bf16 = use_bf16
assert math.log2(stack_factor).is_integer() # maybe you don't actually need this?
self.stack_factor = stack_factor
def encoder(self, x):
if self.bf16:
x = tf.cast(x, tf.bfloat16)
if self.stack_factor > 1:
x = tf.space_to_depth(x, self.stack_factor)
with tf.variable_scope("encoder"):
for block, (stack, channels) in enumerate(self.convblocks):
with tf.variable_scope(f"block_{block}"):
for i in range(stack):
with tf.variable_scope(f"layer_{i}"):
if i == 0:
# downsample
x = self.conv2d(x, channels, (4, 4), (2, 2), padding="SAME", name=f"conv_downsample")
else:
# normal residual block
def encoder_block(x, channels=channels):
out = self.conv2d(x, channels, (3, 3), (1, 1), padding="SAME", name=f"conv_in")
# out = self.norm(out, name=f"bn_in")
out = self.activation(out, name=f"activ")
out = self.conv2d(out, channels, (3, 3), (1, 1), padding="SAME", name=f"conv_out")
# out = self.norm(out, name=f"bn_out")
return out
res_out = recompute_grad(encoder_block, self.bf16)(x) if self.recompute_grad else encoder_block(x)
x = x + res_out
with tf.variable_scope(f"codebook"):
self.n_hid = x.shape[-1]
embedding = tf.get_variable("codebook", shape=[self.n_hid, self.num_tokens], dtype=tf.float32)
if self.bf16:
x = tf.cast(x, tf.float32)
output = tf.matmul(x, embedding)
return output
def decoder(self, x):
with tf.variable_scope(f"codebook", reuse=True):
embedding = tf.get_variable("codebook", shape=[self.n_hid, self.num_tokens], dtype=tf.float32)
x = tf.matmul(x, embedding, transpose_b=True)
if self.bf16:
x = tf.cast(x, tf.bfloat16)
with tf.variable_scope("decoder"):
for block, (stack, channels) in enumerate(reversed(self.convblocks)):
with tf.variable_scope(f"block_{block}"):
for i in range(stack):
with tf.variable_scope(f"layer_{i}"):
if i == 0:
# upsample
x = self.conv2dtranspose(x, channels, (4, 4), (2, 2), padding="SAME", name=f"conv_upsample")
else:
# normal residual block
def decoder_block(x, channels=channels):
out = self.conv2d(x, channels, (3, 3), (1, 1), padding="SAME", name=f"conv_in")
# out = self.norm(out, name=f"bn_in")
out = self.activation(out, name=f"activ")
out = self.conv2d(out, channels, (3, 3), (1, 1), padding="SAME", name=f"conv_out")
# out = self.norm(out, name=f"bn_out")
return out
res_out = recompute_grad(decoder_block, self.bf16)(x) if self.recompute_grad else decoder_block(x)
x = x + res_out
x = self.conv2d(x, self.num_ch * self.stack_factor ** 2, (1, 1), (1, 1))
if self.bf16:
x = tf.cast(x, tf.float32)
if self.stack_factor > 1:
x = tf.depth_to_space(x, self.stack_factor)
return x
def forward(self, features, return_recon_loss=False, return_logits=False, hard_gumbel=True, temperature=1.):
if isinstance(features, dict):
img = features["inputs"]
else:
img = features
# NHWC
logits = self.encoder(img)
if return_logits:
return logits # return logits for getting hard image indices for DALL-E training
soft_one_hot = gumbel_softmax(logits, -1, temperature=temperature, hard=hard_gumbel)
out = self.decoder(soft_one_hot)
if not return_recon_loss:
return out
loss = mse_loss(tf.cast(img, out.dtype), out)
return loss, out
|
DALLE-mtf-main
|
src/vae_tf/models.py
|
from .models import DiscreteVAE
|
DALLE-mtf-main
|
src/vae_tf/__init__.py
|
import mesh_tensorflow as mtf
from mesh_tensorflow.ops import Operation, Dimension, Shape, Tensor, mtf_slice
import tensorflow.compat.v1 as tf
class CustomPadOperation(Operation):
"""tf.pad.
Similar to tf.pad but we only pad along one axis given by pad_dim_name
with values specified by paddings. paddings is a list of two
values, giving the padding value before and after pad_dim.
"""
def __init__(self, x, paddings, pad_dim_name, pad_value=0, name=None):
super(CustomPadOperation, self).__init__([x], name=name or "pad")
assert len(paddings) == 2
input_shape = self._inputs[0].shape
dim_names = [dim.name for dim in x.shape.dims]
if pad_dim_name not in dim_names:
raise ValueError("Padding dim name %s not found in input." % pad_dim_name)
self._paddings = paddings
self._axis = axis = dim_names.index(pad_dim_name)
output_size = input_shape.dims[axis].size + sum(paddings)
self._output_dim = Dimension(pad_dim_name, output_size)
output_shape = Shape(
input_shape.dims[:axis] +
[self._output_dim] + input_shape.dims[axis + 1:])
self._outputs = [Tensor(self, output_shape, x.dtype)]
self._splittable_dims, self._unsplittable_dims = (
self._initialize_splittable_and_unsplittable_dims(
"splittable", [pad_dim_name]))
self.pad_value = pad_value
def gradient(self, grad_ys):
slice_dim_name = self._output_dim.name
slice_size = self._inputs[0].shape.dims[self._axis].size
return [mtf_slice(grad_ys[0], self._paddings[0],
slice_size, slice_dim_name)]
def lower(self, lowering):
mesh_impl = lowering.mesh_impl(self)
if mesh_impl.tensor_dimension_to_mesh_axis(self._output_dim) is not None:
raise ValueError("can't pad along split axis")
inputs = self._inputs[0]
ndims = self._inputs[0].shape.ndims
axis = self._axis
paddings = [[0, 0]] * axis + [self._paddings] + [[0, 0]] * (ndims - axis - 1)
def slicewise_fn(x, paddings):
return tf.pad(x, paddings, constant_values=self.pad_value, name="pad")
y = mesh_impl.slicewise(
slicewise_fn, lowering.tensors[inputs], paddings)
lowering.set_tensor_lowering(self.outputs[0], y)
def pad(x, paddings, dim_name, pad_value=0, name=None):
"""Pad operation.
Args:
x: a Tensor
paddings: list of integers of size 2, padding size before and after for dim.
dim_name: string, name for the padding dim
name: an optional string
pad_value: constant value to pad with
Returns:
a Tensor
"""
return CustomPadOperation(
x, paddings, dim_name, pad_value=pad_value, name=name).outputs[0]
# helpers
def exists(x):
return x is not None
def get_variable_dtype(bf_16=True):
# Trainable variable precision
# Store checkpoints in master type, train in slice type, compute in activation type
if bf_16:
return mtf.VariableDType(master_dtype=tf.bfloat16, slice_dtype=tf.float32, activation_dtype=tf.bfloat16)
else:
return mtf.VariableDType(master_dtype=tf.float32, slice_dtype=tf.float32, activation_dtype=tf.float32)
|
DALLE-mtf-main
|
src/vae_tf/ops.py
|
import tensorflow.compat.v1 as tf
def gumbel_softmax(logits, axis, temperature=1, hard=True):
with tf.name_scope(name="gumbel_softmax"):
smol_val = 1e-9
logits = tf.cast(logits, tf.float32)
g = -tf.log(-tf.log(
tf.random_uniform(
logits.shape,
minval=smol_val,
maxval=1.,
dtype=logits.dtype)))
logits += g
sample = tf.nn.softmax(logits/temperature, axis, name="gumbel_softmax_softmax")
if hard:
sample_hard = tf.cast(tf.one_hot(tf.argmax(sample, axis), sample.shape[axis], axis=axis), sample.dtype)
sample = tf.stop_gradient(sample_hard - sample) + sample
return sample
def mse_loss(prediction, target):
return tf.reduce_mean(tf.square(prediction - target))
|
DALLE-mtf-main
|
src/vae_tf/layers.py
|
from transformers import GPT2TokenizerFast, GPT2Tokenizer
def get_tokenizer(tokenizer_type=None, from_pretrained=True, add_padding_token=True):
if tokenizer_type is None or (tokenizer_type.lower() == "hf_gpt2tokenizerfast" and from_pretrained):
tok = GPT2TokenizerFast.from_pretrained('gpt2')
if add_padding_token:
tok.add_special_tokens({'pad_token': '<|padding|>'})
return tok
elif tokenizer_type.lower() == "hf_gp2tokenizer" and from_pretrained:
tok = GPT2Tokenizer.from_pretrained('gpt2')
if add_padding_token:
tok.add_special_tokens({'pad_token': '<|padding|>'})
return tok
else:
raise NotImplementedError('TODO: add custom tokenizers')
|
DALLE-mtf-main
|
src/data/tokenizer_utils.py
|
import tensorflow.compat.v1 as tf
try:
from .tokenizer_utils import get_tokenizer
except ImportError:
from tokenizer_utils import get_tokenizer
import json
from pathlib import PurePath, Path
import cv2
from tqdm import tqdm
import glob
import random
import os
import shutil
def dump_jsonl(data, output_path, append=False):
"""
Write list of objects to a JSON lines file.
"""
mode = 'a+' if append else 'w'
with open(output_path, mode, encoding='utf-8') as f:
for line in data:
json_record = json.dumps(line, ensure_ascii=False)
f.write(json_record + '\n')
def load_jsonl(input_path):
"""
Read list of objects from a JSON lines file.
"""
data = []
with open(input_path, 'r', encoding='utf-8') as f:
for line in f:
data.append(json.loads(line.rstrip('\n|\r')))
return data
def _bytes_feature(value):
"""Returns a bytes_list from a string / byte."""
if isinstance(value, type(tf.constant(0))):
value = value.numpy() # BytesList won't unpack a string from an EagerTensor.
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def _int64_feature(value):
"""Returns an int64_list from a bool / enum / int / uint."""
return tf.train.Feature(int64_list=tf.train.Int64List(value=value))
def serialize_example(image, caption):
feature = {
'image': _bytes_feature(image),
'caption': _int64_feature(caption),
}
example_proto = tf.train.Example(features=tf.train.Features(feature=feature))
return example_proto.SerializeToString()
def create_random_dataset(path_to_images, out_dir, max_images_per_folder=1000, words_per_caption=50):
"""
creates a paired image / text folder with random captions in the correct format to feed to
create_paired_tfrecord_dataset (for testing)
Args:
out_dir: str
path_to_images: str
glob path to images
max_images_per_folder: int
words_per_caption: int
"""
import requests
word_site = "https://www.mit.edu/~ecprice/wordlist.10000"
response = requests.get(word_site)
WORDS = response.content.splitlines()
out_dir = Path(out_dir)
jsonl_path = out_dir / "captions_data.jsonl"
os.makedirs(out_dir, exist_ok=True)
images = glob.glob(path_to_images)
print(f"{len(images)} images found")
pbar = tqdm()
folder_count = 0
for i, image in enumerate(images):
if i % 100 == 0 or i == 0:
pbar.update(100)
if i % max_images_per_folder == 0 or i == 0:
sub_folder = Path(out_dir) / str(folder_count)
os.makedirs(Path(out_dir) / str(folder_count), exist_ok=True)
folder_count += 1
data = {}
image = Path(image)
data["caption"] = " ".join([random.choice(WORDS).decode() for i in range(words_per_caption)])
data["image_path"] = str(sub_folder.relative_to(out_dir) / image.name)
shutil.copy(image, sub_folder)
dump_jsonl([data], jsonl_path, append=True)
def create_paired_dataset(path_to_jsonl, name, out_dir, examples_per_tfrecord=1000, tokenizer=None, reencode=False):
"""
takes in a jsonl with relative paths to images & captions, and saves tfrecords files with num_examples
examples to out_dir.
Folder structure:
data_folder
jsonl_file
folder_1
img1
img2
...
folder_2
img1
img2
...
...
Jsonl structure:
{"image_path": relative_image_path, "caption": caption}
{"image_path": relative_image_path, "caption": caption}
...
TODO: multiprocessing
Args:
path_to_jsonl: str / path / list of str / path
path to jsonl file
examples_per_tfrecord: int
number of examples to write to each tfrecords file
name: str
name of tfrecords files
out_dir: str / path
path to folder in which to save tfrecords
tokenizer: custom HF tokenizer
if None, defaults to GPT2TokenizerFast
"""
if tokenizer is None:
tokenizer = get_tokenizer()
if isinstance(out_dir, str):
out_dir = Path(out_dir)
os.makedirs(out_dir, exist_ok=True)
if isinstance(path_to_jsonl, PurePath) or isinstance(path_to_jsonl, str):
path_to_jsonl = [path_to_jsonl]
if not isinstance(path_to_jsonl, list):
raise TypeError(f"path_to_jsonl type not recognized, should be str, path, or list")
tfrecord_count = 0
example_count = 0
writer = tf.io.TFRecordWriter(str(out_dir / f"{name}_{tfrecord_count}.tfrecords"))
pbar = tqdm()
for path in path_to_jsonl:
path = Path(path)
data = load_jsonl(path)
for item in data:
if example_count % examples_per_tfrecord == 0 and example_count != 0:
writer.close()
writer = tf.io.TFRecordWriter(str(out_dir / f"{name}_{tfrecord_count}.tfrecords"))
tfrecord_count += 1
image_path = path.parent / item["image_path"]
if reencode:
img = cv2.imread(str(image_path))
img = cv2.imencode('.jpg', img, (cv2.IMWRITE_JPEG_QUALITY, 94))[1].tostring() # encodes image to string
else:
img = open(image_path, "rb").read()
caption = tokenizer.encode(item["caption"][0])
example = serialize_example(img, caption)
writer.write(example)
example_count += 1
if example_count % 100 == 0:
pbar.set_description(f"{example_count} examples written to {tfrecord_count + 1} files")
pbar.update(100)
writer.close()
if __name__ == "__main__":
# creates random test dataset with CIFAR 10
create_paired_dataset("/home/data/coco/coco_captions.jsonl", "COCO", "DALLE-tfrecords", examples_per_tfrecord=1000,
tokenizer=None)
|
DALLE-mtf-main
|
src/data/create_tfrecords.py
|
from .tokenizer_utils import get_tokenizer
|
DALLE-mtf-main
|
src/data/__init__.py
|
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# This work is licensed under the Creative Commons Attribution-NonCommercial
# 4.0 International License. To view a copy of this license, visit
# http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to
# Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
"""Tool for creating multi-resolution TFRecords datasets for StyleGAN and ProGAN."""
# pylint: disable=too-many-lines
import os
import sys
import glob
import argparse
import threading
import six.moves.queue as Queue # pylint: disable=import-error
import traceback
import numpy as np
import tensorflow as tf
import PIL.Image
import dnnlib.tflib as tflib
from training import dataset
#----------------------------------------------------------------------------
def error(msg):
print('Error: ' + msg)
exit(1)
#----------------------------------------------------------------------------
class TFRecordExporter:
def __init__(self, tfrecord_dir, expected_images, print_progress=True, progress_interval=10):
self.tfrecord_dir = tfrecord_dir
self.tfr_prefix = os.path.join(self.tfrecord_dir, os.path.basename(self.tfrecord_dir))
self.expected_images = expected_images
self.cur_images = 0
self.shape = None
self.resolution_log2 = None
self.tfr_writers = []
self.print_progress = print_progress
self.progress_interval = progress_interval
if self.print_progress:
print('Creating dataset "%s"' % tfrecord_dir)
if not os.path.isdir(self.tfrecord_dir):
os.makedirs(self.tfrecord_dir)
assert os.path.isdir(self.tfrecord_dir)
def close(self):
if self.print_progress:
print('%-40s\r' % 'Flushing data...', end='', flush=True)
for tfr_writer in self.tfr_writers:
tfr_writer.close()
self.tfr_writers = []
if self.print_progress:
print('%-40s\r' % '', end='', flush=True)
print('Added %d images.' % self.cur_images)
def choose_shuffled_order(self): # Note: Images and labels must be added in shuffled order.
order = np.arange(self.expected_images)
np.random.RandomState(123).shuffle(order)
return order
def add_image(self, img):
if self.print_progress and self.cur_images % self.progress_interval == 0:
print('%d / %d\r' % (self.cur_images, self.expected_images), end='', flush=True)
if self.shape is None:
self.shape = img.shape
self.resolution_log2 = int(np.log2(self.shape[1]))
assert self.shape[0] in [1, 3]
assert self.shape[1] == self.shape[2]
assert self.shape[1] == 2**self.resolution_log2
tfr_opt = tf.python_io.TFRecordOptions(tf.python_io.TFRecordCompressionType.NONE)
for lod in range(self.resolution_log2 - 1):
tfr_file = self.tfr_prefix + '-r%02d.tfrecords' % (self.resolution_log2 - lod)
self.tfr_writers.append(tf.python_io.TFRecordWriter(tfr_file, tfr_opt))
assert img.shape == self.shape
for lod, tfr_writer in enumerate(self.tfr_writers):
if lod:
img = img.astype(np.float32)
img = (img[:, 0::2, 0::2] + img[:, 0::2, 1::2] + img[:, 1::2, 0::2] + img[:, 1::2, 1::2]) * 0.25
quant = np.rint(img).clip(0, 255).astype(np.uint8)
ex = tf.train.Example(features=tf.train.Features(feature={
'shape': tf.train.Feature(int64_list=tf.train.Int64List(value=quant.shape)),
'data': tf.train.Feature(bytes_list=tf.train.BytesList(value=[quant.tostring()]))}))
tfr_writer.write(ex.SerializeToString())
self.cur_images += 1
def add_labels(self, labels):
if self.print_progress:
print('%-40s\r' % 'Saving labels...', end='', flush=True)
assert labels.shape[0] == self.cur_images
with open(self.tfr_prefix + '-rxx.labels', 'wb') as f:
np.save(f, labels.astype(np.float32))
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
#----------------------------------------------------------------------------
class ExceptionInfo(object):
def __init__(self):
self.value = sys.exc_info()[1]
self.traceback = traceback.format_exc()
#----------------------------------------------------------------------------
class WorkerThread(threading.Thread):
def __init__(self, task_queue):
threading.Thread.__init__(self)
self.task_queue = task_queue
def run(self):
while True:
func, args, result_queue = self.task_queue.get()
if func is None:
break
try:
result = func(*args)
except:
result = ExceptionInfo()
result_queue.put((result, args))
#----------------------------------------------------------------------------
class ThreadPool(object):
def __init__(self, num_threads):
assert num_threads >= 1
self.task_queue = Queue.Queue()
self.result_queues = dict()
self.num_threads = num_threads
for _idx in range(self.num_threads):
thread = WorkerThread(self.task_queue)
thread.daemon = True
thread.start()
def add_task(self, func, args=()):
assert hasattr(func, '__call__') # must be a function
if func not in self.result_queues:
self.result_queues[func] = Queue.Queue()
self.task_queue.put((func, args, self.result_queues[func]))
def get_result(self, func): # returns (result, args)
result, args = self.result_queues[func].get()
if isinstance(result, ExceptionInfo):
print('\n\nWorker thread caught an exception:\n' + result.traceback)
raise result.value
return result, args
def finish(self):
for _idx in range(self.num_threads):
self.task_queue.put((None, (), None))
def __enter__(self): # for 'with' statement
return self
def __exit__(self, *excinfo):
self.finish()
def process_items_concurrently(self, item_iterator, process_func=lambda x: x, pre_func=lambda x: x, post_func=lambda x: x, max_items_in_flight=None):
if max_items_in_flight is None: max_items_in_flight = self.num_threads * 4
assert max_items_in_flight >= 1
results = []
retire_idx = [0]
def task_func(prepared, _idx):
return process_func(prepared)
def retire_result():
processed, (_prepared, idx) = self.get_result(task_func)
results[idx] = processed
while retire_idx[0] < len(results) and results[retire_idx[0]] is not None:
yield post_func(results[retire_idx[0]])
results[retire_idx[0]] = None
retire_idx[0] += 1
for idx, item in enumerate(item_iterator):
prepared = pre_func(item)
results.append(None)
self.add_task(func=task_func, args=(prepared, idx))
while retire_idx[0] < idx - max_items_in_flight + 2:
for res in retire_result(): yield res
while retire_idx[0] < len(results):
for res in retire_result(): yield res
#----------------------------------------------------------------------------
def display(tfrecord_dir):
print('Loading dataset "%s"' % tfrecord_dir)
tflib.init_tf({'gpu_options.allow_growth': True})
dset = dataset.TFRecordDataset(tfrecord_dir, max_label_size='full', repeat=False, shuffle_mb=0)
tflib.init_uninitialized_vars()
import cv2 # pip install opencv-python
idx = 0
while True:
try:
images, labels = dset.get_minibatch_np(1)
except tf.errors.OutOfRangeError:
break
if idx == 0:
print('Displaying images')
cv2.namedWindow('dataset_tool')
print('Press SPACE or ENTER to advance, ESC to exit')
print('\nidx = %-8d\nlabel = %s' % (idx, labels[0].tolist()))
cv2.imshow('dataset_tool', images[0].transpose(1, 2, 0)[:, :, ::-1]) # CHW => HWC, RGB => BGR
idx += 1
if cv2.waitKey() == 27:
break
print('\nDisplayed %d images.' % idx)
#----------------------------------------------------------------------------
def extract(tfrecord_dir, output_dir):
print('Loading dataset "%s"' % tfrecord_dir)
tflib.init_tf({'gpu_options.allow_growth': True})
dset = dataset.TFRecordDataset(tfrecord_dir, max_label_size=0, repeat=False, shuffle_mb=0)
tflib.init_uninitialized_vars()
print('Extracting images to "%s"' % output_dir)
if not os.path.isdir(output_dir):
os.makedirs(output_dir)
idx = 0
while True:
if idx % 10 == 0:
print('%d\r' % idx, end='', flush=True)
try:
images, _labels = dset.get_minibatch_np(1)
except tf.errors.OutOfRangeError:
break
if images.shape[1] == 1:
img = PIL.Image.fromarray(images[0][0], 'L')
else:
img = PIL.Image.fromarray(images[0].transpose(1, 2, 0), 'RGB')
img.save(os.path.join(output_dir, 'img%08d.png' % idx))
idx += 1
print('Extracted %d images.' % idx)
#----------------------------------------------------------------------------
def compare(tfrecord_dir_a, tfrecord_dir_b, ignore_labels):
max_label_size = 0 if ignore_labels else 'full'
print('Loading dataset "%s"' % tfrecord_dir_a)
tflib.init_tf({'gpu_options.allow_growth': True})
dset_a = dataset.TFRecordDataset(tfrecord_dir_a, max_label_size=max_label_size, repeat=False, shuffle_mb=0)
print('Loading dataset "%s"' % tfrecord_dir_b)
dset_b = dataset.TFRecordDataset(tfrecord_dir_b, max_label_size=max_label_size, repeat=False, shuffle_mb=0)
tflib.init_uninitialized_vars()
print('Comparing datasets')
idx = 0
identical_images = 0
identical_labels = 0
while True:
if idx % 100 == 0:
print('%d\r' % idx, end='', flush=True)
try:
images_a, labels_a = dset_a.get_minibatch_np(1)
except tf.errors.OutOfRangeError:
images_a, labels_a = None, None
try:
images_b, labels_b = dset_b.get_minibatch_np(1)
except tf.errors.OutOfRangeError:
images_b, labels_b = None, None
if images_a is None or images_b is None:
if images_a is not None or images_b is not None:
print('Datasets contain different number of images')
break
if images_a.shape == images_b.shape and np.all(images_a == images_b):
identical_images += 1
else:
print('Image %d is different' % idx)
if labels_a.shape == labels_b.shape and np.all(labels_a == labels_b):
identical_labels += 1
else:
print('Label %d is different' % idx)
idx += 1
print('Identical images: %d / %d' % (identical_images, idx))
if not ignore_labels:
print('Identical labels: %d / %d' % (identical_labels, idx))
#----------------------------------------------------------------------------
def create_mnist(tfrecord_dir, mnist_dir):
print('Loading MNIST from "%s"' % mnist_dir)
import gzip
with gzip.open(os.path.join(mnist_dir, 'train-images-idx3-ubyte.gz'), 'rb') as file:
images = np.frombuffer(file.read(), np.uint8, offset=16)
with gzip.open(os.path.join(mnist_dir, 'train-labels-idx1-ubyte.gz'), 'rb') as file:
labels = np.frombuffer(file.read(), np.uint8, offset=8)
images = images.reshape(-1, 1, 28, 28)
images = np.pad(images, [(0,0), (0,0), (2,2), (2,2)], 'constant', constant_values=0)
assert images.shape == (60000, 1, 32, 32) and images.dtype == np.uint8
assert labels.shape == (60000,) and labels.dtype == np.uint8
assert np.min(images) == 0 and np.max(images) == 255
assert np.min(labels) == 0 and np.max(labels) == 9
onehot = np.zeros((labels.size, np.max(labels) + 1), dtype=np.float32)
onehot[np.arange(labels.size), labels] = 1.0
with TFRecordExporter(tfrecord_dir, images.shape[0]) as tfr:
order = tfr.choose_shuffled_order()
for idx in range(order.size):
tfr.add_image(images[order[idx]])
tfr.add_labels(onehot[order])
#----------------------------------------------------------------------------
def create_mnistrgb(tfrecord_dir, mnist_dir, num_images=1000000, random_seed=123):
print('Loading MNIST from "%s"' % mnist_dir)
import gzip
with gzip.open(os.path.join(mnist_dir, 'train-images-idx3-ubyte.gz'), 'rb') as file:
images = np.frombuffer(file.read(), np.uint8, offset=16)
images = images.reshape(-1, 28, 28)
images = np.pad(images, [(0,0), (2,2), (2,2)], 'constant', constant_values=0)
assert images.shape == (60000, 32, 32) and images.dtype == np.uint8
assert np.min(images) == 0 and np.max(images) == 255
with TFRecordExporter(tfrecord_dir, num_images) as tfr:
rnd = np.random.RandomState(random_seed)
for _idx in range(num_images):
tfr.add_image(images[rnd.randint(images.shape[0], size=3)])
#----------------------------------------------------------------------------
def create_cifar10(tfrecord_dir, cifar10_dir):
print('Loading CIFAR-10 from "%s"' % cifar10_dir)
import pickle
images = []
labels = []
for batch in range(1, 6):
with open(os.path.join(cifar10_dir, 'data_batch_%d' % batch), 'rb') as file:
data = pickle.load(file, encoding='latin1')
images.append(data['data'].reshape(-1, 3, 32, 32))
labels.append(data['labels'])
images = np.concatenate(images)
labels = np.concatenate(labels)
assert images.shape == (50000, 3, 32, 32) and images.dtype == np.uint8
assert labels.shape == (50000,)
assert np.min(images) == 0 and np.max(images) == 255
assert np.min(labels) == 0 and np.max(labels) == 9
onehot = np.zeros((labels.size, np.max(labels) + 1), dtype=np.float32)
onehot[np.arange(labels.size), labels] = 1.0
with TFRecordExporter(tfrecord_dir, images.shape[0]) as tfr:
order = tfr.choose_shuffled_order()
for idx in range(order.size):
tfr.add_image(images[order[idx]])
tfr.add_labels(onehot[order])
#----------------------------------------------------------------------------
def create_cifar100(tfrecord_dir, cifar100_dir):
print('Loading CIFAR-100 from "%s"' % cifar100_dir)
import pickle
with open(os.path.join(cifar100_dir, 'train'), 'rb') as file:
data = pickle.load(file, encoding='latin1')
images = data['data'].reshape(-1, 3, 32, 32)
labels = np.array(data['fine_labels'])
assert images.shape == (50000, 3, 32, 32) and images.dtype == np.uint8
assert labels.shape == (50000,)
assert np.min(images) == 0 and np.max(images) == 255
assert np.min(labels) == 0 and np.max(labels) == 99
onehot = np.zeros((labels.size, np.max(labels) + 1), dtype=np.float32)
onehot[np.arange(labels.size), labels] = 1.0
with TFRecordExporter(tfrecord_dir, images.shape[0]) as tfr:
order = tfr.choose_shuffled_order()
for idx in range(order.size):
tfr.add_image(images[order[idx]])
tfr.add_labels(onehot[order])
#----------------------------------------------------------------------------
def create_svhn(tfrecord_dir, svhn_dir):
print('Loading SVHN from "%s"' % svhn_dir)
import pickle
images = []
labels = []
for batch in range(1, 4):
with open(os.path.join(svhn_dir, 'train_%d.pkl' % batch), 'rb') as file:
data = pickle.load(file, encoding='latin1')
images.append(data[0])
labels.append(data[1])
images = np.concatenate(images)
labels = np.concatenate(labels)
assert images.shape == (73257, 3, 32, 32) and images.dtype == np.uint8
assert labels.shape == (73257,) and labels.dtype == np.uint8
assert np.min(images) == 0 and np.max(images) == 255
assert np.min(labels) == 0 and np.max(labels) == 9
onehot = np.zeros((labels.size, np.max(labels) + 1), dtype=np.float32)
onehot[np.arange(labels.size), labels] = 1.0
with TFRecordExporter(tfrecord_dir, images.shape[0]) as tfr:
order = tfr.choose_shuffled_order()
for idx in range(order.size):
tfr.add_image(images[order[idx]])
tfr.add_labels(onehot[order])
#----------------------------------------------------------------------------
def create_lsun(tfrecord_dir, lmdb_dir, resolution=256, max_images=None):
print('Loading LSUN dataset from "%s"' % lmdb_dir)
import lmdb # pip install lmdb # pylint: disable=import-error
import cv2 # pip install opencv-python
import io
with lmdb.open(lmdb_dir, readonly=True).begin(write=False) as txn:
total_images = txn.stat()['entries'] # pylint: disable=no-value-for-parameter
if max_images is None:
max_images = total_images
with TFRecordExporter(tfrecord_dir, max_images) as tfr:
for _idx, (_key, value) in enumerate(txn.cursor()):
try:
try:
img = cv2.imdecode(np.fromstring(value, dtype=np.uint8), 1)
if img is None:
raise IOError('cv2.imdecode failed')
img = img[:, :, ::-1] # BGR => RGB
except IOError:
img = np.asarray(PIL.Image.open(io.BytesIO(value)))
crop = np.min(img.shape[:2])
img = img[(img.shape[0] - crop) // 2 : (img.shape[0] + crop) // 2, (img.shape[1] - crop) // 2 : (img.shape[1] + crop) // 2]
img = PIL.Image.fromarray(img, 'RGB')
img = img.resize((resolution, resolution), PIL.Image.ANTIALIAS)
img = np.asarray(img)
img = img.transpose([2, 0, 1]) # HWC => CHW
tfr.add_image(img)
except:
print(sys.exc_info()[1])
if tfr.cur_images == max_images:
break
#----------------------------------------------------------------------------
def create_lsun_wide(tfrecord_dir, lmdb_dir, width=512, height=384, max_images=None):
assert width == 2 ** int(np.round(np.log2(width)))
assert height <= width
print('Loading LSUN dataset from "%s"' % lmdb_dir)
import lmdb # pip install lmdb # pylint: disable=import-error
import cv2 # pip install opencv-python
import io
with lmdb.open(lmdb_dir, readonly=True).begin(write=False) as txn:
total_images = txn.stat()['entries'] # pylint: disable=no-value-for-parameter
if max_images is None:
max_images = total_images
with TFRecordExporter(tfrecord_dir, max_images, print_progress=False) as tfr:
for idx, (_key, value) in enumerate(txn.cursor()):
try:
try:
img = cv2.imdecode(np.fromstring(value, dtype=np.uint8), 1)
if img is None:
raise IOError('cv2.imdecode failed')
img = img[:, :, ::-1] # BGR => RGB
except IOError:
img = np.asarray(PIL.Image.open(io.BytesIO(value)))
ch = int(np.round(width * img.shape[0] / img.shape[1]))
if img.shape[1] < width or ch < height:
continue
img = img[(img.shape[0] - ch) // 2 : (img.shape[0] + ch) // 2]
img = PIL.Image.fromarray(img, 'RGB')
img = img.resize((width, height), PIL.Image.ANTIALIAS)
img = np.asarray(img)
img = img.transpose([2, 0, 1]) # HWC => CHW
canvas = np.zeros([3, width, width], dtype=np.uint8)
canvas[:, (width - height) // 2 : (width + height) // 2] = img
tfr.add_image(canvas)
print('\r%d / %d => %d ' % (idx + 1, total_images, tfr.cur_images), end='')
except:
print(sys.exc_info()[1])
if tfr.cur_images == max_images:
break
print()
#----------------------------------------------------------------------------
def create_celeba(tfrecord_dir, celeba_dir, cx=89, cy=121):
print('Loading CelebA from "%s"' % celeba_dir)
glob_pattern = os.path.join(celeba_dir, 'img_align_celeba_png', '*.png')
image_filenames = sorted(glob.glob(glob_pattern))
expected_images = 202599
if len(image_filenames) != expected_images:
error('Expected to find %d images' % expected_images)
with TFRecordExporter(tfrecord_dir, len(image_filenames)) as tfr:
order = tfr.choose_shuffled_order()
for idx in range(order.size):
img = np.asarray(PIL.Image.open(image_filenames[order[idx]]))
assert img.shape == (218, 178, 3)
img = img[cy - 64 : cy + 64, cx - 64 : cx + 64]
img = img.transpose(2, 0, 1) # HWC => CHW
tfr.add_image(img)
#----------------------------------------------------------------------------
def create_from_images(tfrecord_dir, image_dir, shuffle):
print('Loading images from "%s"' % image_dir)
image_filenames = sorted(glob.glob(os.path.join(image_dir, '*')))
if len(image_filenames) == 0:
error('No input images found')
img = np.asarray(PIL.Image.open(image_filenames[0]))
resolution = img.shape[0]
channels = img.shape[2] if img.ndim == 3 else 1
if img.shape[1] != resolution:
error('Input images must have the same width and height')
if resolution != 2 ** int(np.floor(np.log2(resolution))):
error('Input image resolution must be a power-of-two')
if channels not in [1, 3]:
error('Input images must be stored as RGB or grayscale')
with TFRecordExporter(tfrecord_dir, len(image_filenames)) as tfr:
order = tfr.choose_shuffled_order() if shuffle else np.arange(len(image_filenames))
for idx in range(order.size):
img = np.asarray(PIL.Image.open(image_filenames[order[idx]]))
if channels == 1:
img = img[np.newaxis, :, :] # HW => CHW
else:
img = img.transpose([2, 0, 1]) # HWC => CHW
tfr.add_image(img)
#----------------------------------------------------------------------------
def create_from_hdf5(tfrecord_dir, hdf5_filename, shuffle):
print('Loading HDF5 archive from "%s"' % hdf5_filename)
import h5py # conda install h5py
with h5py.File(hdf5_filename, 'r') as hdf5_file:
hdf5_data = max([value for key, value in hdf5_file.items() if key.startswith('data')], key=lambda lod: lod.shape[3])
with TFRecordExporter(tfrecord_dir, hdf5_data.shape[0]) as tfr:
order = tfr.choose_shuffled_order() if shuffle else np.arange(hdf5_data.shape[0])
for idx in range(order.size):
tfr.add_image(hdf5_data[order[idx]])
npy_filename = os.path.splitext(hdf5_filename)[0] + '-labels.npy'
if os.path.isfile(npy_filename):
tfr.add_labels(np.load(npy_filename)[order])
#----------------------------------------------------------------------------
def execute_cmdline(argv):
prog = argv[0]
parser = argparse.ArgumentParser(
prog = prog,
description = 'Tool for creating multi-resolution TFRecords datasets for StyleGAN and ProGAN.',
epilog = 'Type "%s <command> -h" for more information.' % prog)
subparsers = parser.add_subparsers(dest='command')
subparsers.required = True
def add_command(cmd, desc, example=None):
epilog = 'Example: %s %s' % (prog, example) if example is not None else None
return subparsers.add_parser(cmd, description=desc, help=desc, epilog=epilog)
p = add_command( 'display', 'Display images in dataset.',
'display datasets/mnist')
p.add_argument( 'tfrecord_dir', help='Directory containing dataset')
p = add_command( 'extract', 'Extract images from dataset.',
'extract datasets/mnist mnist-images')
p.add_argument( 'tfrecord_dir', help='Directory containing dataset')
p.add_argument( 'output_dir', help='Directory to extract the images into')
p = add_command( 'compare', 'Compare two datasets.',
'compare datasets/mydataset datasets/mnist')
p.add_argument( 'tfrecord_dir_a', help='Directory containing first dataset')
p.add_argument( 'tfrecord_dir_b', help='Directory containing second dataset')
p.add_argument( '--ignore_labels', help='Ignore labels (default: 0)', type=int, default=0)
p = add_command( 'create_mnist', 'Create dataset for MNIST.',
'create_mnist datasets/mnist ~/downloads/mnist')
p.add_argument( 'tfrecord_dir', help='New dataset directory to be created')
p.add_argument( 'mnist_dir', help='Directory containing MNIST')
p = add_command( 'create_mnistrgb', 'Create dataset for MNIST-RGB.',
'create_mnistrgb datasets/mnistrgb ~/downloads/mnist')
p.add_argument( 'tfrecord_dir', help='New dataset directory to be created')
p.add_argument( 'mnist_dir', help='Directory containing MNIST')
p.add_argument( '--num_images', help='Number of composite images to create (default: 1000000)', type=int, default=1000000)
p.add_argument( '--random_seed', help='Random seed (default: 123)', type=int, default=123)
p = add_command( 'create_cifar10', 'Create dataset for CIFAR-10.',
'create_cifar10 datasets/cifar10 ~/downloads/cifar10')
p.add_argument( 'tfrecord_dir', help='New dataset directory to be created')
p.add_argument( 'cifar10_dir', help='Directory containing CIFAR-10')
p = add_command( 'create_cifar100', 'Create dataset for CIFAR-100.',
'create_cifar100 datasets/cifar100 ~/downloads/cifar100')
p.add_argument( 'tfrecord_dir', help='New dataset directory to be created')
p.add_argument( 'cifar100_dir', help='Directory containing CIFAR-100')
p = add_command( 'create_svhn', 'Create dataset for SVHN.',
'create_svhn datasets/svhn ~/downloads/svhn')
p.add_argument( 'tfrecord_dir', help='New dataset directory to be created')
p.add_argument( 'svhn_dir', help='Directory containing SVHN')
p = add_command( 'create_lsun', 'Create dataset for single LSUN category.',
'create_lsun datasets/lsun-car-100k ~/downloads/lsun/car_lmdb --resolution 256 --max_images 100000')
p.add_argument( 'tfrecord_dir', help='New dataset directory to be created')
p.add_argument( 'lmdb_dir', help='Directory containing LMDB database')
p.add_argument( '--resolution', help='Output resolution (default: 256)', type=int, default=256)
p.add_argument( '--max_images', help='Maximum number of images (default: none)', type=int, default=None)
p = add_command( 'create_lsun_wide', 'Create LSUN dataset with non-square aspect ratio.',
'create_lsun_wide datasets/lsun-car-512x384 ~/downloads/lsun/car_lmdb --width 512 --height 384')
p.add_argument( 'tfrecord_dir', help='New dataset directory to be created')
p.add_argument( 'lmdb_dir', help='Directory containing LMDB database')
p.add_argument( '--width', help='Output width (default: 512)', type=int, default=512)
p.add_argument( '--height', help='Output height (default: 384)', type=int, default=384)
p.add_argument( '--max_images', help='Maximum number of images (default: none)', type=int, default=None)
p = add_command( 'create_celeba', 'Create dataset for CelebA.',
'create_celeba datasets/celeba ~/downloads/celeba')
p.add_argument( 'tfrecord_dir', help='New dataset directory to be created')
p.add_argument( 'celeba_dir', help='Directory containing CelebA')
p.add_argument( '--cx', help='Center X coordinate (default: 89)', type=int, default=89)
p.add_argument( '--cy', help='Center Y coordinate (default: 121)', type=int, default=121)
p = add_command( 'create_from_images', 'Create dataset from a directory full of images.',
'create_from_images datasets/mydataset myimagedir')
p.add_argument( 'tfrecord_dir', help='New dataset directory to be created')
p.add_argument( 'image_dir', help='Directory containing the images')
p.add_argument( '--shuffle', help='Randomize image order (default: 1)', type=int, default=1)
p = add_command( 'create_from_hdf5', 'Create dataset from legacy HDF5 archive.',
'create_from_hdf5 datasets/celebahq ~/downloads/celeba-hq-1024x1024.h5')
p.add_argument( 'tfrecord_dir', help='New dataset directory to be created')
p.add_argument( 'hdf5_filename', help='HDF5 archive containing the images')
p.add_argument( '--shuffle', help='Randomize image order (default: 1)', type=int, default=1)
args = parser.parse_args(argv[1:] if len(argv) > 1 else ['-h'])
func = globals()[args.command]
del args.command
func(**vars(args))
#----------------------------------------------------------------------------
if __name__ == "__main__":
execute_cmdline(sys.argv)
#----------------------------------------------------------------------------
|
stylegan-master
|
dataset_tool.py
|
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# This work is licensed under the Creative Commons Attribution-NonCommercial
# 4.0 International License. To view a copy of this license, visit
# http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to
# Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
"""Main entry point for training StyleGAN and ProGAN networks."""
import dnnlib
from dnnlib import EasyDict
import dnnlib.tflib as tflib
import config
from metrics import metric_base
from training import misc
#----------------------------------------------------------------------------
def run_pickle(submit_config, metric_args, network_pkl, dataset_args, mirror_augment):
ctx = dnnlib.RunContext(submit_config)
tflib.init_tf()
print('Evaluating %s metric on network_pkl "%s"...' % (metric_args.name, network_pkl))
metric = dnnlib.util.call_func_by_name(**metric_args)
print()
metric.run(network_pkl, dataset_args=dataset_args, mirror_augment=mirror_augment, num_gpus=submit_config.num_gpus)
print()
ctx.close()
#----------------------------------------------------------------------------
def run_snapshot(submit_config, metric_args, run_id, snapshot):
ctx = dnnlib.RunContext(submit_config)
tflib.init_tf()
print('Evaluating %s metric on run_id %s, snapshot %s...' % (metric_args.name, run_id, snapshot))
run_dir = misc.locate_run_dir(run_id)
network_pkl = misc.locate_network_pkl(run_dir, snapshot)
metric = dnnlib.util.call_func_by_name(**metric_args)
print()
metric.run(network_pkl, run_dir=run_dir, num_gpus=submit_config.num_gpus)
print()
ctx.close()
#----------------------------------------------------------------------------
def run_all_snapshots(submit_config, metric_args, run_id):
ctx = dnnlib.RunContext(submit_config)
tflib.init_tf()
print('Evaluating %s metric on all snapshots of run_id %s...' % (metric_args.name, run_id))
run_dir = misc.locate_run_dir(run_id)
network_pkls = misc.list_network_pkls(run_dir)
metric = dnnlib.util.call_func_by_name(**metric_args)
print()
for idx, network_pkl in enumerate(network_pkls):
ctx.update('', idx, len(network_pkls))
metric.run(network_pkl, run_dir=run_dir, num_gpus=submit_config.num_gpus)
print()
ctx.close()
#----------------------------------------------------------------------------
def main():
submit_config = dnnlib.SubmitConfig()
# Which metrics to evaluate?
metrics = []
metrics += [metric_base.fid50k]
#metrics += [metric_base.ppl_zfull]
#metrics += [metric_base.ppl_wfull]
#metrics += [metric_base.ppl_zend]
#metrics += [metric_base.ppl_wend]
#metrics += [metric_base.ls]
#metrics += [metric_base.dummy]
# Which networks to evaluate them on?
tasks = []
tasks += [EasyDict(run_func_name='run_metrics.run_pickle', network_pkl='https://drive.google.com/uc?id=1MEGjdvVpUsu1jB4zrXZN7Y4kBBOzizDQ', dataset_args=EasyDict(tfrecord_dir='ffhq', shuffle_mb=0), mirror_augment=True)] # karras2019stylegan-ffhq-1024x1024.pkl
#tasks += [EasyDict(run_func_name='run_metrics.run_snapshot', run_id=100, snapshot=25000)]
#tasks += [EasyDict(run_func_name='run_metrics.run_all_snapshots', run_id=100)]
# How many GPUs to use?
submit_config.num_gpus = 1
#submit_config.num_gpus = 2
#submit_config.num_gpus = 4
#submit_config.num_gpus = 8
# Execute.
submit_config.run_dir_root = dnnlib.submission.submit.get_template_from_path(config.result_dir)
submit_config.run_dir_ignore += config.run_dir_ignore
for task in tasks:
for metric in metrics:
submit_config.run_desc = '%s-%s' % (task.run_func_name, metric.name)
if task.run_func_name.endswith('run_snapshot'):
submit_config.run_desc += '-%s-%s' % (task.run_id, task.snapshot)
if task.run_func_name.endswith('run_all_snapshots'):
submit_config.run_desc += '-%s' % task.run_id
submit_config.run_desc += '-%dgpu' % submit_config.num_gpus
dnnlib.submit_run(submit_config, metric_args=metric, **task)
#----------------------------------------------------------------------------
if __name__ == "__main__":
main()
#----------------------------------------------------------------------------
|
stylegan-master
|
run_metrics.py
|
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# This work is licensed under the Creative Commons Attribution-NonCommercial
# 4.0 International License. To view a copy of this license, visit
# http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to
# Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
"""Minimal script for reproducing the figures of the StyleGAN paper using pre-trained generators."""
import os
import pickle
import numpy as np
import PIL.Image
import dnnlib
import dnnlib.tflib as tflib
import config
import argparse
# argument parser to make seed configurable
def str2bool(val = ''):
normalized_val = val.lower()
if normalized_val in ('yes', 'true', 't', 'y', '1'):
return True
elif normalized_val in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.')
parser = argparse.ArgumentParser(description='testing StyleGAN generator')
parser.add_argument('--seed', type=int, default=42)
parser.add_argument('--generate-all-faces-examples', type=str2bool, default=False)
parser.add_argument('--generate-bedrooms', type=str2bool, default=False)
parser.add_argument('--generate-cars', type=str2bool, default=False)
parser.add_argument('--generate-cats', type=str2bool, default=False)
args = parser.parse_args()
#----------------------------------------------------------------------------
# Helpers for loading and using pre-trained generators.
url_ffhq = 'https://drive.google.com/uc?id=1MEGjdvVpUsu1jB4zrXZN7Y4kBBOzizDQ' # karras2019stylegan-ffhq-1024x1024.pkl
url_celebahq = 'https://drive.google.com/uc?id=1MGqJl28pN4t7SAtSrPdSRJSQJqahkzUf' # karras2019stylegan-celebahq-1024x1024.pkl
url_bedrooms = 'https://drive.google.com/uc?id=1MOSKeGF0FJcivpBI7s63V9YHloUTORiF' # karras2019stylegan-bedrooms-256x256.pkl
url_cars = 'https://drive.google.com/uc?id=1MJ6iCfNtMIRicihwRorsM3b7mmtmK9c3' # karras2019stylegan-cars-512x384.pkl
url_cats = 'https://drive.google.com/uc?id=1MQywl0FNt6lHu8E_EUqnRbviagS7fbiJ' # karras2019stylegan-cats-256x256.pkl
synthesis_kwargs = dict(output_transform=dict(func=tflib.convert_images_to_uint8, nchw_to_nhwc=True), minibatch_size=8)
_Gs_cache = dict()
def load_Gs(url):
if url not in _Gs_cache:
with dnnlib.util.open_url(url, cache_dir=config.cache_dir) as f:
_G, _D, Gs = pickle.load(f)
_Gs_cache[url] = Gs
return _Gs_cache[url]
#----------------------------------------------------------------------------
# Figures 2, 3, 10, 11, 12: Multi-resolution grid of uncurated result images.
def draw_uncurated_result_figure(png, Gs, cx, cy, cw, ch, rows, lods, seed):
print(png)
latents = np.random.RandomState(seed).randn(sum(rows * 2**lod for lod in lods), Gs.input_shape[1])
images = Gs.run(latents, None, **synthesis_kwargs) # [seed, y, x, rgb]
canvas = PIL.Image.new('RGB', (sum(cw // 2**lod for lod in lods), ch * rows), 'white')
image_iter = iter(list(images))
for col, lod in enumerate(lods):
for row in range(rows * 2**lod):
image = PIL.Image.fromarray(next(image_iter), 'RGB')
image = image.crop((cx, cy, cx + cw, cy + ch))
image = image.resize((cw // 2**lod, ch // 2**lod), PIL.Image.ANTIALIAS)
canvas.paste(image, (sum(cw // 2**lod for lod in lods[:col]), row * ch // 2**lod))
canvas.save(png)
#----------------------------------------------------------------------------
# Figure 3: Style mixing.
def draw_style_mixing_figure(png, Gs, w, h, src_seeds, dst_seeds, style_ranges):
print(png)
src_latents = np.stack(np.random.RandomState(seed).randn(Gs.input_shape[1]) for seed in src_seeds)
dst_latents = np.stack(np.random.RandomState(seed).randn(Gs.input_shape[1]) for seed in dst_seeds)
src_dlatents = Gs.components.mapping.run(src_latents, None) # [seed, layer, component]
dst_dlatents = Gs.components.mapping.run(dst_latents, None) # [seed, layer, component]
src_images = Gs.components.synthesis.run(src_dlatents, randomize_noise=False, **synthesis_kwargs)
dst_images = Gs.components.synthesis.run(dst_dlatents, randomize_noise=False, **synthesis_kwargs)
canvas = PIL.Image.new('RGB', (w * (len(src_seeds) + 1), h * (len(dst_seeds) + 1)), 'white')
for col, src_image in enumerate(list(src_images)):
canvas.paste(PIL.Image.fromarray(src_image, 'RGB'), ((col + 1) * w, 0))
for row, dst_image in enumerate(list(dst_images)):
canvas.paste(PIL.Image.fromarray(dst_image, 'RGB'), (0, (row + 1) * h))
row_dlatents = np.stack([dst_dlatents[row]] * len(src_seeds))
row_dlatents[:, style_ranges[row]] = src_dlatents[:, style_ranges[row]]
row_images = Gs.components.synthesis.run(row_dlatents, randomize_noise=False, **synthesis_kwargs)
for col, image in enumerate(list(row_images)):
canvas.paste(PIL.Image.fromarray(image, 'RGB'), ((col + 1) * w, (row + 1) * h))
canvas.save(png)
#----------------------------------------------------------------------------
# Figure 4: Noise detail.
def draw_noise_detail_figure(png, Gs, w, h, num_samples, seeds):
print(png)
canvas = PIL.Image.new('RGB', (w * 3, h * len(seeds)), 'white')
for row, seed in enumerate(seeds):
latents = np.stack([np.random.RandomState(seed).randn(Gs.input_shape[1])] * num_samples)
images = Gs.run(latents, None, truncation_psi=1, **synthesis_kwargs)
canvas.paste(PIL.Image.fromarray(images[0], 'RGB'), (0, row * h))
for i in range(4):
crop = PIL.Image.fromarray(images[i + 1], 'RGB')
crop = crop.crop((650, 180, 906, 436))
crop = crop.resize((w//2, h//2), PIL.Image.NEAREST)
canvas.paste(crop, (w + (i%2) * w//2, row * h + (i//2) * h//2))
diff = np.std(np.mean(images, axis=3), axis=0) * 4
diff = np.clip(diff + 0.5, 0, 255).astype(np.uint8)
canvas.paste(PIL.Image.fromarray(diff, 'L'), (w * 2, row * h))
canvas.save(png)
#----------------------------------------------------------------------------
# Figure 5: Noise components.
def draw_noise_components_figure(png, Gs, w, h, seeds, noise_ranges, flips):
print(png)
Gsc = Gs.clone()
noise_vars = [var for name, var in Gsc.components.synthesis.vars.items() if name.startswith('noise')]
noise_pairs = list(zip(noise_vars, tflib.run(noise_vars))) # [(var, val), ...]
latents = np.stack(np.random.RandomState(seed).randn(Gs.input_shape[1]) for seed in seeds)
all_images = []
for noise_range in noise_ranges:
tflib.set_vars({var: val * (1 if i in noise_range else 0) for i, (var, val) in enumerate(noise_pairs)})
range_images = Gsc.run(latents, None, truncation_psi=1, randomize_noise=False, **synthesis_kwargs)
range_images[flips, :, :] = range_images[flips, :, ::-1]
all_images.append(list(range_images))
canvas = PIL.Image.new('RGB', (w * 2, h * 2), 'white')
for col, col_images in enumerate(zip(*all_images)):
canvas.paste(PIL.Image.fromarray(col_images[0], 'RGB').crop((0, 0, w//2, h)), (col * w, 0))
canvas.paste(PIL.Image.fromarray(col_images[1], 'RGB').crop((w//2, 0, w, h)), (col * w + w//2, 0))
canvas.paste(PIL.Image.fromarray(col_images[2], 'RGB').crop((0, 0, w//2, h)), (col * w, h))
canvas.paste(PIL.Image.fromarray(col_images[3], 'RGB').crop((w//2, 0, w, h)), (col * w + w//2, h))
canvas.save(png)
#----------------------------------------------------------------------------
# Figure 8: Truncation trick.
def draw_truncation_trick_figure(png, Gs, w, h, seeds, psis):
print(png)
latents = np.stack(np.random.RandomState(seed).randn(Gs.input_shape[1]) for seed in seeds)
dlatents = Gs.components.mapping.run(latents, None) # [seed, layer, component]
dlatent_avg = Gs.get_var('dlatent_avg') # [component]
canvas = PIL.Image.new('RGB', (w * len(psis), h * len(seeds)), 'white')
for row, dlatent in enumerate(list(dlatents)):
row_dlatents = (dlatent[np.newaxis] - dlatent_avg) * np.reshape(psis, [-1, 1, 1]) + dlatent_avg
row_images = Gs.components.synthesis.run(row_dlatents, randomize_noise=False, **synthesis_kwargs)
for col, image in enumerate(list(row_images)):
canvas.paste(PIL.Image.fromarray(image, 'RGB'), (col * w, row * h))
canvas.save(png)
#----------------------------------------------------------------------------
# Main program.
def main():
tflib.init_tf()
os.makedirs(config.result_dir, exist_ok=True)
draw_uncurated_result_figure(os.path.join(config.result_dir, 'figure02-uncurated-ffhq.png'), load_Gs(url_ffhq), cx=0, cy=0, cw=1024, ch=1024, rows=3, lods=[0,1,2,2,3,3], seed=args.seed)
if args.generate_all_faces_examples:
draw_style_mixing_figure(os.path.join(config.result_dir, 'figure03-style-mixing.png'), load_Gs(url_ffhq), w=1024, h=1024, src_seeds=[639,701,687,615,2268], dst_seeds=[888,829,1898,1733,1614,845], style_ranges=[range(0,4)]*3+[range(4,8)]*2+[range(8,18)])
draw_noise_detail_figure(os.path.join(config.result_dir, 'figure04-noise-detail.png'), load_Gs(url_ffhq), w=1024, h=1024, num_samples=100, seeds=[1157,1012])
draw_noise_components_figure(os.path.join(config.result_dir, 'figure05-noise-components.png'), load_Gs(url_ffhq), w=1024, h=1024, seeds=[1967,1555], noise_ranges=[range(0, 18), range(0, 0), range(8, 18), range(0, 8)], flips=[1])
draw_truncation_trick_figure(os.path.join(config.result_dir, 'figure08-truncation-trick.png'), load_Gs(url_ffhq), w=1024, h=1024, seeds=[91,388], psis=[1, 0.7, 0.5, 0, -0.5, -1])
if args.generate_bedrooms:
draw_uncurated_result_figure(os.path.join(config.result_dir, 'figure10-uncurated-bedrooms.png'), load_Gs(url_bedrooms), cx=0, cy=0, cw=256, ch=256, rows=5, lods=[0,0,1,1,2,2,2], seed=args.seed)
if args.generate_cars:
draw_uncurated_result_figure(os.path.join(config.result_dir, 'figure11-uncurated-cars.png'), load_Gs(url_cars), cx=0, cy=64, cw=512, ch=384, rows=4, lods=[0,1,2,2,3,3], seed=args.seed)
if args.generate_cats:
draw_uncurated_result_figure(os.path.join(config.result_dir, 'figure12-uncurated-cats.png'), load_Gs(url_cats), cx=0, cy=0, cw=256, ch=256, rows=5, lods=[0,0,1,1,2,2,2], seed=args.seed)
#----------------------------------------------------------------------------
if __name__ == "__main__":
main()
#----------------------------------------------------------------------------
|
stylegan-master
|
generate_figures.py
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.