shtaxxx日記

コンピュータアーキテクチャについて研究している研究者の日記や技術紹介

rootless (sudoなし) でdockerを動かすときはUID/GIDを指定する

ルートレス (sudoなし/rootにならずに) でdockerを動かす際に、自身のホームディレクトリ等をマウントしていると、何もケアをしないと読み書きができない。そのため、docker起動時にdockerコンテナのUIDとGIDを変更する必要がある。

docker run -it -u $(id -u):$(id -g) -v $HOME:$HOME -d --gpus all --name my_gpu_env --shm-size=4gb pytorch/pytorch:1.10.0-cuda11.3-cudnn8-devel bash

-u $(id -u):$(id -g) でUIDとGIDを上書きしている。

ちなみに、上記コンテナへのbashによるアクセスは以下の通り。(UID/GIDの件は関係ないがメモ)

docker exec -it my_gpu_env bash

Mac版PowerPointとWordにおけるAdobe Acrobat Pro 2020アドインの削除方法

Adobe Acrobat Pro 2020は、M1 (Apple Silicon) Mac用のバイナリを提供していないため、Rosetta2を介してIntel用バイナリを利用することになります。Acrobat Pro本体は特に問題ないのですが、Acrobatインストール時に(強制的に)インストールされてしまうMicrosoft PowerPointとWordのアドインが、M1 (Apple Silicon) には対応しておらず、例えばPowerPointの場合には、起動時に以下の用にVBA (Visual Basic for Applications) 関連のエラー(実行時エラー'53')が発生します。

PowerPointにおけるVBAのエラー

メニューのツールPowerPointアドインなどから一旦はアドインを削除すれば良さそうなのですが、PowerPointを再起動するとゾンビのように復活してしまいます。どうやら、PowerPointやWordの起動時に自動的にアドインを追加するようになっているようです(やめて欲しい)。

永久的にAcrobatアドインを削除するために、スタートアップ時に読み込まれるファイル自体を削除してしまいましょう。

Wordの場合には、

~/Library/Group Containers/UBF8T346G9.Office/User Content.localized/Startup.localized/Word/linkCreation.dotm

を削除します。

PowerPointの場合には、

~/Library/Group Containers/UBF8T346G9.Office/User Content.localized/Startup.localized/PowerPoint/SaveAsAdobePDF.ppam

を削除します。

rmコマンドで削除する場合には、空白をエスケープしましょう。

rm -f ~/Library/Group\ Containers/UBF8T346G9.Office/User\ Content.localized/Startup.localized/Word/linkCreation.dotm
rm -f ~/Library/Group\ Containers/UBF8T346G9.Office/User\ Content.localized/Startup.localized/PowerPoint/SaveAsAdobePDF.ppam

これで二度とAcrobatのアドインが復活することはないでしょう。

macOS Mojave (10.14.4) 向けにEmacsを野良ビルドする際にxml.cでエラーとなる場合の対処法

新しいEmacsのバージョンが出るといつも、こちらを参考に、インラインパッチを当てて野良ビルドをしているのだが、今回は、Emacs 26.2のビルド中に、"xml.c:23:10: fatal error: 'libxml/tree.h' file not found"とエラーが出てビルドができなかった。以前は"xcode-select --install"でCommand Line Toolsをインストールしておけば大丈夫だったはずだが、再インストールしても直らないので、ちょっと手こずった。

解決策は、ここを参考に、Command Line Toolsのをヘッダーファイルをインストールすればよい。

open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg

KLダイバージェンスを用いた異なる量子化パラメータの比較

NVIDIAのINT8量子化では、 KL Divergenceを使って活性値の分布をより正確に近似できる量子化パラメータ(最大値と最小値)を探索しているらしいので、それを実装してみた。

量子化前後でヒストグラムのビンの幅が異なるので、そのままではKLダイバージェンスの計算ができない。そこで、量子化後のヒストグラム量子化前のビンの幅を使ったヒストグラムに変換して、KLダイバージェンスを計算することにした。

以下の例だと、q1はq2はそれぞれ(-20.0, 20.0)と(-7.0, 7.0)という異なる最小値・最大値でクリップするようにしており、16個のビンでヒストグラムを作る(=4ビット量子化)場合にどちらが良いかをKL-divで判定する。 この場合、q1よりもq2の方がKL-divが小さく、元の分布を正確に表現できることがわかる。

from __future__ import absolute_import
from __future__ import print_function

