ホーム 暮らし How to build FP16 GGUF of WAN2.2

How to build FP16 GGUF of WAN2.2

真鍋 千夏 真鍋 千夏 • 更新: • 公開: • 読了約 35 分
目次

2025年8月9日、WAN2.2 VACE fp16 GGUFに関して、ビルド方法を公開しました。

For WAN2.2 i2v/t2v

n1ff8cf931d7a

作業フォルダと仮想環境を作成し、アクティベートする…辺りの事はもう逐一解説はしません。MSVS開発環境とcmakeも当然「あるもの」として以下解説を進めます。

Powershellは、管理者権限で使用します。

pipを更新します。

python -m pip install --upgrade pip

Pytorchをインストールします。2025年8月3日現在は2.7.1+cu128ですが、当然最新版もコマンドも随時変わります。

pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu128

xformersと、一応tritonも入れておきましょう。

pip install xformers
pip install triton-windows

まずは、定番のllama.cppをインストールしていきます。

git clone https://github.com/ggerganov/llama.cpp.git
cd llama.cpp

ライブラリーをインストールしていきます。

pip install numpy sentencepiece huggingface_hub safetensors gguf

作業フォルダを作成します。

New-Item -ItemType Directory -Path "build"

CMake環境のビルドを行います。

cmake -B build -DCMAKE_BUILD_TYPE=Release -DLLAMA_CURL=OFF
cmake --build build --config Release

次にllama.cppフォルダに、WAN2.2 i2v/t2v fp16.safetensorsファイルを保存します。

次に実行用のpyファイルを作成します。名前は任意に指定します。当然ファイル名は、随時変更します。

#!/usr/bin/env python3
import sys
from pathlib import Path
import numpy as np
from safetensors import safe_open
Necessary to load the local gguf package
sys.path.insert(0, str(Path(file).parent / "gguf-py"))

from gguf import GGUFWriter

def convert_safetensors_to_gguf(input_file, output_file):
 print(f"Converting input_file to output_file")

 # Create GGUF writer
 gguf_writer = GGUFWriter(output_file, "wan2.2")

 # Load safetensors file
 with safe_open(input_file, framework="numpy") as f:
 # Get all tensor names
 tensor_names = f.keys()
 print(f"Found len(tensor_names) tensors")

 # Add metadata
 gguf_writer.add_string("model.name", "Wan2.2")
 gguf_writer.add_string("model.architecture", "diffusion")
 gguf_writer.add_uint32("model.tensor_count", len(tensor_names))

 # Add all tensors
 for i, name in enumerate(tensor_names):
 tensor = f.get_tensor(name)
 print(f"Processing tensor i+1/len(tensor_names): name - Shape: tensor.shape, Dtype: tensor.dtype")
 gguf_writer.add_tensor(name, tensor)

 # Write the file
 print("Writing header...")
 gguf_writer.write_header_to_file()
 print("Writing metadata...")
 gguf_writer.write_kv_data_to_file()
 print("Writing tensors...")
 gguf_writer.write_tensors_to_file()

 gguf_writer.close()
 print(f"Conversion completed: output_file")

if name == 'main':
 input_file = "wan2.2_i2v_high_noise_14B_fp16.safetensors"
 output_file = "wan2.2_i2v_high_noise_14B_fp16.gguf"
 convert_safetensors_to_gguf(input_file, output_file)

仮想環境下で、次のコマンドを実行します。ファイル名は、この場合「convertgguf.py」です。

python convertgguf.py

以下の様に表示されれば、完成です。

上図はhighの場合ですが、lowも同様に作成できます。

For WAN2.2 VACE

ビルド方法は以下に追記しますが、まずその「結果」であるFP16 GGUFを公開しました。

さて、ビルド方法ですが、前述のllama.cppとvenv仮想環境をそのまま使用します。

最初に、下図のコマンドを実行して、必要なPythonライブラリーをインストールします。

pip install diffusers transformers accelerate xformers opencv-python

続いて、llama.cppフォルダ直下に、以下の内容でpyファイルを作成します。ここでは、diffusers_setup.pyとしておきます。

# Save as wan22_diffusers_setup.py
import torch
from safetensors.torch import load_file, save_file
import json
import os
import gc

