2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Linux + Radeon RX 7800 XT での生成AIに関するメモ

Posted at

Radeon RX 7800 XT

Radeon RX 7800 XT 16GBが今安く売っています(2025/6/28時点で6万円台)。

Linux+7800XTでROCmやVulkanを利用して生成AIを実行してみました。まとまりのない自分用のメモですが、参考資料として公開します。

動作環境

環境 
CPU Ryzen 5600G
メモリ DDR4 3200 32GB
マザーボード Asrock B450M-HDV
グラフィックボード SAAPPHIRE PULSE AMD Radeon RX 7800 XT
OS Fedora 42(ネイティブ実行)
GPU実行環境 ROCm 6.3.1とVulkan(OS標準)

モニタリング

  • AMDGPU_TOP
    GPUの動作状況やVRAMの消費量をリアルタイムで確認できます。

スクリーンショット_20250628_163621.png

カーネルモジュールの設定

カーネル公式文書
Arch Linuxのwikiに説明があります。

ただ、電源プロファイルの変更をしても特に変化しているようには感じません。

# echo "manual" > /sys/class/drm/card0/device/power_dpm_force_performance_level
# echo "5" > /sys/class/drm/card0/device/pp_power_profile_mode

Pythonのバージョン指定

ComfyUIは標準のpython 3.13.3で動きます。他のバージョンのPythonが必要な場合、例えばpython 3.10ならば

sudo dnf install  python3.10

でインストールができ、venvで仮想環境を作る際に、

python3.10 -m venv venv

のようにすれば、仮想環境内のpythonが3.10になります。

ComfyUIでの画像生成、動画生成、音楽生成

SDXLでの画像生成、ESRGANでの画像拡大、WanVideoでの動画生成、Stable AudioやACE-Stepでの音楽生成が可能です。ただ、問題が発生することがあるので対処法について説明します。

PyTorch

ComfyUIのインストールは公式サイトの説明に従ってgitでインストールすればOKです。ただしPytorchのバージョンによっては問題が生じます。

pip3 install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/rocm6.3/

でインストールされる2.8.0devには2025/6/28時点で何か問題があるらしく、画像生成時のVAEデコードの際にVRAMが不足し(Out Of Memory, OOM)、タイルデコードになってしまう関係で生成が遅いです。

Warning: Ran out of memory when regular VAE decoding, retrying with tiled VAE decoding.

2.7.0dev版をインストールしてください。

pip3 install --pre torch==2.7.0.dev20250310+rocm6.3 torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/rocm6.3/

2.7.0dev版ならVRAM不足にならず動作します。

環境変数とコマンドラインオプション

公式サイトのROCm用TipsROCRの文書AUTOMATIC1111のIssueと、python main.py --helpの実行例より、有用そうなものを試してみました。

