Year: 2017

I have recently become fascinated with (Variational) Autoencoders and with PyTorch.

Kevin Frans has a beautiful blog post online explaining variational autoencoders, with examples in TensorFlow and, importantly, with cat pictures. Jaan Altosaar’s blog post takes an even deeper look at VAEs from both the deep learning perspective and the perspective of graphical models. Both of these posts, as well as Diederik Kingma’s original 2014 paperAuto-Encoding Variational Bayes, are more than worth your time.

In my case, I wanted to understand VAEs from the perspective of a PyTorch implementation. I started with the VAE example on the PyTorch github, adding explanatory comments and Python type annotations as I was working my way through it.

This post summarises my understanding, and contains my commented and annotated version of the PyTorch VAE example. I hope it helps!

What is PyTorch?

PyTorch is FAIR’s (that’s Facebook AI Research) Python dynamic deep learning / neural network library. The way that FAIR has managed to make neural network experimentation so dynamic and so natural is nothing short of miraculous. Read this post by fast.ai to find out more about their reasons for excitement, many of which I share.

What is an autoencoder?

The general idea of the autoencoder (AE) is to squeeze information through a narrow bottleneck between the mirrored encoder (input) and decoder (output) parts of a neural network. (see the diagram below)

Because the network achitecture and loss function are setup so that the output tries to emulate the input, the network has to learn how to encode input data on the very limited space represented by the bottleneck.

What is a variational autoencoder?

Variational Autoencoders, or VAEs, are an extension of AEs that additionally force the network to ensure that samples are normally distributed over the space represented by the bottleneck.

They do this by having the encoder output two n-dimensional (where n is the number of dimensions in the latent space) vectors representing the mean and the standard devation. These Gaussians are sampled, and the samples are sent through the decoder. This is the reparameterization step, also see my comments in the reparameterize() function.

What a fabulous trick!

The loss function has a term for input-output similarity, and, importantly, it has a second term that uses the Kullback–Leibler divergence to test how close the learned Gaussians are to unit Gaussians.

In other words, this extension to AEs enables us to derive Gaussian distributed latent spaces from arbitrary data. Given for example a large set of shapes, the latest space would be a high-dimensional space where each shape is represented by a single point, and the points would be normally distributed over all dimensions. With this one can represent existing shapes, but one can also synthesise completely new and plausible shapes by sampling points in latent space.

Results using MNIST

Below you see 64 random samples of a two-dimensional latent space of MNIST digits that I made with the example below, with ZDIMS=2.

Next is the reconstruction of 8 random unseen test digits via a more reasonable 20-dimensional latent space. Keep in mind that the VAE has learned a 20-dimensional normal distribution for any input digit, from which samples are drawn that reconstruct via the decoder to output that appear similar to the input.

A diagram of a simple VAE

An example VAE, incidentally also the one implemented in the PyTorch code below, looks like this:

A simple VAE implemented using PyTorch

I used PyCharm in remote interpreter mode, with the interpreter running on a machine with a CUDA-capable GPU to explore the code below. PyCharm parses the type annotations, which helps with code completion. I also made extensive use of the debugger to better understand logic flow and variable contents. (Debuggability is one of PyTorch’s strong points.)

Let me know in the comments to this post if you have any suggestions on how the code comments could be further improved.

The Problem

Recently I had to package up a wxPython and VTK-based app for standalone deployment on Windows. Because of great experience with PyInstaller, I opted to use this tool.

With the first try with the freshly built package on the deployment machine, it refused to start up due to an ImportError: DLL load failed: The specified module could not be found., and specifically with the vtk.vtkCommonCorePython.pyd Python extension DLL.

What was frustrating, is that the relevant file was definitely present and in the right place, namely the same folder as the exe file.

A test app that imports only wx(4.0.0rc) and vtk(8.0.1) generated the following traceback:

However, using the same invocation on the offending PYD would still raise an error. By the way, I had to disable PyInstaller’s silly exceptions, because they masked the underlying OSError exception.

Great deal of good that did me, because Windows 10 gets me no additional information other than reporting “error 126” on the top-level DLL. Why can’t such a mature system not offer a little more guidance?

(Pdb) ctypes.WinDLL("vtk.vtkCommonCorePython.pyd")
>>> OSError: [WinError 126] The specified module could not be found
(Pdb) ctypes.WinDLL("C:\\Users\\cpbotha\\Downloads\\t1\\vtk.vtkCommonCorePython.pyd")
>>> OSError: [WinError 126] The specified module could not be found
(Pdb)import os
(Pdb) os.path.exists("C:\\Users\\cpbotha\\Downloads\\t1\\vtk.vtkCommonCorePython.pyd")True(Pdb) ctypes.WinDLL("vtkCommonCorePython.pyd")
>>> OSError: [WinError 126] The specified module could not be found
(Pdb) os.path.exists("vtkCommonCorePython.pyd")True

I did spend more time than I should have in pdb tracing through the whole complicated PyInstaller and Python import code innards. The fact that some PYDs loaded and some did not should have more quickly pushed me in the direction of nested dependencies.

