Skip to main content

Emacs recipe for starting tensorboard server

tensorboard is a quite popular among deep learning practitioners for experiment tracking. I also use it often, but what was bothering me for a while was to start the server (using tensorboard command) on one emacs buffer every time I want to track something. It gets tedious very quickly considering restarts as well. So, I've written a tiny elisp recipe to start/restart tensorboard directly from the (Python) file buffer (python-mode) in emacs.

Here's the recipe:

;; Start tensorboard server
(defun start-tensorboard-server (&optional logdir port restart)
    "Run `tensorboard` command to start the server with input LOGDIR
    (default: `PWD/runs`) and PORT (default: 6006). If RESTART is `t`,
    any currently running instance of `tensorboard` is stopped before
    starting a new one."

    (interactive)

    (defun make-command(executable &rest args-list)
      (let* ((args-list (mapcar (lambda (arg) (concat " " arg)) args-list))
         (full-command (cons executable args-list)))
    (apply #'concat full-command)))

    ;; restart
    (when (and (boundp restart) (eq restart t))
      (with-temp-buffer
    (while (eq (shell-command (make-command "pgrep" "-f" "tensorboard")) 0)
      (shell-command (make-command "pkill" "-f" "tensorboard"))
      (sleep-for .5))))

    (let* ((logdir (if (and (boundp 'logdir) (not (eq logdir nil))) logdir "runs"))
       (logdir (if (string-prefix-p "/" logdir) logdir (concat (file-name-directory buffer-file-name) logdir )))
       (port (if (and (boundp 'port) (not (eq port nil))) port "6006"))
       (tensorboard-command (make-command "tensorboard" "--logdir" logdir "--port" port "&")))

      (if (eq (shell-command (make-command "pgrep" "-f" "tensorboard")) 1)
      (progn (message "Invoking command: \"%s\"" tensorboard-command)
         (shell-command tensorboard-command nil nil)

         (while (eq (shell-command (make-command "pgrep" "-f" "tensorboard")) 1)
           (message "%s" "Starting tensorboard server..."))

         ;; Grace period for the server to be able to accept new connections
         (sleep-for 3)
         (browse-url (concat "http://localhost:" port))

         (save-current-buffer
           (switch-to-buffer-other-window "*Async Shell Command*")
           (delete-window)))

    (message "%s" "tensorboard server is already running."))))

And, for ease of access, I've bound it to the F8 key (only applicable in the python-mode):

(global-set-key (kbd "<f8>")
        (lambda () (interactive)
          (when (eq major-mode 'python-mode)(start-tensorboard-server nil nil t))))

Comments

Comments powered by Disqus