Author: cpbotha

I have prepared a simple Ansible script which will enable you to convert a clean Ubuntu 18.04 image (as supplied by Google Compute Engine or PaperSpace) into a CUDA 10, PyTorch 1.0 preview, fastai 1.0.x, miniconda3 powerhouse, ready to live the (mixed-precision!) deep learning dream.

I built this script specifically in order to be able to do mixed-precision neural network training on NVIDIA’s TensorCores. It currently makes use of the vxlabs.com build of PyTorch 1.0, because we need full CUDA 10 for the new TensorCores.

When I run this in order to configure a V100-equipped paperspace machine with 8 cores and 30GB of RAM, it takes about 13 minutes from start to finish.

Here’s a 20x sped up video showing the script doing it’s work on a GCE V100 machine, also with 8 cores and 30 GB RAM:

After running the script, you’ll be able to ssh or mosh in, type conda activate pt, and then start your NVIDIA-powered deep learning engines.

Motivation

Since that previous post on Palantir’s language server, I’ve been using Emacs far more intensively for Python coding in tmux on remote machines with GPUs for deep learning.

The interactive programming possibilities of Emacs (remember that Lisp programmers have been doing this since the 60s) make for a great development solution: I can interact with my remotely running neural network code, start a long-running training, and then detach from the running tmux. When I re-attach the next morning (or the next), I can continue interactively experimenting with the still-running Python instance, for example further fine-tuning the training.

Palantir’s Python Language Server can become sluggish at times, so I switched back to elpy which is usually quite snappy, and affords an impressive suite of code intelligence features for such a small package.

However, the elpy RPC Python process has a tendency to die quite often, and even M-x elpy-rpc-restart simply stops working at some point.

This, together with the fact that Microsoft’s own Python Language Server, the one used for both Visual Studio Code and also in Microsoft’s flagship Visual Studio IDE, has enjoyed and will continue to enjoy a far larger share of developer mindshare and attention, encouraged me to try and get this language server also working with Emacs.

This exercise cost many more hours than I was planning to spend, but everything seems to be working now.

/In this post, I will explain step-by-step how you too can enjoy the highly multi-threaded and actively developed Microsoft Python Language Server in your Emacs./

The Goal

If you follow the steps set out further down in this blog post, your Emacs too could end up looking like the one showed in the following screenshots.

LSP showing the blue documentation overlay box, with Emacs in a tmux, i.e. terminal mode, on a remote Linux machine, editing PyTorch / fastai training code.The same documentation showed locally, i.e. in GUI mode, on the macOS desktop.lsp-describe-thing-at-point on the right for more persistent documentation, blue overlay box on the left.C#’s strong multi-threading support comes in handy when parsing Python code! Ironic?

Required change to lsp-ui-doc.el

Furthermore, there seems to be an additional misunderstanding between Emacs lsp-mode and the MS PyLS with regard to the interpretation of markdown and plaintext docstrings.

Both of these issues impact the blue documentation overlay, and should be worked around by editing the lsp-ui-doc-extract function in lsp-ui-doc.el.

Right before the line with

((gethash "kind" contents)(gethash "value" contents));; MarkupContent

add the following sexp:

;; cpbotha: with numpy functions, e.g. np.array for example,;; kind=markdown and docs are in markdown, but in default;; lsp-ui-20181031 this is rendered as plaintext see;; https://microsoft.github.io/language-server-protocol/specification#markupcontent;; not only that, MS PyLS turns all spaces into &nbsp; instances,;; which we remove here this single additional cond clause fixes all;; of this for hover;; as if that was not enough: import pandas as pd - pandas is returned;; with kind plaintext but contents markdown, whereas pd is returned;; with kind markdown. fortunately, handling plaintext with the;; markdown viewer still looks good, so here we are.((member (gethash "kind" contents) '("markdown""plaintext"))(replace-regexp-in-string "&nbsp;"" "(lsp-ui-doc--extract-marked-string contents)))

Emacs configuration

Add the following to your Emacs init.el, and don’t forget to read the comments.

If you’re not yet using use-package now would be a good time to upgrade.

