【PyTorch】torch.utils.bottleneck実行時のUnicodeDecodeErrorの対処法 - 加賀百万石ですが何か?

【PyTorch】torch.utils.bottleneck実行時のUnicodeDecodeErrorの対処法

PyTorchではボトルネックを解析するための機能が用意されていて,↓こんな感じで簡単に使用することができます。

>python -m torch.utils.bottleneck /PATH/TO/PyTorch_SCRIPT.py

実装してみたスクリプトがやたら遅かったのでこれを使ってみようと思ったところ,PythonによくあるUnicodeDecodeErrorに遭遇したので,その対処法を残しておきます。

※原因そのものは,PyTorchやtorch.utils.bottleneckとは直接的には関係なく,他の状況でも発生するものです。

実行環境

  • Windows環境(コマンドプロンプト上で実行)
  • PyTorch==0.4.1

エラーの内容

実際に発生したエラーはこんな内容です。

>python -m torch.utils.bottleneck cnn_tutorial.py

`bottleneck` is a tool that can be used as an initial step for debugging
bottlenecks in your program.

It summarizes runs of your script with the Python profiler and PyTorch's
autograd profiler. Because your script will be profiled, please ensure that it
exits in a finite amount of time.

For more complicated uses of the profilers, please see
https://docs.python.org/3/library/profile.html and
http://pytorch.org/docs/master/autograd.html#profiler for more information.
Running environment analysis...
Traceback (most recent call last):
(中略)
    err = err.decode("ascii")
UnicodeDecodeError: 'ascii' codec can't decode byte 0x82 in position 8: ordinal not in range(128)

Pythonを使っているとUnicodeDecodeErrorはよく遭遇する割には,解決方法がパッとはなかなか分からない曲者だと思います。

エラーの原因と対処方法

エラーの原因

エラーの原因は以下の通りです。

  • Windows環境のコマンドプロンプトで実行していた
  • コマンドプロンプトの文字コードがUTF-8ではなかった

コマンドプロンプトではchcpコマンドで確認すれば分かるように,文字コードがSHIFT-JISになっています。

>chcp
現在のコード ページ: 932

932はSHIFT-JISを表していますので,これをUTF-8に変更してやれば解決です。

対処方法

以下のようにコマンドプロンプトの文字コードをUTF-8に変更します。

>chcp 65001
Active code page: 65001

これで再度ボトルネック解析のコマンドを実行すれば,エラーは解消されているはずです。

スポンサーリンク