Python始めて1週間程度の素人がDeepSeek-OCRを使ってみたときのメモ

Last Updated on 2025年11月4日 by num46

DeepSeek-OCRがすごいっぽいのでどんなものなのか試しで使ってみることにした。

DeepSeek-OCR
https://huggingface.co/deepseek-ai/DeepSeek-OCR
https://github.com/deepseek-ai/DeepSeek-OCR

Windows 11とUbuntu 24.04で試したが、結果、Windows 11はGPUではなくCPUを使った計算になり、Ubuntu 24.04はCUDA11.8が入らず断念。Ubuntuは24.04ではなく22.04にしないとだめかもしれない。

また、過去ログから思い出して書いてるので間違ってたりちぐはぐな部分があります。

Windows 11とUbuntu 24.04のデュアルブート。

参考

世界が注目するDeepSeek-OCRとは?単なる文字起こしAIではない理由
https://note.com/masa_wunder/n/n7f361aa17128

Python入門:始める準備をする(WinとMac)
https://gammasoft.jp/blog/python-install-and-code-run/

GPUの型番にあったCUDAバージョンの選び方
https://zenn.dev/yumizz/articles/73d6c7d1085d2f

CUDA
https://en.wikipedia.org/wiki/CUDA

CUDA Toolkit Archive
https://developer.nvidia.com/cuda-toolkit-archive

CUDA Toolkit 11.8 Downloads
https://developer.nvidia.com/cuda-11-8-0-download-archive

pipでPILインストール
https://qiita.com/7280ayubihs/items/13486f7689dc50480949

DeepSeek-OCRにはHugging FaceとGitHub版があり

Hugging Face: モデルやデモが公開されており、手軽に試すことができます。

GitHub: ソースコードが公開されており、より詳細な実装を確認したり、自身のプロジェクトに組み込んだりすることが可能です。

世界が注目するDeepSeek-OCRとは?単なる文字起こしAIではない理由
https://note.com/masa_wunder/n/n7f361aa17128

とのこと。

ということで手軽に試すことができるHugging Faceで試してみる。

https://huggingface.co/deepseek-ai/DeepSeek-OCRを見ると

Usage
Inference using Huggingface transformers on NVIDIA GPUs. Requirements tested on python 3.12.9 + CUDA11.8:

とあるのでとりあえずpython 3.12.9をインストールする。

https://www.python.org/downloads/release/python-3129よりWindows installer (64-bit)を選択してインストールする。

インストールは

Python入門:始める準備をする(WinとMac)
https://gammasoft.jp/blog/python-install-and-code-run/

を見ながら進めた。

以下のようにインストーラーが起動するので、「Use admin privileges when installing py.exe」だけチェックした状態で、「Install Now」の部分をクリックします。

「Add python.exe to PATH」はチェックしないでください
ここをチェックするのは、コマンドプロンプトでPythonコマンドを利用したい場合だけにしてください。最近ではpyコマンド(py.exe:Pythonランチャー)の方が、バージョンの切り替えが出来るなど、使い勝手が良い場合が多いです。逆に、ここをチェックしてパスが通ると混同する場合もあるので、ここはチェックしないでください(デフォルトもチェックなしになっています)。

Python入門:始める準備をする(WinとMac)
https://gammasoft.jp/blog/python-install-and-code-run/

とのこと。環境変数に追加されるよりはされない方がめんどくさくなさそうで良さそうなのでAdd python.exe to PATHにはチェックを入れずにインストール。

画像のようにチェックを入れた。
インストール完了。Closeを押す。

GPUの型番にあったCUDAバージョンの選び方
https://zenn.dev/yumizz/articles/73d6c7d1085d2f

を参考に使用するPCがCUDA11.8が対応しているか調べる。

https://en.wikipedia.org/wiki/CUDAからGTX 1650のMobileを探す。Mobileは無かったがCompute capability (version)は7.5、Micro-architectureはTuringということを確認。

TuringはCUDA11.8に対応していることを確認。