(use-packagelsp-mode:ensure t
:config;; change nil to 't to enable logging of packets between emacs and the LS;; this was invaluable for debugging communication with the MS Python Language Server;; and comparing this with what vs.code is doing(setq lsp-print-io nil);; lsp-ui gives us the blue documentation boxes and the sidebar info(use-packagelsp-ui:ensure t
:config(setq lsp-ui-sideline-ignore-duplicate t)(add-hook 'lsp-mode-hook 'lsp-ui-mode));; make sure we have lsp-imenu everywhere we have LSP(require 'lsp-imenu)(add-hook 'lsp-after-open-hook 'lsp-enable-imenu);; install LSP company backend for LSP-driven completion(use-packagecompany-lsp:ensure t
:config(push 'company-lsp company-backends));; dir containing Microsoft.Python.LanguageServer.dll(setq ms-pyls-dir (expand-file-name "~/build/python-language-server/output/bin/Release/"));; this gets called when we do lsp-describe-thing-at-point in lsp-methods.el;; we remove all of the "&nbsp;" entities that MS PYLS adds;; this is mostly harmless for other language servers(defunrender-markup-content(kind content)(message kind)(replace-regexp-in-string "&nbsp;"" " content))(setq lsp-render-markdown-markup-content #'render-markup-content);; it's crucial that we send the correct Python version to MS PYLS, else it returns no docs in many cases;; furthermore, we send the current Python's (can be virtualenv) sys.path as searchPaths(defunget-python-ver-and-syspath(workspace-root)"return list with pyver-string and json-encoded list of python search paths."(let((python (executable-find python-shell-interpreter))(init "from __future__ import print_function; import sys; import json;")(ver "print(\"%s.%s\" % (sys.version_info[0], sys.version_info[1]));")(sp (concat "sys.path.insert(0, '" workspace-root "'); print(json.dumps(sys.path))")))(with-temp-buffer(call-process python nil t nil "-c"(concat init ver sp))(subseq (split-string (buffer-string)"\n") 0 2))));; I based most of this on the vs.code implementation:;; https://github.com/Microsoft/vscode-python/blob/master/src/client/activation/languageServer/languageServer.ts#L219;; (it still took quite a while to get right, but here we are!)(defunms-pyls-extra-init-params(workspace)(destructuring-bind(pyver pysyspath)(get-python-ver-and-syspath (lsp--workspace-root workspace))
`(:interpreter(:properties(:InterpreterPath ,(executable-find python-shell-interpreter);; this database dir will be created if required:DatabasePath ,(expand-file-name (concat ms-pyls-dir "db/")):Version ,pyver));; preferredFormat "markdown" or "plaintext";; experiment to find what works best -- over here mostly plaintext:displayOptions(:preferredFormat"plaintext":trimDocumentationLines:json-false:maxDocumentationLineLength 0
:trimDocumentationText:json-false:maxDocumentationTextLength 0):searchPaths ,(json-read-from-string pysyspath))))(lsp-define-stdio-client lsp-python "python"
#'ffip-get-project-root-directory
`("dotnet" ,(concat ms-pyls-dir "Microsoft.Python.LanguageServer.dll")):extra-init-params #'ms-pyls-extra-init-params);; lsp-python-enable is created by macro above (add-hook 'python-mode-hook
(lambda()(lsp-python-enable)))

Conclusions

Although I would have preferred to do this with the two lsp-mode work-arounds, I am pretty satisfied with this setup.

With the number of users and development effort Microsoft’s Python Language Server has been enjoying and will probably continue to enjoy, it’s great knowing we can make use of this functionality in Emacs.

I am curious how well eglot, a smaller Emacs LSP package than lsp-mode, would do based on the integration above. (hint hint…)

Updates

2018-11-22

Uploaded new version of emacs-lisp init code with two improvements:

Thanks to reddit user cyanj for the print_function import suggestion, and commenter Erik Hetzner below for the old-style string interpolation suggestion, this setup should now also work with Python 2, in addition to 3.

The ms-pyls database directory is now created as a subdirectory of the bindir.

2018-11-20

So far, I have logged two issues, one with MS PyLS and one with lsp-mode, so that we can hopefully one day remove some of the work-arounds detailed above:

(The wheel has now been updated to the latest PyTorch 1.0 preview as of December 6, 2018.)

