We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Incomplete download of MNIST data
### Description

`make test-examples` fails to fully download mnist data dependency for the air example

### Details

On `osx==10.14.1` and `docker==18.09.2`

```
git checkout 3ac5a02e0e6b0a11ae796707413c11df2c14ff6b
make build pyro_branch=dev pytorch_branch=release python_verion=3.6
make run pyro_branch=dev pytorch_branch=release python_verion=3.6
cd pyro
pip install numpy==1.15
pip install scipy==1.2
make test-examples > output 2>&1
```

[Output](https://github.com/pyro-ppl/pyro/files/3204055/make_test_examples.txt)

Resulting files in `.data`
```
ls -lh -rw-r--r--  1 matt  staff    19M May 21 15:03 train-images-idx3-ubyte.gz.part
```

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `setup.py`
Content:
```
1 from __future__ import absolute_import, division, print_function
2 
3 import os
4 import subprocess
5 import sys
6 
7 from setuptools import find_packages, setup
8 
9 PROJECT_PATH = os.path.dirname(os.path.abspath(__file__))
10 VERSION = """
11 # This file is auto-generated with the version information during setup.py installation.
12 
13 __version__ = '{}'
14 """
15 
16 # Find pyro version.
17 for line in open(os.path.join(PROJECT_PATH, 'pyro', '__init__.py')):
18     if line.startswith('version_prefix = '):
19         version = line.strip().split()[2][1:-1]
20 
21 # Append current commit sha to version
22 commit_sha = ''
23 try:
24     current_tag = subprocess.check_output(['git', 'tag', '--points-at', 'HEAD'],
25                                           cwd=PROJECT_PATH).decode('ascii').strip()
26     # only add sha if HEAD does not point to the release tag
27     if not current_tag == version:
28         commit_sha = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'],
29                                              cwd=PROJECT_PATH).decode('ascii').strip()
30 # catch all exception to be safe
31 except Exception:
32     pass  # probably not a git repo
33 
34 # Write version to _version.py
35 if commit_sha:
36     version += '+{}'.format(commit_sha)
37 with open(os.path.join(PROJECT_PATH, 'pyro', '_version.py'), 'w') as f:
38     f.write(VERSION.format(version))
39 
40 # Convert README.md to rst for display at https://pypi.python.org/pypi/pyro-ppl
41 # When releasing on pypi, make sure pandoc is on your system:
42 # $ brew install pandoc          # OS X
43 # $ sudo apt-get install pandoc  # Ubuntu Linux
44 try:
45     import pypandoc
46     long_description = pypandoc.convert('README.md', 'rst')
47     print(long_description)
48 except Exception as e:
49     sys.stderr.write('Failed to convert README.md to rst:\n  {}\n'.format(e))
50     sys.stderr.flush()
51     long_description = open('README.md').read()
52 
53 # Remove badges since they will always be obsolete.
54 # This assumes the first 10 lines contain badge info.
55 long_description = '\n'.join([str(line) for line in long_description.split('\n')[10:]])
56 
57 # examples/tutorials
58 EXTRAS_REQUIRE = [
59     'jupyter>=1.0.0',
60     'matplotlib>=1.3',
61     'observations>=0.1.4',
62     'pillow',
63     'torchvision>=0.2.2',
64     'visdom>=0.1.4',
65     'pandas',
66     'seaborn',
67     'wget',
68 ]
69 
70 if sys.version_info[0] == 2:
71     EXTRAS_REQUIRE.append('functools32')
72 
73 setup(
74     name='pyro-ppl',
75     version=version,
76     description='A Python library for probabilistic modeling and inference',
77     long_description=long_description,
78     packages=find_packages(include=['pyro', 'pyro.*']),
79     url='http://pyro.ai',
80     author='Uber AI Labs',
81     author_email='pyro@uber.com',
82     install_requires=[
83         # if you add any additional libraries, please also
84         # add them to `docs/requirements.txt`
85         'contextlib2',
86         'graphviz>=0.8',
87         # numpy is necessary for some functionality of PyTorch
88         'numpy>=1.7',
89         'opt_einsum>=2.3.2',
90         'six>=1.10.0',
91         'torch>=1.1.0',
92         'tqdm>=4.31',
93     ],
94     extras_require={
95         'extras': EXTRAS_REQUIRE,
96         'test': EXTRAS_REQUIRE + [
97             'nbval',
98             'pytest>=4.1',
99             'pytest-cov',
100             # TODO: remove once https://github.com/pyro-ppl/pyro/issues/1871
101             # is fixed.
102             'scipy>=1.1, <1.3',
103         ],
104         'profile': ['prettytable', 'pytest-benchmark', 'snakeviz'],
105         'dev': EXTRAS_REQUIRE + [
106             'flake8',
107             'isort',
108             'nbformat',
109             'nbsphinx>=0.3.2',
110             'nbstripout',
111             'nbval',
112             'pypandoc',
113             'pytest>=4.1',
114             'pytest-xdist',
115             # TODO: remove once https://github.com/pyro-ppl/pyro/issues/1871
116             # is fixed.
117             'scipy>=1.1, < 1.3',
118             'sphinx',
119             'sphinx_rtd_theme',
120             'yapf',
121         ],
122     },
123     tests_require=['flake8', 'pytest>=4.1'],
124     keywords='machine learning statistics probabilistic programming bayesian modeling pytorch',
125     license='MIT License',
126     classifiers=[
127         'Intended Audience :: Developers',
128         'Intended Audience :: Education',
129         'Intended Audience :: Science/Research',
130         'Operating System :: POSIX :: Linux',
131         'Operating System :: MacOS :: MacOS X',
132         'Programming Language :: Python :: 2.7',
133         'Programming Language :: Python :: 3.6',
134     ],
135     # yapf
136 )
137
```

Path: `pyro/contrib/examples/multi_mnist.py`
Content:
```
1 """
2 This script generates a dataset similar to the Multi-MNIST dataset
3 described in [1].
4 
5 [1] Eslami, SM Ali, et al. "Attend, infer, repeat: Fast scene
6 understanding with generative models." Advances in Neural Information
7 Processing Systems. 2016.
8 """
9 
10 import os
11 
12 import numpy as np
13 from PIL import Image
14 
15 from pyro.contrib.examples.util import get_data_loader
16 
17 
18 def imresize(arr, size):
19     return np.array(Image.fromarray(arr).resize(size))
20 
21 
22 def sample_one(canvas_size, mnist):
23     i = np.random.randint(mnist['digits'].shape[0])
24     digit = mnist['digits'][i]
25     label = mnist['labels'][i].item()
26     scale = 0.1 * np.random.randn() + 1.3
27     new_size = tuple(int(s / scale) for s in digit.shape)
28     resized = imresize(digit, new_size)
29     w = resized.shape[0]
30     assert w == resized.shape[1]
31     padding = canvas_size - w
32     pad_l = np.random.randint(0, padding)
33     pad_r = np.random.randint(0, padding)
34     pad_width = ((pad_l, padding - pad_l), (pad_r, padding - pad_r))
35     positioned = np.pad(resized, pad_width, 'constant', constant_values=0)
36     return positioned, label
37 
38 
39 def sample_multi(num_digits, canvas_size, mnist):
40     canvas = np.zeros((canvas_size, canvas_size))
41     labels = []
42     for _ in range(num_digits):
43         positioned_digit, label = sample_one(canvas_size, mnist)
44         canvas += positioned_digit
45         labels.append(label)
46     # Crude check for overlapping digits.
47     if np.max(canvas) > 255:
48         return sample_multi(num_digits, canvas_size, mnist)
49     else:
50         return canvas, labels
51 
52 
53 def mk_dataset(n, mnist, max_digits, canvas_size):
54     x = []
55     y = []
56     for _ in range(n):
57         num_digits = np.random.randint(max_digits + 1)
58         canvas, labels = sample_multi(num_digits, canvas_size, mnist)
59         x.append(canvas)
60         y.append(labels)
61     return np.array(x, dtype=np.uint8), y
62 
63 
64 def load_mnist(root_path):
65     loader = get_data_loader('MNIST', root_path)
66     return {
67         'digits': loader.dataset.data.cpu().numpy(),
68         'labels': loader.dataset.targets
69     }
70 
71 
72 def load(root_path):
73     file_path = os.path.join(root_path, 'multi_mnist_uint8.npz')
74     if os.path.exists(file_path):
75         data = np.load(file_path)
76         return data['x'], data['y']
77     else:
78         # Set RNG to known state.
79         rng_state = np.random.get_state()
80         np.random.seed(681307)
81         mnist = load_mnist(root_path)
82         print('Generating multi-MNIST dataset...')
83         x, y = mk_dataset(60000, mnist, 2, 50)
84         # Revert RNG state.
85         np.random.set_state(rng_state)
86         # Crude checksum.
87         # assert x.sum() == 883114919, 'Did not generate the expected data.'
88         with open(file_path, 'wb') as f:
89             np.savez_compressed(f, x=x, y=y)
90         print('Done!')
91         return x, y
92
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/pyro/contrib/examples/multi_mnist.py b/pyro/contrib/examples/multi_mnist.py
--- a/pyro/contrib/examples/multi_mnist.py
+++ b/pyro/contrib/examples/multi_mnist.py
@@ -72,7 +72,7 @@
 def load(root_path):
     file_path = os.path.join(root_path, 'multi_mnist_uint8.npz')
     if os.path.exists(file_path):
-        data = np.load(file_path)
+        data = np.load(file_path, allow_pickle=True)
         return data['x'], data['y']
     else:
         # Set RNG to known state.
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -58,7 +58,6 @@
 EXTRAS_REQUIRE = [
     'jupyter>=1.0.0',
     'matplotlib>=1.3',
-    'observations>=0.1.4',
     'pillow',
     'torchvision>=0.2.2',
     'visdom>=0.1.4',

{"golden_diff": "diff --git a/pyro/contrib/examples/multi_mnist.py b/pyro/contrib/examples/multi_mnist.py\n--- a/pyro/contrib/examples/multi_mnist.py\n+++ b/pyro/contrib/examples/multi_mnist.py\n@@ -72,7 +72,7 @@\n def load(root_path):\n     file_path = os.path.join(root_path, 'multi_mnist_uint8.npz')\n     if os.path.exists(file_path):\n-        data = np.load(file_path)\n+        data = np.load(file_path, allow_pickle=True)\n         return data['x'], data['y']\n     else:\n         # Set RNG to known state.\ndiff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -58,7 +58,6 @@\n EXTRAS_REQUIRE = [\n     'jupyter>=1.0.0',\n     'matplotlib>=1.3',\n-    'observations>=0.1.4',\n     'pillow',\n     'torchvision>=0.2.2',\n     'visdom>=0.1.4',\n", "issue": "Incomplete download of MNIST data\n### Description\r\n\r\n`make test-examples` fails to fully download mnist data dependency for the air example\r\n\r\n### Details\r\n\r\nOn `osx==10.14.1` and `docker==18.09.2`\r\n\r\n```\r\ngit checkout 3ac5a02e0e6b0a11ae796707413c11df2c14ff6b\r\nmake build pyro_branch=dev pytorch_branch=release python_verion=3.6\r\nmake run pyro_branch=dev pytorch_branch=release python_verion=3.6\r\ncd pyro\r\npip install numpy==1.15\r\npip install scipy==1.2\r\nmake test-examples > output 2>&1\r\n```\r\n\r\n[Output](https://github.com/pyro-ppl/pyro/files/3204055/make_test_examples.txt)\r\n\r\nResulting files in `.data`\r\n```\r\nls -lh -rw-r--r--  1 matt  staff    19M May 21 15:03 train-images-idx3-ubyte.gz.part\r\n```\n", "before_files": [{"content": "from __future__ import absolute_import, division, print_function\n\nimport os\nimport subprocess\nimport sys\n\nfrom setuptools import find_packages, setup\n\nPROJECT_PATH = os.path.dirname(os.path.abspath(__file__))\nVERSION = \"\"\"\n# This file is auto-generated with the version information during setup.py installation.\n\n__version__ = '{}'\n\"\"\"\n\n# Find pyro version.\nfor line in open(os.path.join(PROJECT_PATH, 'pyro', '__init__.py')):\n    if line.startswith('version_prefix = '):\n        version = line.strip().split()[2][1:-1]\n\n# Append current commit sha to version\ncommit_sha = ''\ntry:\n    current_tag = subprocess.check_output(['git', 'tag', '--points-at', 'HEAD'],\n                                          cwd=PROJECT_PATH).decode('ascii').strip()\n    # only add sha if HEAD does not point to the release tag\n    if not current_tag == version:\n        commit_sha = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'],\n                                             cwd=PROJECT_PATH).decode('ascii').strip()\n# catch all exception to be safe\nexcept Exception:\n    pass  # probably not a git repo\n\n# Write version to _version.py\nif commit_sha:\n    version += '+{}'.format(commit_sha)\nwith open(os.path.join(PROJECT_PATH, 'pyro', '_version.py'), 'w') as f:\n    f.write(VERSION.format(version))\n\n# Convert README.md to rst for display at https://pypi.python.org/pypi/pyro-ppl\n# When releasing on pypi, make sure pandoc is on your system:\n# $ brew install pandoc          # OS X\n# $ sudo apt-get install pandoc  # Ubuntu Linux\ntry:\n    import pypandoc\n    long_description = pypandoc.convert('README.md', 'rst')\n    print(long_description)\nexcept Exception as e:\n    sys.stderr.write('Failed to convert README.md to rst:\\n  {}\\n'.format(e))\n    sys.stderr.flush()\n    long_description = open('README.md').read()\n\n# Remove badges since they will always be obsolete.\n# This assumes the first 10 lines contain badge info.\nlong_description = '\\n'.join([str(line) for line in long_description.split('\\n')[10:]])\n\n# examples/tutorials\nEXTRAS_REQUIRE = [\n    'jupyter>=1.0.0',\n    'matplotlib>=1.3',\n    'observations>=0.1.4',\n    'pillow',\n    'torchvision>=0.2.2',\n    'visdom>=0.1.4',\n    'pandas',\n    'seaborn',\n    'wget',\n]\n\nif sys.version_info[0] == 2:\n    EXTRAS_REQUIRE.append('functools32')\n\nsetup(\n    name='pyro-ppl',\n    version=version,\n    description='A Python library for probabilistic modeling and inference',\n    long_description=long_description,\n    packages=find_packages(include=['pyro', 'pyro.*']),\n    url='http://pyro.ai',\n    author='Uber AI Labs',\n    author_email='pyro@uber.com',\n    install_requires=[\n        # if you add any additional libraries, please also\n        # add them to `docs/requirements.txt`\n        'contextlib2',\n        'graphviz>=0.8',\n        # numpy is necessary for some functionality of PyTorch\n        'numpy>=1.7',\n        'opt_einsum>=2.3.2',\n        'six>=1.10.0',\n        'torch>=1.1.0',\n        'tqdm>=4.31',\n    ],\n    extras_require={\n        'extras': EXTRAS_REQUIRE,\n        'test': EXTRAS_REQUIRE + [\n            'nbval',\n            'pytest>=4.1',\n            'pytest-cov',\n            # TODO: remove once https://github.com/pyro-ppl/pyro/issues/1871\n            # is fixed.\n            'scipy>=1.1, <1.3',\n        ],\n        'profile': ['prettytable', 'pytest-benchmark', 'snakeviz'],\n        'dev': EXTRAS_REQUIRE + [\n            'flake8',\n            'isort',\n            'nbformat',\n            'nbsphinx>=0.3.2',\n            'nbstripout',\n            'nbval',\n            'pypandoc',\n            'pytest>=4.1',\n            'pytest-xdist',\n            # TODO: remove once https://github.com/pyro-ppl/pyro/issues/1871\n            # is fixed.\n            'scipy>=1.1, < 1.3',\n            'sphinx',\n            'sphinx_rtd_theme',\n            'yapf',\n        ],\n    },\n    tests_require=['flake8', 'pytest>=4.1'],\n    keywords='machine learning statistics probabilistic programming bayesian modeling pytorch',\n    license='MIT License',\n    classifiers=[\n        'Intended Audience :: Developers',\n        'Intended Audience :: Education',\n        'Intended Audience :: Science/Research',\n        'Operating System :: POSIX :: Linux',\n        'Operating System :: MacOS :: MacOS X',\n        'Programming Language :: Python :: 2.7',\n        'Programming Language :: Python :: 3.6',\n    ],\n    # yapf\n)\n", "path": "setup.py"}, {"content": "\"\"\"\nThis script generates a dataset similar to the Multi-MNIST dataset\ndescribed in [1].\n\n[1] Eslami, SM Ali, et al. \"Attend, infer, repeat: Fast scene\nunderstanding with generative models.\" Advances in Neural Information\nProcessing Systems. 2016.\n\"\"\"\n\nimport os\n\nimport numpy as np\nfrom PIL import Image\n\nfrom pyro.contrib.examples.util import get_data_loader\n\n\ndef imresize(arr, size):\n    return np.array(Image.fromarray(arr).resize(size))\n\n\ndef sample_one(canvas_size, mnist):\n    i = np.random.randint(mnist['digits'].shape[0])\n    digit = mnist['digits'][i]\n    label = mnist['labels'][i].item()\n    scale = 0.1 * np.random.randn() + 1.3\n    new_size = tuple(int(s / scale) for s in digit.shape)\n    resized = imresize(digit, new_size)\n    w = resized.shape[0]\n    assert w == resized.shape[1]\n    padding = canvas_size - w\n    pad_l = np.random.randint(0, padding)\n    pad_r = np.random.randint(0, padding)\n    pad_width = ((pad_l, padding - pad_l), (pad_r, padding - pad_r))\n    positioned = np.pad(resized, pad_width, 'constant', constant_values=0)\n    return positioned, label\n\n\ndef sample_multi(num_digits, canvas_size, mnist):\n    canvas = np.zeros((canvas_size, canvas_size))\n    labels = []\n    for _ in range(num_digits):\n        positioned_digit, label = sample_one(canvas_size, mnist)\n        canvas += positioned_digit\n        labels.append(label)\n    # Crude check for overlapping digits.\n    if np.max(canvas) > 255:\n        return sample_multi(num_digits, canvas_size, mnist)\n    else:\n        return canvas, labels\n\n\ndef mk_dataset(n, mnist, max_digits, canvas_size):\n    x = []\n    y = []\n    for _ in range(n):\n        num_digits = np.random.randint(max_digits + 1)\n        canvas, labels = sample_multi(num_digits, canvas_size, mnist)\n        x.append(canvas)\n        y.append(labels)\n    return np.array(x, dtype=np.uint8), y\n\n\ndef load_mnist(root_path):\n    loader = get_data_loader('MNIST', root_path)\n    return {\n        'digits': loader.dataset.data.cpu().numpy(),\n        'labels': loader.dataset.targets\n    }\n\n\ndef load(root_path):\n    file_path = os.path.join(root_path, 'multi_mnist_uint8.npz')\n    if os.path.exists(file_path):\n        data = np.load(file_path)\n        return data['x'], data['y']\n    else:\n        # Set RNG to known state.\n        rng_state = np.random.get_state()\n        np.random.seed(681307)\n        mnist = load_mnist(root_path)\n        print('Generating multi-MNIST dataset...')\n        x, y = mk_dataset(60000, mnist, 2, 50)\n        # Revert RNG state.\n        np.random.set_state(rng_state)\n        # Crude checksum.\n        # assert x.sum() == 883114919, 'Did not generate the expected data.'\n        with open(file_path, 'wb') as f:\n            np.savez_compressed(f, x=x, y=y)\n        print('Done!')\n        return x, y\n", "path": "pyro/contrib/examples/multi_mnist.py"}], "after_files": [{"content": "from __future__ import absolute_import, division, print_function\n\nimport os\nimport subprocess\nimport sys\n\nfrom setuptools import find_packages, setup\n\nPROJECT_PATH = os.path.dirname(os.path.abspath(__file__))\nVERSION = \"\"\"\n# This file is auto-generated with the version information during setup.py installation.\n\n__version__ = '{}'\n\"\"\"\n\n# Find pyro version.\nfor line in open(os.path.join(PROJECT_PATH, 'pyro', '__init__.py')):\n    if line.startswith('version_prefix = '):\n        version = line.strip().split()[2][1:-1]\n\n# Append current commit sha to version\ncommit_sha = ''\ntry:\n    current_tag = subprocess.check_output(['git', 'tag', '--points-at', 'HEAD'],\n                                          cwd=PROJECT_PATH).decode('ascii').strip()\n    # only add sha if HEAD does not point to the release tag\n    if not current_tag == version:\n        commit_sha = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'],\n                                             cwd=PROJECT_PATH).decode('ascii').strip()\n# catch all exception to be safe\nexcept Exception:\n    pass  # probably not a git repo\n\n# Write version to _version.py\nif commit_sha:\n    version += '+{}'.format(commit_sha)\nwith open(os.path.join(PROJECT_PATH, 'pyro', '_version.py'), 'w') as f:\n    f.write(VERSION.format(version))\n\n# Convert README.md to rst for display at https://pypi.python.org/pypi/pyro-ppl\n# When releasing on pypi, make sure pandoc is on your system:\n# $ brew install pandoc          # OS X\n# $ sudo apt-get install pandoc  # Ubuntu Linux\ntry:\n    import pypandoc\n    long_description = pypandoc.convert('README.md', 'rst')\n    print(long_description)\nexcept Exception as e:\n    sys.stderr.write('Failed to convert README.md to rst:\\n  {}\\n'.format(e))\n    sys.stderr.flush()\n    long_description = open('README.md').read()\n\n# Remove badges since they will always be obsolete.\n# This assumes the first 10 lines contain badge info.\nlong_description = '\\n'.join([str(line) for line in long_description.split('\\n')[10:]])\n\n# examples/tutorials\nEXTRAS_REQUIRE = [\n    'jupyter>=1.0.0',\n    'matplotlib>=1.3',\n    'pillow',\n    'torchvision>=0.2.2',\n    'visdom>=0.1.4',\n    'pandas',\n    'seaborn',\n    'wget',\n]\n\nif sys.version_info[0] == 2:\n    EXTRAS_REQUIRE.append('functools32')\n\nsetup(\n    name='pyro-ppl',\n    version=version,\n    description='A Python library for probabilistic modeling and inference',\n    long_description=long_description,\n    packages=find_packages(include=['pyro', 'pyro.*']),\n    url='http://pyro.ai',\n    author='Uber AI Labs',\n    author_email='pyro@uber.com',\n    install_requires=[\n        # if you add any additional libraries, please also\n        # add them to `docs/requirements.txt`\n        'contextlib2',\n        'graphviz>=0.8',\n        # numpy is necessary for some functionality of PyTorch\n        'numpy>=1.7',\n        'opt_einsum>=2.3.2',\n        'six>=1.10.0',\n        'torch>=1.1.0',\n        'tqdm>=4.31',\n    ],\n    extras_require={\n        'extras': EXTRAS_REQUIRE,\n        'test': EXTRAS_REQUIRE + [\n            'nbval',\n            'pytest>=4.1',\n            'pytest-cov',\n            # TODO: remove once https://github.com/pyro-ppl/pyro/issues/1871\n            # is fixed.\n            'scipy>=1.1, <1.3',\n        ],\n        'profile': ['prettytable', 'pytest-benchmark', 'snakeviz'],\n        'dev': EXTRAS_REQUIRE + [\n            'flake8',\n            'isort',\n            'nbformat',\n            'nbsphinx>=0.3.2',\n            'nbstripout',\n            'nbval',\n            'pypandoc',\n            'pytest>=4.1',\n            'pytest-xdist',\n            # TODO: remove once https://github.com/pyro-ppl/pyro/issues/1871\n            # is fixed.\n            'scipy>=1.1, < 1.3',\n            'sphinx',\n            'sphinx_rtd_theme',\n            'yapf',\n        ],\n    },\n    tests_require=['flake8', 'pytest>=4.1'],\n    keywords='machine learning statistics probabilistic programming bayesian modeling pytorch',\n    license='MIT License',\n    classifiers=[\n        'Intended Audience :: Developers',\n        'Intended Audience :: Education',\n        'Intended Audience :: Science/Research',\n        'Operating System :: POSIX :: Linux',\n        'Operating System :: MacOS :: MacOS X',\n        'Programming Language :: Python :: 2.7',\n        'Programming Language :: Python :: 3.6',\n    ],\n    # yapf\n)\n", "path": "setup.py"}, {"content": "\"\"\"\nThis script generates a dataset similar to the Multi-MNIST dataset\ndescribed in [1].\n\n[1] Eslami, SM Ali, et al. \"Attend, infer, repeat: Fast scene\nunderstanding with generative models.\" Advances in Neural Information\nProcessing Systems. 2016.\n\"\"\"\n\nimport os\n\nimport numpy as np\nfrom PIL import Image\n\nfrom pyro.contrib.examples.util import get_data_loader\n\n\ndef imresize(arr, size):\n    return np.array(Image.fromarray(arr).resize(size))\n\n\ndef sample_one(canvas_size, mnist):\n    i = np.random.randint(mnist['digits'].shape[0])\n    digit = mnist['digits'][i]\n    label = mnist['labels'][i].item()\n    scale = 0.1 * np.random.randn() + 1.3\n    new_size = tuple(int(s / scale) for s in digit.shape)\n    resized = imresize(digit, new_size)\n    w = resized.shape[0]\n    assert w == resized.shape[1]\n    padding = canvas_size - w\n    pad_l = np.random.randint(0, padding)\n    pad_r = np.random.randint(0, padding)\n    pad_width = ((pad_l, padding - pad_l), (pad_r, padding - pad_r))\n    positioned = np.pad(resized, pad_width, 'constant', constant_values=0)\n    return positioned, label\n\n\ndef sample_multi(num_digits, canvas_size, mnist):\n    canvas = np.zeros((canvas_size, canvas_size))\n    labels = []\n    for _ in range(num_digits):\n        positioned_digit, label = sample_one(canvas_size, mnist)\n        canvas += positioned_digit\n        labels.append(label)\n    # Crude check for overlapping digits.\n    if np.max(canvas) > 255:\n        return sample_multi(num_digits, canvas_size, mnist)\n    else:\n        return canvas, labels\n\n\ndef mk_dataset(n, mnist, max_digits, canvas_size):\n    x = []\n    y = []\n    for _ in range(n):\n        num_digits = np.random.randint(max_digits + 1)\n        canvas, labels = sample_multi(num_digits, canvas_size, mnist)\n        x.append(canvas)\n        y.append(labels)\n    return np.array(x, dtype=np.uint8), y\n\n\ndef load_mnist(root_path):\n    loader = get_data_loader('MNIST', root_path)\n    return {\n        'digits': loader.dataset.data.cpu().numpy(),\n        'labels': loader.dataset.targets\n    }\n\n\ndef load(root_path):\n    file_path = os.path.join(root_path, 'multi_mnist_uint8.npz')\n    if os.path.exists(file_path):\n        data = np.load(file_path, allow_pickle=True)\n        return data['x'], data['y']\n    else:\n        # Set RNG to known state.\n        rng_state = np.random.get_state()\n        np.random.seed(681307)\n        mnist = load_mnist(root_path)\n        print('Generating multi-MNIST dataset...')\n        x, y = mk_dataset(60000, mnist, 2, 50)\n        # Revert RNG state.\n        np.random.set_state(rng_state)\n        # Crude checksum.\n        # assert x.sum() == 883114919, 'Did not generate the expected data.'\n        with open(file_path, 'wb') as f:\n            np.savez_compressed(f, x=x, y=y)\n        print('Done!')\n        return x, y\n", "path": "pyro/contrib/examples/multi_mnist.py"}]}