def setup_wan22_for_diffusers(input_path, output_dir):
 print(f"Setting up Wan2.2 for diffusers: input_path -> output_dir")

 os.makedirs(output_dir, exist_ok=True)

 # Use streaming approach to avoid memory issues
 print("Converting bfloat16 to float32...")

 model_path = os.path.join(output_dir, "diffusion_pytorch_model.safetensors")

 # Read header to get tensor info
 with open(input_path, 'rb') as f:
 header_size = int.from_bytes(f.read(8), byteorder='little')
 header_data = f.read(header_size)
 header = json.loads(header_data.decode('utf-8'))

 print(f"Found len(header) tensors to process")

 # Process tensors in small chunks to avoid memory issues
 temp_files = []
 chunk_size = 20 # Smaller chunks for memory efficiency

 tensor_names = list(header.keys())
 for i in range(0, len(tensor_names), chunk_size):
 chunk_names = tensor_names[i:i + chunk_size]
 print(f"Processing chunk i//chunk_size + 1/(len(tensor_names) + chunk_size - 1)//chunk_size")

 # Load all tensors but only process the chunk we need
 all_tensors = load_file(input_path, device='cpu')
 chunk_tensors = 

 for name in chunk_names:
 if name in all_tensors:
 tensor = all_tensors[name]
 if tensor.dtype == torch.bfloat16:
 # Convert bfloat16 to float32
 print(f"Converting name: tensor.dtype -> float32")
 chunk_tensors[name] = tensor.to(torch.float32)
 else:
 # Keep other dtypes unchanged (including float16)
 print(f"Keeping name: tensor.dtype")
 chunk_tensors[name] = tensor

 del all_tensors
 gc.collect()

 # Save chunk to temporary file
 temp_file = f"model_path.temp_i//chunk_size"
 save_file(chunk_tensors, temp_file)
 temp_files.append(temp_file)

 del chunk_tensors
 gc.collect()

 # Merge all temporary files into final model
 print("Merging into final model...")
 final_tensors = 
 for temp_file in temp_files:
 temp_tensors = load_file(temp_file)
 final_tensors.update(temp_tensors)
 del temp_tensors
 os.remove(temp_file)
 gc.collect()

 # Save final model
 save_file(final_tensors, model_path)
 del final_tensors
 gc.collect()

 print("Conversion completed successfully!")

 # Create config.json
 config = 
 "_class_name": "Wan22VACEPipeline",
 "model_type": "wan2.2_vace",
 "architecture": "text_to_video_diffusion",
 "precision": "mixed_precision"
 

 with open(os.path.join(output_dir, "config.json"), 'w') as f:
 json.dump(config, f, indent=2)

 print("Diffusers setup completed!")

if name == 'main':
 input_path = "Wan2.2-VACE-Fun-A14B-High.safetensors"
 output_dir = "wan22_diffusers"
 setup_wan22_for_diffusers(input_path, output_dir)

変換するfp16.safetensorsも直下に置く想定です。

fp16.safetensorsファイルの設置が出来たら、以下で実行します。

python diffusers_setup.py

完了すると以下の様に表示されます。

Setting up Wan2.2 for diffusers: Wan2.2_T2V_Low_Noise_14B_VACE_fp16.safetensors -> wan22_diffusers
Diffusers setup completed!
(venv) PS D:\USERFILES\gguf\llama.cpp>

以下の様に出力されます。この状態では、Vaceコードをfp32で変換した為、サイズが膨張しています。

何でこんな事になるかと言えば、対象のWAN2.2 t2v Vaceが個人の有志の自作故か否か不明ですが、t2vのベース部分がfp16形式、Vace部分がBf16形式で構成されているからです。

bf16は、直接fp16に持っていけないので、一度ここでfp32に変換した訳です。この後、更にそれをfp16に持っていきます。

続いて、以下の内容でpyファイルを作成します。ここでは、tofp16.pyとしておきます。

#!/usr/bin/env python3
import torch
from safetensors.torch import load_file, save_file
import gc
import psutil
import os

def get_memory_usage():
 """現在のメモリ使用量を取得"""
 process = psutil.Process(os.getpid())
 return process.memory_info().rss / 1024 / 1024 / 1024 # GB