CUDAをhttps://developer.nvidia.com/cuda-11-8-0-download-archiveからインストールする。画像のような感じで選択してexeファイルをダウンロード、実行。

適当にインストールする。

VSCodeも適当にインストール。なくてもいいがあった方が便利。

C:\Python\DeepSeek-OCRTest1のようにフォルダ作成。コマンドプロンプトを開き、cd c:\python\DeepSeek-OCRTest1と実行。次に仮想環境を作る。python -m venv venvだとPythonとしか表示されないのでpy -m venv venvを実行。多分Add python.exe to PATHにチェックを入れなかったからだと思われる。他のサイトの参考の際はpython~と書いているコマンドはpy~に置き換えて読む。

torch==2.6.0
transformers==4.46.3
tokenizers==0.20.3
einops
addict
easydict
pip install flash-attn==2.7.3 –no-build-isolation

DeepSeek-OCR
https://huggingface.co/deepseek-ai/DeepSeek-OCR

とのことなのでこれらをインストールする。

ここからvenv\Scripts\activateで仮想環境に入る必要があるのだが忘れて仮想環境に入らず色々Pythonパッケージのインストールをしてしまった。

通常はvenv\Scripts\activateを実行して仮想環境に入ってからパッケージをインストールする。

pip install torch==2.6.0 transformers==4.46.3 tokenizers==0.20.3 einops addict easydictを実行すると

'pip' は、内部コマンドまたは外部コマンド、
操作可能なプログラムまたはバッチ ファイルとして認識されていません。

とのことなのでpy -m pip install torch==2.6.0 transformers==4.46.3 tokenizers==0.20.3 einops addict easydictを実行。

      FileNotFoundError: [WinError 2] 指定されたファイルが見つかりません。
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.

[notice] A new release of pip is available: 24.3.1 -> 25.3
[notice] To update, run: C:\Users\Y\AppData\Local\Programs\Python\Python312\python.exe -m pip install --upgrade pip
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

というエラーが出たが気にせずpy -m pip install flash-attn==2.7.3 –no-build-isolation実行。

      FileNotFoundError: [WinError 2] 指定されたファイルが見つかりません。
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.

[notice] A new release of pip is available: 24.3.1 -> 25.3
[notice] To update, run: C:\Users\Y\AppData\Local\Programs\Python\Python312\python.exe -m pip install --upgrade pip
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

というエラーが出た。気にせず続ける。

https://huggingface.co/deepseek-ai/DeepSeek-OCRからコードをもらう。

from transformers import AutoModel, AutoTokenizer
import torch
import os
os.environ["CUDA_VISIBLE_DEVICES"] = '0'
model_name = 'deepseek-ai/DeepSeek-OCR'

tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
model = AutoModel.from_pretrained(model_name, _attn_implementation='flash_attention_2', trust_remote_code=True, use_safetensors=True)
model = model.eval().cuda().to(torch.bfloat16)

# prompt = "<image>\nFree OCR. "
prompt = "<image>\n<|grounding|>Convert the document to markdown. "
image_file = 'your_image.jpg'
output_path = 'your/output/dir'

# infer(self, tokenizer, prompt='', image_file='', output_path = ' ', base_size = 1024, image_size = 640, crop_mode = True, test_compress = False, save_results = False):

# Tiny: base_size = 512, image_size = 512, crop_mode = False
# Small: base_size = 640, image_size = 640, crop_mode = False
# Base: base_size = 1024, image_size = 1024, crop_mode = False
# Large: base_size = 1280, image_size = 1280, crop_mode = False

# Gundam: base_size = 1024, image_size = 640, crop_mode = True

res = model.infer(tokenizer, prompt=prompt, image_file=image_file, output_path = output_path, base_size = 1024, image_size = 640, crop_mode=True, save_results = True, test_compress = True)

をDeepSeek-OCRTest1.pyとしてDeepSeek-OCRTest1に保存。py -m DeepSeek-OCRTest1.pyを実行。