options:
  -h, --help            show this help message and exit
  --listen [IP]         Specify the IP address to listen on (default: 127.0.0.1). You can give a list of ip addresses by separating them with a comma like: 127.2.2.2,127.3.3.3 If --listen is provided without an argument, it defaults to 0.0.0.0,:: (listens on all ipv4
                        and ipv6)
  --port PORT           Set the listen port.
  --tls-keyfile TLS_KEYFILE
                        Path to TLS (SSL) key file. Enables TLS, makes app accessible at https://... requires --tls-certfile to function
  --tls-certfile TLS_CERTFILE
                        Path to TLS (SSL) certificate file. Enables TLS, makes app accessible at https://... requires --tls-keyfile to function
  --enable-cors-header [ORIGIN]
                        Enable CORS (Cross-Origin Resource Sharing) with optional origin or allow all with default '*'.
  --max-upload-size MAX_UPLOAD_SIZE
                        Set the maximum upload size in MB.
  --base-directory BASE_DIRECTORY
                        Set the ComfyUI base directory for models, custom_nodes, input, output, temp, and user directories.
  --extra-model-paths-config PATH [PATH ...]
                        Load one or more extra_model_paths.yaml files.
  --output-directory OUTPUT_DIRECTORY
                        Set the ComfyUI output directory. Overrides --base-directory.
  --temp-directory TEMP_DIRECTORY
                        Set the ComfyUI temp directory (default is in the ComfyUI directory). Overrides --base-directory.
  --input-directory INPUT_DIRECTORY
                        Set the ComfyUI input directory. Overrides --base-directory.
  --auto-launch         Automatically launch ComfyUI in the default browser.
  --disable-auto-launch
                        Disable auto launching the browser.
  --cuda-device DEVICE_ID
                        Set the id of the cuda device this instance will use.
  --cuda-malloc         Enable cudaMallocAsync (enabled by default for torch 2.0 and up).
  --disable-cuda-malloc
                        Disable cudaMallocAsync.
  --force-fp32          Force fp32 (If this makes your GPU work better please report it).
  --force-fp16          Force fp16.
  --fp32-unet           Run the diffusion model in fp32.
  --fp64-unet           Run the diffusion model in fp64.
  --bf16-unet           Run the diffusion model in bf16.
  --fp16-unet           Run the diffusion model in fp16
  --fp8_e4m3fn-unet     Store unet weights in fp8_e4m3fn.
  --fp8_e5m2-unet       Store unet weights in fp8_e5m2.
  --fp8_e8m0fnu-unet    Store unet weights in fp8_e8m0fnu.
  --fp16-vae            Run the VAE in fp16, might cause black images.
  --fp32-vae            Run the VAE in full precision fp32.
  --bf16-vae            Run the VAE in bf16.
  --cpu-vae             Run the VAE on the CPU.
  --fp8_e4m3fn-text-enc
                        Store text encoder weights in fp8 (e4m3fn variant).
  --fp8_e5m2-text-enc   Store text encoder weights in fp8 (e5m2 variant).
  --fp16-text-enc       Store text encoder weights in fp16.
  --fp32-text-enc       Store text encoder weights in fp32.
  --bf16-text-enc       Store text encoder weights in bf16.
  --force-channels-last
                        Force channels last format when inferencing the models.
  --directml [DIRECTML_DEVICE]
                        Use torch-directml.
  --oneapi-device-selector SELECTOR_STRING
                        Sets the oneAPI device(s) this instance will use.
  --disable-ipex-optimize
                        Disables ipex.optimize default when loading models with Intel's Extension for Pytorch.
  --supports-fp8-compute
                        ComfyUI will act like if the device supports fp8 compute.
  --preview-method [none,auto,latent2rgb,taesd]
                        Default preview method for sampler nodes.
  --preview-size PREVIEW_SIZE
                        Sets the maximum preview size for sampler nodes.
  --cache-classic       Use the old style (aggressive) caching.
  --cache-lru CACHE_LRU
                        Use LRU caching with a maximum of N node results cached. May use more RAM/VRAM.
  --cache-none          Reduced RAM/VRAM usage at the expense of executing every node for each run.
  --use-split-cross-attention
                        Use the split cross attention optimization. Ignored when xformers is used.
  --use-quad-cross-attention
                        Use the sub-quadratic cross attention optimization . Ignored when xformers is used.
  --use-pytorch-cross-attention
                        Use the new pytorch 2.0 cross attention function.
  --use-sage-attention  Use sage attention.
  --use-flash-attention
                        Use FlashAttention.
  --disable-xformers    Disable xformers.
  --force-upcast-attention
                        Force enable attention upcasting, please report if it fixes black images.
  --dont-upcast-attention
                        Disable all upcasting of attention. Should be unnecessary except for debugging.
  --gpu-only            Store and run everything (text encoders/CLIP models, etc... on the GPU).
  --highvram            By default models will be unloaded to CPU memory after being used. This option keeps them in GPU memory.
  --normalvram          Used to force normal vram use if lowvram gets automatically enabled.
  --lowvram             Split the unet in parts to use less vram.
  --novram              When lowvram isn't enough.
  --cpu                 To use the CPU for everything (slow).
  --reserve-vram RESERVE_VRAM
                        Set the amount of vram in GB you want to reserve for use by your OS/other software. By default some amount is reserved depending on your OS.
  --async-offload       Use async weight offloading.
  --default-hashing-function {md5,sha1,sha256,sha512}
                        Allows you to choose the hash function to use for duplicate filename / contents comparison. Default is sha256.
  --disable-smart-memory
                        Force ComfyUI to agressively offload to regular ram instead of keeping models in vram when it can.
  --deterministic       Make pytorch use slower deterministic algorithms when it can. Note that this might not make images deterministic in all cases.
  --fast [FAST ...]     Enable some untested and potentially quality deteriorating optimizations. --fast with no arguments enables everything. You can pass a list specific optimizations if you only want to enable specific ones. Current valid optimizations:
                        fp16_accumulation fp8_matrix_mult cublas_ops
  --mmap-torch-files    Use mmap when loading ckpt/pt files.
  --dont-print-server   Don't print server output.
  --quick-test-for-ci   Quick test for CI.
  --windows-standalone-build
                        Windows standalone build: Enable convenient things that most people using the standalone windows build will probably enjoy (like auto opening the page on startup).
  --disable-metadata    Disable saving prompt metadata in files.
  --disable-all-custom-nodes
                        Disable loading all custom nodes.
  --disable-api-nodes   Disable loading all api nodes.
  --multi-user          Enables per-user storage.
  --verbose [{DEBUG,INFO,WARNING,ERROR,CRITICAL}]
                        Set the logging level
  --log-stdout          Send normal process output to stdout instead of stderr (default).
  --front-end-version FRONT_END_VERSION
                        Specifies the version of the frontend to be used. This command needs internet connectivity to query and download available frontend implementations from GitHub releases. The version string should be in the format of:
                        [repoOwner]/[repoName]@[version] where version is one of: "latest" or a valid version number (e.g. "1.0.0")
  --front-end-root FRONT_END_ROOT
                        The local filesystem path to the directory where the frontend is located. Overrides --front-end-version.
  --user-directory USER_DIRECTORY
                        Set the ComfyUI user directory with an absolute path. Overrides --base-directory.
  --enable-compress-response-body
                        Enable compressing response body.
  --comfy-api-base COMFY_API_BASE
                        Set the base URL for the ComfyUI API. (default: https://api.comfy.org)
  --database-url DATABASE_URL
                        Specify the database URL, e.g. for an in-memory database you can use 'sqlite:///:memory:'.

環境変数

  • TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1
    問題なく動きます。
  • PYTORCH_TUNABLEOP_ENABLED=1
    遅くなる上ESRGANでの画像拡大時にエラーがでます。
  • HSA_ENABLE_SDMA=0
    GPU内蔵System DMAを無効にした方が安定するようです。無効にしても速度は特に変わりません。
  • PYTORCH_HIP_ALLOC_CONF=max_split_size_mb:256
    これを指定するとVRAMの断片化が減り、VRAM不足が減るはずです。

コマンドラインオプション

  • --use-pytorch-cross-attention
    画像生成時には問題ないですが、WanVideoでの動画生成時はVRAM不足になります。
  • --use-split-cross-attention
    必要に応じて自動でデータを分割して処理するオプションです。WanVideoのとき指定すると、VRAM不足を回避できる場合があります(指定しても長時間高解像度動画生成ではVRAM不足になりますが)。
  • --use-quad-cross-attention
    常時データを分割して処理するオプションで、VRAM不足になりにくくなりますが、処理速度が低下します。
  • --fp16-vae --force-fp16
    特に変わった感じはしません。

VRAMとCPUのオフロードに関するオプション

--highvram --gpu-only --normalvram --lowvram --novram --cpu

これらのオプションでComfyUIのVRAMのメインメモリへのオフロードやCPUへのオフロード具合を指定できます。

間違っているかもしれませんが、ComfyUIのモデル管理コードを眺めると、

VRAMの消費量:

HIGH_VRAM(--highvram, --gpu-only) > NORMAL_VRAM(--normalvram) > NORMAL_VRAM(オプション無指定) = LOW_VRAM(--lowvram) > NO_VRAM(--novram, --cpu)

CPUへのオフロード(GPUでの実行度合いが多いほど左):
HIGH_VRAM = NORMAL_VRAM > LOW_VRAM = NO_VRAM(--novram) > NO_VRAM(--cpu)

となっているようです。

オプション無指定と--normalvramについて、オプション無指定ではlowvramと同様に必要に応じて自動的にVRAMからメインメモリへのオフロードを行うようです。オプション無指定と--normalvramとで動作に違いがあるようなので気を付けてください。

オプション無指定と--lowvramについて、VRAMの扱いは同様ですが、--lowvramではテキストエンコーダーの処理をCPUにオフロードします。WanVideoでの動画生成の場合これを指定しないとKサンプラーでの動画生成時に処理が止まってしまう場合があるようです。

ComfyUIのコードの修正

ComfyUIのモデル管理コードではGPUに合わせて非常に細かいチューニングがされています。

277行目から279行目MIN_WEIGHT_MEMORY_RATIOという変数がNVIDIAのGPUでのみ0.0それ以外では0.4に設定され、629行目で使われています。

MIN_WEIGHT_MEMORY_RATIO = 0.4
if is_nvidia():
    MIN_WEIGHT_MEMORY_RATIO = 0.0
            lowvram_model_memory = max(128 * 1024 * 1024, (current_free_mem - minimum_memory_required), min(current_free_mem * MIN_WEIGHT_MEMORY_RATIO, current_free_mem - minimum_inference_memory()))

AMDのGPUでもMIN_WEIGHT_MEMORY_RATIO = 0.0に変更してみました。

MIN_WEIGHT_MEMORY_RATIO = 0.4
if is_nvidia() or is_amd():
    MIN_WEIGHT_MEMORY_RATIO = 0.0

この変更をすると、VRAM不足が多少改善するかもしれません。

実際に使っているComfyUIの起動オプション

現時点では次のオプションを指定してComfyUIを起動しています。

HSA_ENABLE_SDMA=0 TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 PYTORCH_HIP_ALLOC_CONF=max_split_size_mb:256 python main.py --use-split-cross-attention --fp16-vae --lowvram --auto-launch

音楽生成

  • stable audio
  • ACE-Step
    どちらもComfyUIで動きますが、VAEデコード時にMIOpenの警告が大量に出ます。

--cpu-vaeオプションを指定してCPUでデコードすればエラーは出ませんが、処理が遅くなります。

...
MIOpen(HIP): Warning [IsEnoughWorkspace] [GetSolutionsFallback WTI] Solver <GemmFwdRest>, workspace required: 2370830336, provided ptr: 0 size: 0
...

ComfyUI標準ノードではなくComfyUI_ACE-Stepなら問題ないです。

ただ、ComfyUI標準ノード版もComfyUI_ACE-Step版も日本語歌詞の処理に問題があるようなので(漢字を読み飛ばしたり歌詞がまざったりする)、ComfyUIではなくStandalone版で動かしたほうがいいと思います。python 3.10で正常に動きます。

音声合成

sd-scriptsによるLoRA作成

キャラや画風を追加学習してLoRAを作成できるsd-scriptsも動作します。

ただ、latent作成時にbitsandbytesが警告を出して処理が遅いので、
bitsandbytes-rocmを入れるといいです。

タグ付けはComfyUIのWD14 Taggerカスタムノードでできます。

RAdamScheduleFreeオプティマイザがよいらしいので、sd3ブランチを使用します。LoHAを使うためにlycoris_loraも入れます。

git clone https://github.com/kohya-ss/sd-scripts
cd sd-scripts
git switch sd3
pip install --pre torch==2.7.0.dev20250310+rocm6.3 torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/rocm6.3/
pip install -r requirements.txt
pip install lycoris_lora

コマンドラインで細かくオプション指定するのは面倒なので、データセット用のTOMLファイルとコマンドオプション指定用TOMLファイルを用意して実行しています。

キャラ学習用データセット用TOMLファイル例(datasetディレクトリに画像ファイルと対応するタグファイル(.txt)を入れている場合):

[general]
enable_bucket = true
resolution = 1024
batch_size = 1
bucket_no_upscale = true
max_bucket_reso = 1280
min_bucket_reso = 320
flip_aug = false
num_repeats = 1
shuffle_caption = true

[[datasets]]

  [[datasets.subsets]]
  image_dir = 'dataset'
  caption_extension = '.txt'
  class_tokens = 'キャラ名'
  keep_tokens = 2

コマンドオプション指定用TOMLファイル例(outputディレクトリに出力し、lycoris.kohyaLoHAを使用し、RAdamScheduleFreeで50エポックまで学習):

pretrained_model_name_or_path = "modelのパス"
output_dir = "./output"
output_name = "LoRAファイル名"
dataset_config = "上のデータセット用TOMLファイルのパス"

save_model_as = "safetensors"
mixed_precision= "fp16"
save_precision = "fp16"
gradient_checkpointing = true
persistent_data_loader_workers = true
max_data_loader_n_workers = 4

cache_latents_to_disk = true

network_module = "lycoris.kohya"

optimizer_type = "RAdamScheduleFree"
learning_rate = 1e-3

max_train_epochs = 50
save_every_n_epochs = 25

lr_scheduler = "cosine"
lr_scheduler_num_cycles = 1
network_dim = 16
network_alpha = 1
network_args = [ "algo=loha", "conv_dim=16", "conv_alpha=1" ]

max_token_length = 150
min_snr_gamma = 5
no_half_vae = true

accelerate configの設定は公式文書の設定そのままで大丈夫です。

- This machine
- No distributed training
- NO
- NO
- NO
- all
- fp16

sd-scriptsの実行例:

export PYTORCH_HIP_ALLOC_CONF=max_split_size_mb:256
export HSA_ENABLE_SDMA=0

accelerate launch  --num_cpu_threads_per_process 4 sdxl_train_network.py --config_file=./上のコマンドライン指定用TOMLファイル

学習画像は6~10枚程度で問題ないです。学習画像10枚では30分程度で学習できます。若干過学習気味になるので、LoRAは0.6~0.8ぐらいの強度で指定しています。

大規模言語モデル

llama.cpp のVulkan版で正常に動作します。モデルによりますが、ROCm版では-ngl 3以上にしてGPUで実行した場合に、エラーが出て落ちました。Vulkanで動かしたほうがいいようです。

うまく動かないもの

  • FramePack-eichi
    VRAM不足やメインメモリ不足が発生して動きませんでした。メインメモリが48GB以上あるなら動くかもしれません。
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?