def optimize_to_fp16(input_file, output_file):
 print(f"Optimizing model to FP16: input_file -> output_file")
 print(f"Initial memory usage: get_memory_usage():.2f GB")

 # 元のファイルサイズを確認
 original_size = os.path.getsize(input_file) / (10243)
 print(f"Original file size: original_size:.2f GB")

 # モデルを読み込み
 print("Loading model...")
 tensors = load_file(input_file)
 print(f"Loaded len(tensors) tensors")

 # データ型の分布を確認
 dtype_counts = 
 for tensor in tensors.values():
 dtype = str(tensor.dtype)
 dtype_counts[dtype] = dtype_counts.get(dtype, 0) + 1

 print(f"\\nOriginal data type distribution:")
 for dtype, count in dtype_counts.items():
 print(f" dtype: count tensors")

 # FP16に最適化
 optimized_tensors = 
 fp32_to_fp16_count = 0
 kept_original_count = 0

 for name, tensor in tensors.items():
 if tensor.dtype == torch.float32:
 # float32 → float16に変換
 optimized_tensor = tensor.to(torch.float16)
 optimized_tensors[name] = optimized_tensor
 fp32_to_fp16_count += 1
 print(f"Converted name: float32 → float16, Shape: tensor.shape")
 else:
 # その他はそのまま保持
 optimized_tensors[name] = tensor
 kept_original_count += 1

 print(f"\\nOptimization summary:")
 print(f" FP32 → FP16 converted: fp32_to_fp16_count")
 print(f" Kept original: kept_original_count")

 # 最適化後のデータ型分布を確認
 optimized_dtype_counts = 
 for tensor in optimized_tensors.values():
 dtype = str(tensor.dtype)
 optimized_dtype_counts[dtype] = optimized_dtype_counts.get(dtype, 0) + 1

 print(f"\\nOptimized data type distribution:")
 for dtype, count in optimized_dtype_counts.items():
 print(f" dtype: count tensors")

 # 最適化されたモデルを保存
 print(f"\\nSaving optimized model to: output_file")
 save_file(optimized_tensors, output_file)

 # 結果を確認
 optimized_size = os.path.getsize(output_file) / (10243)
 size_reduction = original_size - optimized_size
 reduction_percentage = (size_reduction / original_size) * 100

 print(f"\\n Optimization completed!")
 print(f" Original size: original_size:.2f GB")
 print(f" Optimized size: optimized_size:.2f GB")
 print(f" Size reduction: size_reduction:.2f GB (reduction_percentage:.1f%)")
 print(f" Final memory usage: get_memory_usage():.2f GB")

 # メモリクリーンアップ
 del tensors, optimized_tensors
 gc.collect()

if name == 'main':
 input_file = "wan22_diffusers/diffusion_pytorch_model.safetensors"
 output_file = "wan22_diffusers/diffusion_pytorch_model_fp16_optimized.safetensors"
 optimize_to_fp16(input_file, output_file)

以下の様に実行します。

python tofp16.py

この結果、以下の様に同フォルダ内に、完全に内部構造をfp16化したsafetensorsファイルが作成されます。

続いて、以下の内容でpyファイルを作成します。ここでは、convertvace.pyとしておきます。

#!/usr/bin/env python3
import sys
from pathlib import Path
import numpy as np
from safetensors.torch import load_file
import gc
import psutil
import os
Necessary to load the local gguf package
sys.path.insert(0, str(Path(file).parent / "gguf-py"))

from gguf import GGUFWriter

def get_memory_usage():
 """現在のメモリ使用量を取得"""
 process = psutil.Process(os.getpid())
 return process.memory_info().rss / 1024 / 1024 / 1024 # GB

def convert_diffusers_to_gguf(input_file, output_file):
 print(f"Converting diffusers model to GGUF: input_file -> output_file")
 print(f"Initial memory usage: get_memory_usage():.2f GB")

 # Create GGUF writer
 gguf_writer = GGUFWriter(output_file, "wan2.2_vace")

 # Load diffusers safetensors file
 print("Loading diffusers model...")
 tensors = load_file(input_file)

 tensor_names = list(tensors.keys())
 print(f"Found len(tensor_names) tensors")

 # Add VACE-specific metadata
 gguf_writer.add_string("model.name", "Wan2.2_VACE")
 gguf_writer.add_string("model.version", "2.2")
 gguf_writer.add_string("model.architecture", "diffusion")
 gguf_writer.add_string("model.type", "text_to_video")
 gguf_writer.add_string("model.variant", "VACE")
 gguf_writer.add_uint32("model.tensor_count", len(tensor_names))
 gguf_writer.add_string("model.precision", "fp16")
 gguf_writer.add_string("conversion.source", "diffusers")

 successful_tensors = 0
 skipped_tensors = 0

 # Convert all tensors
 for i, name in enumerate(tensor_names):
 try:
 tensor = tensors[name]

 # Convert to numpy if needed
 if hasattr(tensor, 'numpy'):
 numpy_tensor = tensor.numpy()
 else:
 numpy_tensor = tensor

 print(f"Processing tensor i+1/len(tensor_names): name")
 print(f" Shape: tensor.shape, Type: tensor.dtype")

 gguf_writer.add_tensor(name, numpy_tensor)
 successful_tensors += 1

 # メモリ解放
 del tensor, numpy_tensor

 # 定期的にガベージコレクション実行
 if i % 50 == 0:
 gc.collect()
 print(f" Memory usage after i+1 tensors: get_memory_usage():.2f GB")

 except Exception as e:
 print(f" ️ Error processing name: e")
 print(f" Skipping this tensor...")
 skipped_tensors += 1
 continue

 # Write the GGUF file
 print("\\nWriting GGUF file...")
 print("Writing header...")
 gguf_writer.write_header_to_file()
 print("Writing metadata...")
 gguf_writer.write_kv_data_to_file()
 print("Writing tensors...")
 gguf_writer.write_tensors_to_file()

 gguf_writer.close()

 # 変換統計を表示
 print(f"\\nGGUF conversion completed!")
 print(f" Successful tensors: successful_tensors")
 print(f" Skipped tensors: skipped_tensors")
 print(f" Output file: output_file")
 print(f"Final memory usage: get_memory_usage():.2f GB")