Seeing the light with lucasg’s Dependencies

Although I had at an earlier stage checked DLL loading first with Dependency Walker (this gets very confused by the new Windows api-ms-win-* DLLs) and later with lucasg’s improved utility, I did not drill down far enough into the dependency tree.

It’s important to keep on drilling down until you see missing DLLs, the application won’t automatically traverse the tree.

Anyways, drilling down from the offending vtk.vtkCommonCorePython.pyd soon enough led me to the culprit: The Intel Threading Building Blocks (TBB) DLL conda package I was using was accidentally built in debug mode, and the debug runtimes it relied one were obviously not being deployed:

After switching to a TBB conda package from a different channel, the app was finally able to start up and run on the deployment machine.

Note that we copy the json file into our local jupyter runtime directory, which will create the ssh connection file there, and enable us to reference it by name.json only (vs its full path) in any ob-ipython source code blocks.

Now you can open ob-ipython org-babel source blocks which will connect to the remote kernel. They start like this:

TL;DR: Parallels Desktop 13 only supports OpenGL 3.2 on an extremely limited subset of mostly games. VMWare Fusion 10 has full OpenGL 3.3 support. In my case, this made the difference between being able to work on a VTK-based client project (VMWare Fusion 👍👍) or NOT being able to work the project (Parallels 👎👎).

I bought a Parallels Desktop Pro 13 subscription to be able to do Linux and Windows development on my MacBook Pro.

Although PD is extremely well done otherwise, they seem to have been dragging their feet with rolling out full OpenGL 3.2 support, as can be seen in a number of threads on their forums, e.g. here, here and here.

For a client project, we are currently working on a cross-platform VTK-based app which targets Windows as its main platform. I was looking forward to using my Parallels Windows 10 guest to test the prototype out. Unfortunately, when trying to run a simple VTK sample I was greeted with this error message:

Warning: In ..\Rendering\OpenGL2\vtkOpenGLRenderWindow.cxx, line 647
vtkWin32OpenGLRenderWindow (0000018AAABA44B0): VTK is designed to work
with OpenGL version 3.2 but it appears it has been given a context
that does not support 3.2. VTK will run in a compatibility mode
designed to work with earlier versions of OpenGL but some features may
not work.

The app then reproducibly crashes hard.

Further investigation with the OpenGL Extension Viewer showed that there were three different OpenGL renderers: Two of them are OpenGL 2.1 capable, and one is 3.2 capable. However, as a user, you can’t decide which app gets which renderer.

Further digging, also with the glewinfo app, reveals that Parallels only very selectively supports certain games and apps. See the list at the end of this knowledge base article.

I logged a support issue re the VTK 7 and later OpenGL 3.2+ requirement. The bug was acknowledged, and Parallels confirmed that it was now on their backlog, but that they could give no indication of when this would be available.

Client projects really can’t wait for this, so based on good reviews of the OpenGL support in VMWare Fusion 10, I made use of their Cyber Monday special to purchase a license for the Pro version.

After installation, I imported the VM from Parallels Desktop:

… after which I was greeted with the VM configuration screen where I could configure the 3D support:

After which I could boot up the same Windows VM and run the VTK sample app without any issues whatsoever:

So there you go: If you need good OpenGL support in your VMs, prefer VMWare Fusion over Parallels Desktop.

ob-ipython is an Emacs package that enables org-babel to talk to a running ipython kernel. The upshot of this is that you can use org-mode instead of the jupyter notebook for interspersing executable code, results and documentation.

You could also use ein for this, but then you would have to give up org-mode.

As I was testing ob-ipython yesterday, I noticed that its company-backend (completion system for Emacs) doc-buffer support was absent. Usually, as you’re exploring possible code completions, you can press <f1> or C-h to show help on the currently highlighted completion candidate.

Fast-forward an hour or two of Emacs Lisp surgery, and I was able to hook up the ob-ipython company-mode backend to ob-ipython’s inspection facility. Now pressing C-h gets you detailed help in a company-documentation buffer!

Here is my github pull request, and here is a screenshot of the company-mode ob-ipython documentation in action:

Hopefully this will be merged soon so it can find its way onto the Melpa package archives.

Here’s a bonus screenshot showing the ob-ipython notes from my org-mode journal where you can see embedded Python code that has been executed via the connected ipython kernel, with the resultant SVG format plot embedded and displayed inline:

P.S. I am currently disabling elpy-mode when the ob-ipython minor mode is active, until I figure out a better solution to elpy interfering with ob-ipython.

(use-packageob-ipython:config;; for now I am disabling elpy only ob-ipython minor mode;; what we should actually do, is just to ensure that;; ob-ipython's company backend comes before elpy's (TODO)(add-hook 'ob-ipython-mode-hookp
(lambda()(elpy-mode 0)(company-mode 1)))(add-to-list 'company-backends 'company-ob-ipython)(add-to-list 'org-latex-minted-langs '(ipython "python")))