ImportError: This modeling file requires the following packages that were not found in your environment: PIL, torchvision. Run pip install PIL torchvision

PILとtorchvisionないよというエラーが出たのでpy -m pip install PIL torchvisionを実行。

ERROR: Could not find a version that satisfies the requirement PIL (from versions: none)

[notice] A new release of pip is available: 24.3.1 -> 25.3
[notice] To update, run: C:\Users\(ユーザー名)\AppData\Local\Programs\Python\Python312\python.exe -m pip install --upgrade pip
ERROR: No matching distribution found for PIL

ということでPILはないよというエラー。

ダメだった。
$ sudo pip install pil

インストールできた。
$ sudo pip install pillow

pipでPILインストール
https://qiita.com/7280ayubihs/items/13486f7689dc50480949

ということでpilでなくpillowでインストールする。py -m pip install torchvisionを実行した後py -m pip install pillowを実行。

再度py -m DeepSeek-OCRTest1.pyを実行すると

. Make sure to double-check they do not contain any added malicious code. To avoid downloading new versions of the code file, you can pin a revision.
You are using a model of type deepseek_vl_v2 to instantiate a model of type DeepseekOCR. This is not supported for all configurations of models and can yield errors.
model.safetensors.index.json: 247kB [00:00, ?B/s]
Downloading shards:   0%|                                                                        | 0/1 [00:00<?, ?it/s]Xet Storage is enabled for this repo,

色々ダウンロードされ最後にこのような表示になった。

ここで仮想環境に入っていないことに気づきvenv\Scripts\activateを実行して仮想環境に入った。仮想環境では行頭に(venv)が表示される。pythonコマンドも使えた。

例:python -V

Python 3.12.9

python DeepSeek-OCRTest1.pyを実行すると

Traceback (most recent call last):
  File "c:\Python\DeepSeek-OCRTest1\DeepSeek-OCRTest1.py", line 1, in <module>
    from transformers import AutoModel, AutoTokenizer
ModuleNotFoundError: No module named 'transformers'

transformersないよとのエラー。pip install transformers==4.46.3を実行。

次にpip install torch==2.6.0 transformers==4.46.3 tokenizers==0.20.3 einops addict easydictの実行。

次にpip install flash-attn==2.7.3 –no-build-isolationの実行。エラーが出た。

Collecting flash-attn==2.7.3
  Using cached flash_attn-2.7.3.tar.gz (3.2 MB)
  Preparing metadata (pyproject.toml) ... error
  error: subprocess-exited-with-error

  × Preparing metadata (pyproject.toml) did not run successfully.
  │ exit code: 1
  ╰─> [25 lines of output]
      Traceback (most recent call last):
        File "c:\Python\DeepSeek-OCRTest1\venv\Lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 353, in <module>

~省略~

      FileNotFoundError: [WinError 2] 指定されたファイルが見つかりません。
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.

[notice] A new release of pip is available: 24.3.1 -> 25.3
[notice] To update, run: python.exe -m pip install --upgrade pip
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

とりあえずまっさらな状態にするためpip uninstall flash-attn -yでアンインストール。そもそもインストールされてないよと返される。

またpython DeepSeek-OCRTest1.py実行。

ImportError: This modeling file requires the following packages that were not found in your environment: PIL, torchvision. Run `pip install PIL torchvision`

PILとtorchvisionないよとのエラー。pip install pillowとpip install torchvisionを実行。その後またpython DeepSeek-OCRTest1.py実行。

ImportError: FlashAttention2 has been toggled on, but it cannot be used due to the following error: the package flash_attn seems to be not installed. Please refer to the documentation of https://huggingface.co/docs/transformers/perf_infer_gpu_one#flashattention-2 to install Flash Attention 2.

Flash Attention 2ないよと返される。

ここでChatGPTに聞いたら

このエラーは、flash-attn を Windows 環境でインストールしようとした際に発生する典型的な問題です。
結論から言うと、flash-attn は Windows ではビルド非対応のため、直接インストールできません。