if name == 'main':
 input_file = "wan22_diffusers/diffusion_pytorch_model_fp16_optimized.safetensors"
 output_file =wan2.2_vace_final.gguf"
 convert_diffusers_to_gguf(input_file, output_file)

以下の様に実行します。

python convertvace.py

この結果、以下の様にllama.cpp直下にGGUFが作成されます。

\nGGUF conversion completed!
 Successful tensors: 1331
 Skipped tensors: 0
 Output file: wan2.2_vace_final.gguf
Final memory usage: 32.69 GB
(venv) PS D:\USERFILES\gguf\llama.cpp>

WAN2.2 Upscaling時のOOM対策追記

WAN2.2アップスケール時のOOM(この場合、VRAMではなくシステムメモリ不足で落ちる)対策を追記しました。

今日のBGM

堀内孝雄「愛しき日々」ライブ・レコーディング

昭和61年日本テレビ年末時代劇『白虎隊』主題歌。当時の俺は、今とは比較にならん位尖っていたので(これでも丸くはなったのだ)、紅白や年末特番バラエティーなんぞ絶対拒否…だけでなく、「軽い」「チャラい」的なものを悉く拒絶していた時期だった。

今でも好きではないが…ともあれ、当時から頭の中は歴史歴史歴史…それも政治軍事経済…の勉強読書に明け暮れてた時期。そりゃ、同世代の大半と話が噛み合う訳ねえ…そして、外ではバイク(てのは勿論自転車の事だ)。所謂ローリング族…二輪と四輪と双方で走り屋の世界に身を投じたのは、これより数年後の事である。

過零丁洋 作・文宋瑞(文天祥)

辛苦遭逢起一經,干戈寥落四周星。
山河破碎風飄絮,身世浮沈雨打萍。
惶恐灘頭説惶恐,零丁洋裏歎零丁。
人生自古誰無死,留取丹心照汗青。

辛苦遭逢は一經より起こり,干戈寥落として四周星。
山河破れ碎けて風絮を飄ばし,身世浮沈し雨萍を打つ。
惶恐灘の頭に 惶恐を説き,零丁洋の裏に零丁を歎く。
人生古より誰か死無からん,丹心を留取して汗靑を照らさん。

「過零丁洋(文天祥)」吟:玉越律子(寛村会)公益社団法人 関西吟詩文化協会

五木ひろし 絆

テレビ東京12時間超ワイドドラマ 大忠臣蔵主題歌

昭和64年1月2日放送。この5日後に昭和の帝が崩御された。この年、ベルリンの壁が崩壊、一連の東欧革命が勃発、世界は激変することになる。東西冷戦構造を「当たり前」の皮膚感覚として育ってきた俺達(何しろ「ドラえもん」ですら劇場版で「相互確証破壊」が描かれる時代だった)は、以降それまでの「常識」を様々な意味で更新せねばならぬ時代であった。

プリンセス プリンセス『19 GROWING UP -ode to my buddy-(HERE WE ARE Live ver.)』(デジタル・リマスター版)

昭和から平成に変わったその同月1月、彼らは一つの歴史を新しく築く。

全員女性バンドとしては初めての日本武道館公演は、現在に至るまで日本のロックシーンで女性が活躍しうる環境の為の一里塚となった。実はこの点に限って言えば、日本は世界に先駆けた自由を誇って良いとすら言える。

俺は、アメリカの少女が自国で「女の子がロックバンドをやれる」自由と環境がないことを嘆き、日本のガールズバンドに憧れる…声を実際に複数見聞したことがある。かの国では意外と、この自由が少ないらしい。特に最近のかの国を見ていれば、さもありなんとも思う。


同じカテゴリの記事

真鍋 千夏
デジタルマーケター 真鍋 千夏
プロフィールを見る →

美容と暮らしの話題を担当。メーカーの公式発表、商品成分の公表資料、専門家の監修記事をもとに事実を整理します。

おすすめの関連記事