0
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?

共有 GPU メモリの検証コード

0
Last updated at Posted at 2023-08-30

Stable Diffusion WebUI AUTIMATIC1111 で共有メモリ

というコメントが GitHub に上がっているのをみて、
そもそも
Windows(WSL2)
+ CUDA
+ Python
+ PyTorch
で共有メモリは確保できるのか?
そんな疑問から 30年ぶりぐらいにコードしてみた 元assembler屋です。

参考資料は以下です。2015年ぐらいに電子書籍で買ってたら、今(2023現在)古本がすごい値上がりしてますね。

参考文献
CUDA C プロフェッショナル プログラミング

CUDA で GPU を確保 2026/10/25 20:14 修正

GPU のメモリを確保して、20秒後に開放する。
(が、しかし解放しない てきとーに Ctrl+C で終了してください)
gpumem03.cu

#include <stdio.h>
#include <cuda_runtime.h>
#include <windows.h> // Sleep() 用

// 4 GiB (4 * 1024 * 1024 * 1024 バイト)
#define VRAM_BYTES (4ULL * 1024ULL * 1024ULL * 1024ULL)

int main() {
    void *device_memory = NULL;

    printf("=== VRAM 4 GiB Allocation Test ===\n");

    // 1. VRAM 確保
    cudaError_t err = cudaMalloc(&device_memory, VRAM_BYTES);
    if (err != cudaSuccess) {
        printf("cudaMalloc failed: %s\n", cudaGetErrorString(err));
        return 1;
    }
    printf("1. Allocated 4 GiB VRAM successfully.\n");

    // 2. VRAM 初期化(0 でフィルして物理メモリを確実に割り当て)
    printf("2. Initializing VRAM (cudaMemset)... ");
    fflush(stdout);
    err = cudaMemset(device_memory, 0, VRAM_BYTES);
    if (err != cudaSuccess) {
        printf("failed: %s\n", cudaGetErrorString(err));
        cudaFree(device_memory);
        return 1;
    }
    printf("Done.\n");

    // 3. 20秒待機(タスクマネージャーでメモリ使用量を確認可能)
    printf("3. Holding VRAM for 20 seconds. Check Task Manager -> GPU Memory.\n");
    for (int sec = 20; sec > 0; sec--) {
        printf("\rRemaining time: %2d s...", sec);
        fflush(stdout);
        Sleep(1000); // 1秒スリープ
    }
    printf("\n");

    // 4. メモリ解放
    printf("4. Freeing VRAM... ");
    cudaFree(device_memory);
    printf("Done. Memory released.\n");

    return 0;
}

Python で確保

似たようなことをやる。
gpu02.py

f = open("test.txt", "w+b")

f.seek(2 * 1024 * 1024 * 1024 - 1) # 2GB - 1バイト
f.write(b"\x00")
f.flush()

import mmap
m = mmap.mmap(f.fileno(), 0)

m[0:4] = b"abcd"

print(m[0:4])

import torch # PyTorch ライブラリをインポートする
device = torch.device("cuda")
g = torch.cuda.HalfTensor(2 * 1024 * 1024 * 1024 // 2).to(device)

import time
time.sleep(20)
del g
m.close()
f.close()

以上。

参考文献
CUDA C プロフェッショナル プログラミング
YouTube 動画リンク

0
0
1

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
0
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?