import matplotlib.pyplot as plt
import numpy as np

N = 1000 * 1000
loc = 0
scale = 2
epsilon = 0.00001

ref_num_bins = 1024
q_num_bins = 16

dist = np.random.normal(loc, scale, N)
q1_dist = np.clip(dist, -20.0, 20.0)
q2_dist = np.clip(dist, -7.0, 7.0)

ref_hist, ref_bins = np.histogram(dist, bins=ref_num_bins, density=True)
q1_hist, q1_bins = np.histogram(q1_dist, bins=q_num_bins, density=True)
q2_hist, q2_bins = np.histogram(q2_dist, bins=q_num_bins, density=True)


def to_hist_with_orig_bins(targ_hist, targ_bins, orig_hist, orig_bins):
    targ_v = 0.0
    targ_i = 0
    targ_bin = targ_bins[0]
    ret_hist = np.zeros_like(orig_hist)

    for i, orig_bin in enumerate(orig_bins[:-1]):
        if targ_bin <= orig_bin:
            if targ_i < len(targ_bins) - 1:
                targ_v = targ_hist[targ_i]
                targ_i += 1
                targ_bin = targ_bins[targ_i]
            else:
                targ_v = 0.0
                targ_bin = orig_bin.max() + 1.0

        ret_hist[i] = targ_v

    return ret_hist


c_q1_hist = to_hist_with_orig_bins(q1_hist, q1_bins, ref_hist, ref_bins)
c_q2_hist = to_hist_with_orig_bins(q2_hist, q2_bins, ref_hist, ref_bins)

pad_ref_bins = np.pad(ref_bins, [1, 0], 'constant')
sumd = np.sum((ref_bins - pad_ref_bins[:-1])[1:])


ref_hist = (ref_hist + epsilon) / (1.0 + epsilon * sumd)
c_q1_hist = (c_q1_hist + epsilon) / (1.0 + epsilon * sumd)
c_q2_hist = (c_q2_hist + epsilon) / (1.0 + epsilon * sumd)

kl_ref = np.sum(ref_hist * np.log(ref_hist / ref_hist))
kl_c_q1 = np.sum(ref_hist * np.log(ref_hist / c_q1_hist))
kl_c_q2 = np.sum(ref_hist * np.log(ref_hist / c_q2_hist))


def to_labels(bins):
    labels = []
    for i in range(len(bins) - 1):
        labels.append((bins[i] + bins[i + 1]) / 2)
    return labels


ref_labels = to_labels(ref_bins)
q1_labels = to_labels(q1_bins)
q2_labels = to_labels(q2_bins)

plt.figure(figsize=(10, 5))

#plt.bar(ref_labels, ref_hist, label='ref')

plt.plot(ref_labels, ref_hist, label='ref')
plt.plot(q1_labels, q1_hist, label='q1')
plt.plot(q2_labels, q2_hist, label='q2')

plt.plot(ref_labels, c_q1_hist, label='q1 KL=%f' % kl_c_q1)
plt.plot(ref_labels, c_q2_hist, label='q2 KL=%f' % kl_c_q2)

plt.legend(title='histogram', loc='best')
plt.grid()

# plt.show()
plt.savefig('out.png')

https://gist.github.com/shtaxxx/6ca20df2cb7933291fdb9cb02ccf2088

f:id:sxhxtxa:20190422121826p:plain

参考

https://paper.hatenadiary.jp/entry/2018/10/13/164539

macOS Sierra上のMicrosoft Office各種でEmacsキーバインドを使う

macOS Sierraでは(現状)Karabinerが動作しないため,標準でEmacsキーバインドが利用できないアプリケーションにもEmacsキーバインドを割り当てることができずに困っていた.英かなでもキーバインドの変更が可能であるが,一部のアプリケーションでは一部のキーバインドを無効にしたい場合には対応していないため,Hammerspoonを使ってみた.


下記の記事に倣って,Hammerspoonをインストールし,.hammerspoon/init.luaを書いた.

qiita.com

自分の設定ファイルは以下の通りである. Word,ExcelPowerPointだけで良かったのだが,面倒だったので,アプリケーション名がMicrosoftを含むとき時だけアクティブになるように設定した. その他のアプリケーションでも同様の方法で設定できるはず.