らしい。また

✅ どうしても GPU 高速化を使いたい場合(上級者向け)

Windows ではなく Linux(Ubuntu)+ CUDA 対応GPU が必要です。
その場合のみ以下の手順を行います:

Linux で

pip install flash-attn==2.7.3 –no-build-isolation

が通るようになります。

Windows で GPU 高速化を試すなら、WSL2 + Ubuntu + CUDA Toolkit を使う手もあります。
ただし構築が難易度高めです。

らしい。

今回はお試しでやってみたいのでGPUでの計算をあきらめ、CPUでの計算にすることにした。

ChatGPT曰くCPUとGPUでは速度が変わるだけらしいのでお試しならまぁいいか、という感じ。

ということでChatGPTにお伺いを立てたら以下のようなGPU不使用のコードを作ってくれました

from transformers import AutoModel, AutoTokenizer
import torch
import os

os.environ["CUDA_VISIBLE_DEVICES"] = '0'
model_name = 'deepseek-ai/DeepSeek-OCR'

tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)

# flash_attention_2 を削除

device = "cuda" if torch.cuda.is_available() else "cpu"

model = AutoModel.from_pretrained(
    model_name,
    trust_remote_code=True,
    use_safetensors=True
)
model = model.eval().to(device).to(torch.bfloat16)

prompt = "<image>\n<|grounding|>Convert the document to markdown. "
image_file = 'TEST1.png'
output_path = r'C:\Python\DeepSeek-OCRTest1\output'  # ← r'' でエスケープ問題を回避

res = model.infer(
    tokenizer,
    prompt=prompt,
    image_file=image_file,
    output_path=output_path,
    base_size=1024,
    image_size=640,
    crop_mode=True,
    save_results=True,
    test_compress=True
)

これを「DeepSeek-OCRTest3.py」として実行すると

AssertionError: Torch not compiled with CUDA enabled

「アサーションエラー: Torch が CUDA 対応でコンパイルされていません」とのエラー。

その後pip install torch==2.6.0 torchvision==0.13.1 torchaudio==2.6.0のようにtorch、torchvision、torchaudioのインストールとpip uninstall torch torchvision torchaudio -yのようにtorch、torchvision、torchaudioのアンインストールを繰り返す。

色々調べたら

Installing previous versions of PyTorch
https://pytorch.org/get-started/previous-versions/

のv2.6.0内

# CUDA 11.8
pip install torch==2.6.0 torchvision==0.21.0 torchaudio==2.6.0 –index-url https://download.pytorch.org/whl/cu118

を発見。最終的に

pip uninstall torch torchvision torchaudio -y
pip cache purge
pip install torch==2.6.0 torchvision==0.21.0 torchaudio==2.6.0 --index-url https://download.pytorch.org/whl/cu118

を実行してインストール完了。(pip uninstall torch torchvision torchaudio -y、pip cache purgeはChatGPTのアドバイスを元に実行。これで多分しっかりアンインストールされるんだと思う。)

DeepSeek-OCRTest1フォルダ内にDeepSeek-OCRTest3.py、読み込み用画像TEST1.pngを準備する。

TEST1.png

python DeepSeek-OCRTest3.pyを実行する。