You’ve just received a shiny new NVIDIA Turing (RTX 2070, 2080 or 2080 Ti), or maybe even a beautiful Tesla V100, and now you would like to try out mixed precision (well mostly fp16) training on those lovely tensor cores, using PyTorch on an Ubuntu 18.04 LTS x86_64 system.

The idea is that these tensor cores chew through fp16 much faster than they do through fp32. In practice, neural networks tolerate having large parts of themselves living in fp16, although one does have to be careful with this. Furthermore, fp16 promises to save a substantial amount of graphics memory, enabling one to train bigger models.

For full fp16 support on the Turing architecture, CUDA 10 is currently the best option. Also, a number of CUDA 10 specific improvements were made to PyTorch after the 0.4.1 release.

However, PyTorch 1.0 (first release after 0.4.1) is not quite ready yet, and neither is it easy to find CUDA 10 builds of the current PyTorch 1.0 preview / PyTorch nightly.

Installing and using these packages.

After this, you will also need to download CUDNN 7.1 packages for your system from the NVIDIA Developer site. An NVIDIA developer account (free signup) is required for this. I downloaded and installed libcudnn7_7.4.1.5-1+cuda10.0_amd64.deb and libcudnn7-dev_7.4.1.5-1+cuda10.0_amd64.deb but you’ll probably only need the former.

Setup a suitable conda environment with Python 3.7. Setup and activate with something like the following:

The libraries in the wheel don’t have the conda-style relative RUNPATH correctly set, so you have to set LD_LIBRARY_PATH every time when starting your jupyter or any other Python code. This should work:

LD_LIBRARY_PATH=$CONDA_PREFIX/lib jupyter lab

You’re now good to go!

First tests of mixed precision training with fast.ai on Tesla V100.

I fired up a Google Compute Engine with Tesla V100 node in Amsterdam to check that everything works.

Below I show the MNIST example code where I tried to compare fp32 with fast.ai fp16 (well, mixed precision to be precise) training.

The simple CNN trains up to 97% accuracy in 8 seconds, which is pretty quick already, but I could not see any training speed difference between fp16 and fp32. This could very well be because the network is so tiny.

However, I could confirm that the model parameters (at the very least) were all stored in fp16 floats when using the fast.ai to_fp16() Learner method.

Over the years, I’ve built up quite a collection of notes as Org mode text files. So far, it has proven to be the most expressive and the most robust note-taking modality out of a long list of candidates that I’ve tried.

In other words, consulting one’s org mode notes database from a mobile device is painful. This should not be the case; notes should be always and instantly available, even on mobile.

In this blog post, I show you how to import your complete org mode notes database into Apple Notes, including typesetting and attachments, using the org mode publishing functionality.

To be clear: Org mode on the desktop remains my primary note-taking system. The goal of importing all of my notes into Apple Notes is only to have my personal knowledge base accessible from my mobile devices.

End result

After configuring and running org-publish, and then importing the whole directory of exported HTML files and attachments into Apple Notes on macOS, your notes will look like one of the two examples below: First macOS, then iOS on the phone.

Note the Emacs-supplied syntax highlighting, and the inline image.

If you import these to your icloud account (the default) the notes will be available on all of your iOS mobile devices.

These imported notes are fully indexed, and hence searchable from all of your devices.

An example note in Apple Notes on macOS.The same note as above, but now in Apple Notes on iOS.

org-publish configuration

In order to make this happen, we make use of the org-publish functionality. We also configure one or two Apple Notes-specific changes to improve rendering.

Add the configuration below to your init.el.

There are two publish targets: One for the org files (called pkb4000 below), and one for all of the attachments (called pkb4000-static below).

As an aside, pkb4000 is short for Personal Knowledge Base 4000. Ichose the name as a joke, as this synced directory of org mode filesfelt like just the Nth in a long series of knowledge baseiterations. Little did I know how well this one would stick.

Remember to change both the :base-directory properties to the top-level directory of your notes database. :publishing-directory is anywhere convenient where you would like to store the published HTML files and attachments.

This process can be easily repeated when you want to refresh the database on your Apple Notes, but unfortunately Notes will create a new Imported Notes N folder.