local function keyCode(key, modifiers)
   modifiers = modifiers or {}
   return function()
      hs.eventtap.event.newKeyEvent(modifiers, string.lower(key), true):post()
      hs.timer.usleep(1000)
      hs.eventtap.event.newKeyEvent(modifiers, string.lower(key), false):post()      
   end
end

local function remapKey(modifiers, key, keyCode)
   hs.hotkey.bind(modifiers, key, keyCode, nil, keyCode)
end

local function disableAllHotkeys()
   for k, v in pairs(hs.hotkey.getHotkeys()) do
      v['_hk']:disable()
   end
end

local function enableAllHotkeys()
   for k, v in pairs(hs.hotkey.getHotkeys()) do
      v['_hk']:enable()
   end
end

local function handleGlobalAppEvent(name, event, app)
   if event == hs.application.watcher.activated then
      -- hs.alert.show(name)
      -- if name == "Microsoft Word" then
      if string.find(name, "Microsoft") then
         enableAllHotkeys()
      else
         disableAllHotkeys()
      end
   end
end

appsWatcher = hs.application.watcher.new(handleGlobalAppEvent)
appsWatcher:start()

remapKey({'ctrl'}, 'p', keyCode('up'))
remapKey({'ctrl'}, 'n', keyCode('down'))
remapKey({'ctrl'}, 'b', keyCode('left'))
remapKey({'ctrl'}, 'f', keyCode('right'))

remapKey({'ctrl'}, 'a', keyCode('home'))
remapKey({'ctrl'}, 'e', keyCode('end'))

remapKey({'ctrl'}, 'h', keyCode('delete')) -- backspace
remapKey({'ctrl'}, 'd', keyCode('forwarddelete')) -- delete

remapKey({'alt'}, 'w', keyCode('c', {'cmd'})) -- copy
remapKey({'ctrl'}, 'w', keyCode('x', {'cmd'})) -- cut
remapKey({'ctrl'}, 'y', keyCode('v', {'cmd'})) -- paste

Mac上のemacsでauto-complete-clang-asyncを使う

Emacsc/c++の補完をするためにauto-complete-clang-asyncを使うことにしました. 以下はその設定時のメモ.

Homebrewでemacs-clang-complete-asyncをインストールする

brew install emacs-clang-complete-async 

emacsでauto-complete-clang-asyncをインストールする

僕はpackage.elで自動インストールするように管理しています. 手動の場合には,"M-x package-list-packages" でpackage一覧を表示してからauto-complete-clang-asyncを指定すればインストールできるのでしょうか. 自動でパッケージをインストールする方法はコードを参照.

github.com

emacsのinit.elとかに設定を書く

僕はinit-loaderで設定を分けて管理しています.

20-auto-complete.el

(require 'auto-complete)
(require 'auto-complete-config)
(ac-config-default)
(global-auto-complete-mode t)

70-cc-mode.el

(autoload 'google-c-style "google-c-style" nil t)
(add-hook 'c-mode-common-hook 'google-set-c-style)
(add-hook 'c++-mode-common-hook 'google-set-c-style)
(add-hook 'c-mode-common-hook 'google-make-newline-indent)

(add-hook 'c-mode-common-hook
          '(lambda()
             (setq ac-clang-complete-executable "clang-complete")
             (when (executable-find ac-clang-complete-executable)
               (require 'auto-complete-clang-async)
               (setq ac-sources '(ac-source-clang-async))
               (ac-clang-launch-completion-process))))

設定一式

GitHubにアップロードしてあるのでそちらを参照してください.

github.com

Debian Linux on Zynq Setup Flow (for Vivado 2015.4)

Xilinx Zynq(ARM搭載FPGA)の上でDebian Linux(8.0 Jessie)を動作させるためのチュートリアルを作りました。Slideshareからどうぞ。

以下の手順で専用ハードウェア(といってもチュートリアルではGPIOのみ)をLinux経由で制御するHW/SW協調システムを開発します。

  • Zybo用FPGAボード設定ファイルの追加
  • Vivadoを用いたハードウェア開発
  • U-boot SPLとU-bootの生成
  • Linuxカーネルとデバイスツリーのカスタマイズと生成
  • Debianルートファイルシステムの構築
  • SDカードの準備
  • SDカードからの起動と初期設定
  • CMA (Continuous Memory Allocator)ドライバーのインストール
  • テストアプリケーションの実行
  • ビットファイルの変更方法

www.slideshare.net

アドバイス・コメント等がありましたらお知らせ頂けますと助かります。