You are using a model of type deepseek_vl_v2 to instantiate a model of type DeepseekOCR. This is not supported for all configurations of models and can yield errors.
Some weights of DeepseekOCRForCausalLM were not initialized from the model checkpoint at deepseek-ai/DeepSeek-OCR and are newly initialized: ['model.vision_model.embeddings.position_ids']
You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
c:\Python\DeepSeek-OCRTest1\venv\Lib\site-packages\transformers\generation\configuration_utils.py:590: UserWarning: `do_sample` is set to `False`. However, `temperature` is set to `0.0` -- this flag is only used in sample-based generation modes. You should set `do_sample=True` or unset `temperature`.
  warnings.warn(
The attention mask and the pad token id were not set. As a consequence, you may observe unexpected behavior. Please pass your input's `attention_mask` to obtain reliable results.
Setting `pad_token_id` to `eos_token_id`:None for open-end generation.
The attention mask is not set and cannot be inferred from input because pad token is same as eos token. As a consequence, you may observe unexpected behavior. Please pass your input's `attention_mask` to obtain reliable results.
The `seen_tokens` attribute is deprecated and will be removed in v4.41. Use the `cache_position` model input instead.
`get_max_cache()` is deprecated for all Cache classes. Use `get_max_cache_shape()` instead. Calling `get_max_cache()` will raise error from v4.48
=====================
BASE:  torch.Size([1, 256, 1280])
NO PATCHES
=====================
The attention layers in this model are transitioning from computing the RoPE embeddings internally through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed `position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be removed and `position_embeddings` will be mandatory.

と、いろいろ警告が出ているが動いたのでとりあえずよしとした。

結果が出力される。以下出力されたコマンドプロンプトのログ。

<|ref|>text<|/ref|><|det|>[[11, 40, 730, 150]]<|/det|>
TEST テスト めいうえお

<|ref|>text<|/ref|><|det|>[[11, 250, 190, 710]]<|/det|>
TEST
トイプ
トイプ
トイプ
トイプ
トイプ
トイト

~省略~

トイプ
トイプ
トイプ
トイ-
==================================================
image size:  (302, 184)
valid image tokens:  155
output texts tokens (valid):  375
compression ratio:  2.42
==================================================
===============save results:===============
image: 0it [00:00, ?it/s]
other: 100%|█████████████████████████████████████████████████████████████████████████████████████| 2/2 [00:00<?, ?it/s]

縦書きはちょっとおかしい結果だが横書きはほぼ問題なし。メモ帳で適当に画像作ったのがよくないのかもしれない。

また、outputフォルダが作られ、中にresult_with_boxes.jpg(認識結果の画像)、result.mmd(結果のログ)、imagesフォルダ(空)が作られる。

result_with_boxes.jpg

result.mmdは識別、出力した文字が保存されています。メモ帳等で開けます。

GPUでの計算はできなかった。CPUでの計算になる。

Hugging Faceに行ってモデルのダウンロードはしなくていい。Python実行時に自動でダウンロードされる。

やり方は

python 3.12.9、CUDA11.8をインストール。

Pythonで仮想環境作成して

pip install transformers==4.46.3 tokenizers==0.20.3 einops addict easydict
pip install pillow
pip install torch==2.6.0 torchvision==0.21.0 torchaudio==2.6.0 --index-url https://download.pytorch.org/whl/cu118

をインストール。

DeepSeek-OCRTest1フォルダ内にDeepSeek-OCRTest3.py、読み込み用画像TEST1.pngを準備してpython DeepSeek-OCRTest3.pyを実行。

初回はDeepSeek-OCRのダウンロードで時間がかかります。

読み取り結果がoutputフォルダに出力される。outputフォルダは勝手に作られます。

これで多分いけます。

参考

Ubuntu22.04へCUDA11.8環境を作る
https://note.com/teruaki_ishizaki/n/n3fa5589d0915

UbuntuでCUDAをインストールする完全ガイド【初心者向け】
https://www.linux.digibeatrix.com/development-environment-setup/install-cuda-on-ubuntu

GPUの型番にあったCUDAバージョンの選び方
https://zenn.dev/yumizz/articles/73d6c7d1085d2f

CUDA Toolkit Archive
https://developer.nvidia.com/cuda-toolkit-archive

CUDA
https://en.wikipedia.org/wiki/CUDA

build-essentialとは
https://qiita.com/h_tyokinuhata/items/431a56fb054145468c16

CUDA Toolkit 11.8 Downloads
https://developer.nvidia.com/cuda-11-8-0-download-archive

add-apt-repositoryでリポジトリの追加、削除
https://asa-hari.hatenablog.com/entry/2025/02/25/204102

CUDAとnvidiaドライバの削除する方法
https://qiita.com/not_charge/items/dce7512544a7ead04bca

Ubuntu でNVIDIAのGPUがうまく動かなくなった時の対処法【2024年12月版】
https://www.nemotos.net/?p=5565

結論から言うと失敗した。多分Ubuntu22.04でないとだめっぽい。

端末を開き、sudo apt update、sudo apt upgradeを実行。

lspci | grep -i nvidiaを実行。

01:00.0 VGA compatible controller: NVIDIA Corporation TU117M [GeForce GTX 1650 Mobile / Max-Q] (rev a1)
01:00.1 Audio device: NVIDIA Corporation Device 10fa (rev a1)

GeForce GTX 1650 Mobileということを確認。

https://en.wikipedia.org/wiki/CUDAからGTX 1650のMobileを探す。Mobileは無かったがCompute capability (version)は7.5、Micro-architectureはTuringということを確認。

TuringはCUDA11.8に対応していることを確認。

lsb_release -aを実行。

No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 24.04.3 LTS
Release: 24.04
Codename: noble

自分のUbuntuのバージョンは24.04だった

gccがインストールされているか確認のためgcc –versionを実行。

コマンド 'gcc' が見つかりません。

とのことだったのでsudo apt install build-essentialでインストール。なぜsudo apt install gccでなくsudo apt install build-essentialかというと

build-essentialとは
https://qiita.com/h_tyokinuhata/items/431a56fb054145468c16

曰く

名前の通り, 開発に必須のビルドツールを提供しているパッケージ.
gcc(GNU C Compiler)とかg++(GNU C++ Compiler), makeとかその他色々入るらしい.

とのことで便利そうだったのでこっち入れました。

まずドライバの削除をしたほうがいいとのことなのでsudo apt remove –purge -y nvidia-*、sudo apt remove –purge -y cuda-*、sudo apt autoremove -yを実行。

次にドライバのインストール。sudo ubuntu-drivers autoinstallを実行。sudo update-initramfsを実行したが

You must specify at least one of -c, -u, or -d.


Usage: update-initramfs {-c|-d|-u} [-k version] [-v] [-b directory]

Options:
 -k version	Specify kernel version or 'all'
 -c		Create a new initramfs
 -u		Update an existing initramfs
 -d		Remove an existing initramfs
 -b directory	Set alternate boot directory
 -v		Be verbose

See update-initramfs(8) for further details.

と表示され、コマンド操作が必要らしく、よくわからなかったのでスルー。

sudo /sbin/shutdown -r nowで再起動した。

ちなみにFirefox開きっぱなしで再起動するとFirefoxでセッションの復元画面が表示されたので全部閉じてから再起動すること。

nvidia-smi実行。

Ubuntu22.04へCUDA11.8環境を作る
https://note.com/teruaki_ishizaki/n/n3fa5589d0915

曰く

起動してきた後に、nvida-smiでGPUの状態出力して正常動作するか確認。ちなみにこの際に出力される CUDA Version はこのドライバがサポートしているCUDAバージョンの上限のものらしい。初見だと、CUDA入れていないのに、なんで出力されてるんだ?と思ってしまいましたが、そういうことのようです。

とのこと。

CUDAをインストールするに当たり公式の情報が一番正しいんじゃないかと思い

CUDA Toolkit 11.8 Downloads
https://developer.nvidia.com/cuda-11-8-0-download-archive

を開いて画像のように設定。Versionは24.04がなかったので22.04を選択。これからインストール手順を学ぶ。

上のコードから順に実行していく。

wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/cuda-ubuntu2204.pin

sudo mv cuda-ubuntu2204.pin /etc/apt/preferences.d/cuda-repository-pin-600

wget https://developer.download.nvidia.com/compute/cuda/11.8.0/local_installers/cuda-repo-ubuntu2204-11-8-local_11.8.0-520.61.05-1_amd64.deb

を実行。

sudo cp /var/cuda-repo-ubuntu2204-11-8-local/cuda-*-keyring.gpg /usr/share/keyrings/

を実行したときに

cp: '/var/cuda-repo-ubuntu2204-11-8-local/cuda-*-keyring.gpg' を stat できません: そのようなファイルやディレクトリはありません

とのエラー。次にsudo apt-get updateを実行し、sudo apt-get -y install cudaを実行するも

E: パッケージ cuda が見つかりません

とのエラー。sudo apt -y install cuda-11-8を実行しても同様のエラーだった。

Ubuntu22.04へCUDA11.8環境を作る
https://note.com/teruaki_ishizaki/n/n3fa5589d0915

にすがりつき

sudo wget -O /etc/apt/preferences.d/cuda-repository-pin-600 https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/cuda-ubuntu2204.pin

sudo apt-key adv –fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/3bf863cc.pub

sudo add-apt-repository “deb https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/ /”

を実行。

sudo apt -y update

を実行。

sudo apt -y install cuda-11-8

を実行したときに

パッケージリストを読み込んでいます... 完了
依存関係ツリーを作成しています... 完了        
状態情報を読み取っています... 完了        
インストールすることができないパッケージがありました。おそらく、あり得
ない状況を要求したか、(不安定版ディストリビューションを使用しているの
であれば) 必要なパッケージがまだ作成されていなかったり Incoming から移
動されていないことが考えられます。
以下の情報がこの問題を解決するために役立つかもしれません:

以下のパッケージには満たせない依存関係があります:
 nsight-systems-2022.4.2 : 依存: libtinfo5 しかし、インストールすることができません
E: 問題を解決することができません。壊れた変更禁止パッケージがあります。

とのエラー。あきらめることにした。

add-apt-repositoryでリポジトリの追加、削除
https://asa-hari.hatenablog.com/entry/2025/02/25/204102

を参考に、一応sudo add-apt-repository –remove “deb https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/ /”でリポジトリの削除。

ドライバの再インストールをするためsudo apt remove –purge -y nvidia-*を実行してnVidiaドライバの削除。

sudo apt remove –purge -y cuda-*を実行すると

パッケージリストを読み込んでいます... 完了
依存関係ツリーを作成しています... 完了        
状態情報を読み取っています... 完了        
E: パッケージ cuda-repo-ubuntu2204-11-8-local_11.8.0-520.61.05-1_amd64.deb が見つかりません

とのこと。

念の為一応CUDAのアンインストール方法を調べてみる。

CUDAとnvidiaドライバの削除する方法
https://qiita.com/not_charge/items/dce7512544a7ead04bca

によると

sudo apt-get –purge remove nvidia-*
sudo apt-get –purge remove cuda-10.2
# cudaは*ではなくバージョンを打ってやらないと削除できなかった.私の場合ver10.2だったため10.2で記載している

とのこと。

Ubuntu でNVIDIAのGPUがうまく動かなくなった時の対処法【2024年12月版】
https://www.nemotos.net/?p=5565

によると

1.2. cuda-11-8のアンインストール

  • 過去の cuda-11-8 をアンインストールします。 sudo apt remove cuda-11-8
  • この後はメッセージに従って 続行しますか? [Y/n] と出たらEnterをタイプします。

2.1. cuda のアンインストール

cuda-11-8 だけでなく、cuda もアンインストールします。 sudo apt remove cuda

とのことなのでsudo apt-get –purge remove cuda-11.8、sudo apt remove cudaも一応実行しとく。

sudo apt autoremove -y、sudo ubuntu-drivers autoinstallを実行して終了とした。

CUDA11.8のインストールにはUbuntu22.04が必要っぽい。

最初はメインPCでやっていたが、CUDAのインストールを適当に最新版にするミスやPyTorchのv2.6.0をインストールするならCUDA 12.6でいいんじゃねとCUDA 12.6をインストールして推奨バージョンの11.8をインストールするまでにインストール、アンインストールを繰り返したらWindowsが壊れて自己修復する羽目になり、不動になるのが怖くなってサブPCでやりました。