Alternatively, you can re-publish, and then import just changed HTML files one by one, after which you’ll have to move them back into the correct Apple Notes folder.

Conclusion

This solves the problem of being able to search rapidly and consult your whole org mode notes database using your iOS mobile device.

However, it does not yet solve the problem of importing Apple Notes you create on the mobile device back into Orgmode. This is something one could consider trying to solve using AppleScript.

Whatever the case may be, this is still a nice improvement over my previous workflow!

Bonus round: Convert orgmode buffer to Apple Note using AppleScript

Before I tried org-publish, I worked on some emacs-lisp and AppleScript to convert the current org mode buffer to HTML, and then to inject that into Apple Notes using Apple Script.

I am posting this here in case it might be useful to someone. However it is NOT required for the org-publish workflow described above.

This assumes that you have an orgmode folder.

Although far more humble than org-publish, this code will only create a new note if it does not exist yet. If the note already exists, it will simply update its contents to the current org file.

;; https://www.emacswiki.org/emacs/string-utils.el(defunstring-utils-escape-double-quotes(str-val)"Return STR-VAL with every double-quote escaped with backslash."(save-match-data(replace-regexp-in-string "\"""\\\\\"" str-val)))(defunstring-utils-escape-backslash(str-val)"Return STR-VAL with every backslash escaped with an additional backslash."(save-match-data(replace-regexp-in-string "\\\\""\\\\\\\\" str-val)))(setq as-tmpl "set TITLE to \"%s\"set NBODY to \"%s\"tell application \"Notes\" tell folder \"orgmode\" if not (note named TITLE exists) then make new note with properties {name:TITLE} end if set body of note TITLE to NBODY end tellend tell")(defunoan-export()(interactive)(let((title (file-name-base (buffer-file-name))))(with-current-buffer(org-export-to-buffer 'html "*orgmode-to-apple-notes*")(let((body (string-utils-escape-double-quotes
(string-utils-escape-backslash (buffer-string)))));; install title + body into template above and send to notes(do-applescript (format as-tmpl title body));; get rid of temp orgmode-to-apple-notes buffer(kill-buffer)))))

Emacs configuration

Add the following to your Emacs init.el, and don’t forget to read the comments.

If you’re not yet using use-package now would be a good time to upgrade.

(use-packagelsp-mode:ensure t
:config;; make sure we have lsp-imenu everywhere we have LSP(require 'lsp-imenu)(add-hook 'lsp-after-open-hook 'lsp-enable-imenu);; get lsp-python-enable defined;; NB: use either projectile-project-root or ffip-get-project-root-directory;; or any other function that can be used to find the root directory of a project(lsp-define-stdio-client lsp-python "python"
#'projectile-project-root
'("pyls"));; make sure this is activated when python-mode is activated;; lsp-python-enable is created by macro above (add-hook 'python-mode-hook
(lambda()(lsp-python-enable)));; lsp extras(use-packagelsp-ui:ensure t
:config(setq lsp-ui-sideline-ignore-duplicate t)(add-hook 'lsp-mode-hook 'lsp-ui-mode))(use-packagecompany-lsp:config(push 'company-lsp company-backends));; NB: only required if you prefer flake8 instead of the default;; send pyls config via lsp-after-initialize-hook -- harmless for;; other servers due to pyls key, but would prefer only sending this;; when pyls gets initialised (:initialize function in;; lsp-define-stdio-client is invoked too early (before server;; start)) -- cpbotha(defunlsp-set-cfg()(let((lsp-cfg `(:pyls(:configurationSources("flake8")))));; TODO: check lsp--cur-workspace here to decide per server / project(lsp--set-configuration lsp-cfg)))(add-hook 'lsp-after-initialize-hook 'lsp-set-cfg))

Putting it all together

Importantly, use pyvenv or something similar to switch to the relevant virtualenv before opening the first Python file.

When you open the file, the pyls should be automatically started up, and you can edit away with LSP-powered code intelligence.

This often gives better and more detailed results than elpy, probably because pyls uses a mix of static and dynamic (introspection-based) analysis.

Furthermore, the handling of LSP servers in Emacs can be unified, giving the same consistent level of support across a whole range of programming languages.