0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

NPUってなんだ?〜AI PCの心臓部を徹底解説 Intel・AMD・Apple・Qualcomm完全比較〜

Last updated at Posted at 2026-01-15

この記事の対象読者

  • CPUやGPUの基本的な役割を理解している方
  • 「AI PC」「Copilot+ PC」という言葉を聞いたことがある方
  • ローカルでAIを動かすことに興味がある方
  • 各社のNPUの違いを整理したい方

この記事で得られること

  • NPUの基本概念と、なぜ今注目されているかの理解
  • Intel / AMD / Apple / Qualcomm / Google の各社NPUアーキテクチャの比較
  • 各SDKを使った実装サンプルコード
  • 自分の用途に合ったNPU搭載デバイスの選び方

この記事で扱わないこと

  • データセンター向けAIアクセラレータ(NVIDIA H100、Google TPU v5など)の詳細
  • NPUのVerilog/RTLレベルの設計
  • 量子化理論の数学的な詳細

1. NPUとの出会い

「このノートPC、NPU搭載って書いてあるけど、結局何ができるの?」

2024年から「AI PC」「Copilot+ PC」という言葉が飛び交うようになり、PCの購入ページには「○○ TOPS」という見慣れない数字が並ぶようになりました。正直、最初は私も「また新しいマーケティング用語か」と思っていました。

しかし、実際にNPU搭載のノートPCでStable Diffusionを動かしてみたとき、その考えは一変しました。ディスクリートGPUなしで、システム全体で20〜30W程度の消費電力で画像が生成される。速度はRTX 4090のような高性能GPUには遠く及ばないものの(1枚あたり数十秒〜1分以上かかる)、バッテリー駆動のままAIモデルを動かせる。これは、ローカルAIの民主化だと感じました。

NPUは、いわば 「AIに特化した省エネ脳」 です。人間で言えば、論理的思考を担う前頭葉(CPU)、視覚処理を担う後頭葉(GPU)に加えて、直感的なパターン認識を担う新しい脳の領域が追加されたようなもの。

この記事では、Intel・AMD・Apple・Qualcomm・Googleの各社NPUを徹底比較し、実際に動かすためのコードまでお届けします。

ここまでで、NPUがどんな存在かイメージできたでしょうか。次は、この技術を理解するための前提知識を整理していきます。


2. 前提知識の確認

本題に入る前に、この記事で使う用語を整理しておきましょう。

2.1 TOPS(Tera Operations Per Second)とは

NPUの性能を表す指標で、1秒間に実行できる演算回数を「兆」単位で表したものです。

単位 意味
1 TOPS 1秒間に1兆回の演算
45 TOPS 1秒間に45兆回の演算

ただし、TOPSは「INT8」「FP16」など、どの精度で測定したかによって数値が変わります。公称値を比較する際は、同じ精度での比較が重要です。

2.2 量子化(Quantization)とは

AIモデルの計算精度を下げて、処理を高速化・省メモリ化する技術です。

精度 ビット数 用途
FP32 32bit 学習時の標準
FP16 / BF16 16bit 推論の高精度モード
INT8 8bit 推論の標準モード
INT4 4bit 超軽量モード

NPUはINT8やINT4での演算に最適化されているため、量子化されたモデルで真価を発揮します。

2.3 推論(Inference)とは

学習済みのAIモデルを使って、入力データから結果を得る処理のことです。ChatGPTの応答生成、画像認識、音声認識などがこれに該当します。NPUは主にこの「推論」処理を高速化するために設計されています。

2.4 SoC(System on a Chip)とは

CPU、GPU、NPU、メモリコントローラーなどを1つのチップに統合した構成のことです。現代のスマートフォンやノートPC向けプロセッサは、ほぼすべてがSoCアーキテクチャを採用しています。

これらの用語が押さえられたら、次に進みましょう。


3. NPUが生まれた背景

3.1 なぜCPUやGPUではダメなのか

AIの推論処理は、本質的に「行列演算の繰り返し」です。これは従来のCPUやGPUでも実行できます。では、なぜ専用のNPUが必要になったのでしょうか。

プロセッサ 得意なこと AI推論の課題
CPU 複雑な分岐処理、逐次処理 並列度が低く、効率が悪い
GPU 大規模並列処理、グラフィックス 消費電力が高い(数十〜数百W)
NPU 低精度行列演算、パターン認識 汎用性は低いが、省電力で高速

つまり、NPUは 「AIの推論に特化することで、GPUの1/10以下の電力で同等の処理を実現する」 ために生まれました。

3.2 2024年:AI PCの年

2024年は「AI PC元年」と呼ばれます。MicrosoftはCopilot+ PC認定の要件として「NPU 40 TOPS以上」を定め、各社が一斉にNPU強化に動きました。

時期 出来事
2017年 Apple、A11 BionicでNeural Engine搭載(スマートフォン初)
2023年 Intel Meteor Lake、PC向けNPU本格搭載(11 TOPS)
2024年 Microsoft Copilot+ PC発表、NPU 40 TOPS要件を設定
2024年 Qualcomm Snapdragon X Elite登場(45 TOPS)
2024年 AMD Ryzen AI 300登場(50 TOPS)
2024年 Intel Lunar Lake登場(48 TOPS)
2025年 Qualcomm Snapdragon X2 Elite登場(80 TOPS)

背景がわかったところで、抽象的な概念から順に、各社NPUの具体的なアーキテクチャを見ていきましょう。


4. 各社NPUアーキテクチャ徹底比較

4.1 アーキテクチャ比較表

メーカー NPU名称 最新世代 TOPS(INT8) 対応SDK 主な搭載製品
Intel NPU 4/5 Panther Lake 48-50 TOPS OpenVINO Core Ultra 200V/300
AMD XDNA 2 Strix Point 50-55 TOPS Ryzen AI Software Ryzen AI 300
Apple Neural Engine M4 38 TOPS Core ML MacBook Pro/Air, iPad Pro
Qualcomm Hexagon NPU6 X2 Elite 80 TOPS SNPE / QNN Surface Laptop, Galaxy Book
Google Edge TPU Tensor G5 非公開 TensorFlow Lite Pixel 10

4.2 Intel NPU(OpenVINO)

Intel NPUは、Meteor Lake(2023年)で本格的にPC向けに登場しました。

アーキテクチャの特徴:

  • NPU 4(Lunar Lake): 48 TOPS、6つのNeural Compute Engine搭載
  • NPU 5(Panther Lake): 48-50 TOPS、面積40%削減で効率向上
  • OpenVINOランタイム: CPU/GPU/NPUを統一的に扱えるフレームワーク
┌─────────────────────────────────────┐
│           Intel SoC                 │
│  ┌─────────┐ ┌─────────┐ ┌───────┐ │
│  │   CPU   │ │   GPU   │ │  NPU  │ │
│  │ (Lion   │ │  (Xe2/  │ │(NPU4/ │ │
│  │  Cove)  │ │  Xe3)   │ │ NPU5) │ │
│  └────┬────┘ └────┬────┘ └───┬───┘ │
│       └───────────┴──────────┘     │
│              OpenVINO              │
└─────────────────────────────────────┘

私がハマったポイント:

最初、OpenVINOでNPUを使おうとしたとき、モデルが動かなくて困りました。原因は、NPUが対応していないオペレータ(演算子)がモデルに含まれていたこと。NPUは汎用性よりも効率を優先しているため、すべてのモデルがそのまま動くわけではありません。

4.3 AMD XDNA(Ryzen AI)

AMD XDNAは、2022年に買収したXilinxの技術をベースにしています。

アーキテクチャの特徴:

  • 空間データフローアーキテクチャ: AI Engineタイルを2次元配列で配置
  • XDNA 2(Strix Point): 50 TOPS、Block FP16対応で量子化不要
  • Ryzen AI Software: ONNX Runtime + DirectML対応
┌─────────────────────────────────────┐
│         AMD XDNA NPU               │
│  ┌─────┬─────┬─────┬─────┐        │
│  │ AIE │ AIE │ AIE │ AIE │  Row 0 │
│  ├─────┼─────┼─────┼─────┤        │
│  │ AIE │ AIE │ AIE │ AIE │  Row 1 │
│  ├─────┼─────┼─────┼─────┤        │
│  │ AIE │ AIE │ AIE │ AIE │  Row 2 │
│  ├─────┼─────┼─────┼─────┤        │
│  │ AIE │ AIE │ AIE │ AIE │  Row 3 │
│  └─────┴─────┴─────┴─────┘        │
│  AIE = AI Engine Tile              │
│  各タイルにVLIW+SIMDプロセッサ搭載  │
└─────────────────────────────────────┘

Block FP16の革新:

AMDのXDNA 2は「Block FP16」という独自のデータ形式をサポートしています。これにより、INT8と同等の速度を維持しながら、FP16相当の精度を実現。モデルの量子化作業が不要になるのは大きなメリットです。

4.4 Apple Neural Engine(Core ML)

Apple Neural Engineは、2017年のA11 Bionicで初登場。最も歴史のあるコンシューマ向けNPUです。

アーキテクチャの特徴:

  • M4: 16コアNeural Engine、38 TOPS
  • Unified Memory Architecture: CPU/GPU/NPUがメモリを共有
  • Core ML: Appleエコシステムに深く統合されたフレームワーク
┌─────────────────────────────────────┐
│        Apple M4 SoC                │
│  ┌──────────────────────────────┐  │
│  │      Unified Memory          │  │
│  │    (LPDDR5X, 120GB/s)        │  │
│  └──────────────────────────────┘  │
│       ↑         ↑         ↑       │
│  ┌────┴───┐ ┌───┴───┐ ┌───┴────┐  │
│  │  CPU   │ │  GPU  │ │ Neural │  │
│  │(10コア)│ │(10コア)│ │ Engine │  │
│  │        │ │       │ │(16コア)│  │
│  └────────┘ └───────┘ └────────┘  │
└─────────────────────────────────────┘

TOPSだけでは測れない実力:

Apple M4のNeural Engineは38 TOPSと、競合より数字は低めです。しかし、Geekbench AIベンチマークでは、45 TOPSのQualcomm Snapdragon X Eliteを上回るスコアを記録しています。

これは、Unified Memory Architectureによるデータ転送の効率化と、Core MLによるソフトウェア最適化の賜物です。カタログスペックだけでは見えない部分ですね。

4.5 Qualcomm Hexagon NPU(SNPE/QNN)

Qualcommは、スマートフォン向けDSPの経験を活かしてPC向けNPUを開発しています。

アーキテクチャの特徴:

  • Hexagon NPU6(X2 Elite): 80 TOPS、12スレッド対応
  • Scalar/Vector/Matrix Unit: 3種類の演算ユニットを統合
  • SNPE/QNN SDK: TensorFlow, PyTorch, ONNXモデルをサポート
┌─────────────────────────────────────┐
│      Qualcomm Hexagon NPU          │
│  ┌─────────────────────────────┐   │
│  │      Scalar Unit            │   │
│  │   (12スレッド, 4-wide VLIW) │   │
│  └─────────────────────────────┘   │
│  ┌─────────────────────────────┐   │
│  │      Vector Unit            │   │
│  │  (8並列エンジン, FP8/BF16)  │   │
│  └─────────────────────────────┘   │
│  ┌─────────────────────────────┐   │
│  │      Matrix Unit            │   │
│  │    (INT2/INT4/INT8/BF16)    │   │
│  └─────────────────────────────┘   │
└─────────────────────────────────────┘

Snapdragon X2 Eliteの進化:

2025年発表のSnapdragon X2 Eliteでは、NPU性能が45 TOPSから80 TOPSへと大幅に向上。64ビットDMAサポートにより、4GB以上のメモリを直接アクセスできるようになり、大規模モデルの実行が現実的になりました。

4.6 Google Tensor TPU(TensorFlow Lite)

Google Tensorは、Pixelスマートフォン向けに開発されたSoCです。「TPU」という名称はクラウドのTensor Processing Unitと共通ですが、アーキテクチャは異なります。

アーキテクチャの特徴:

  • Edge TPU: オンデバイスAI処理に特化
  • Tensor G5(Pixel 10): TSMC 3nm、G4比で60%高速なTPU
  • TensorFlow Lite: Google製MLフレームワーク

基本概念が理解できたところで、これらの抽象的な概念を具体的なコードで実装していきましょう。


5. 実際に使ってみよう

5.1 環境構築

各社NPUを使用するための環境構築手順を示します。

Intel OpenVINO(Linux/Windows)

# Pythonパッケージのインストール
pip install openvino openvino-dev

# NPUドライバの確認(Linux)
ls /dev/accel*
# /dev/accel0 が表示されればNPU認識済み

# NPUドライバの確認(Windows)
# デバイスマネージャーで「Intel(R) AI Boost」を確認

AMD Ryzen AI(Windows)

# Ryzen AI Softwareのインストール(公式サイトからダウンロード)
# https://www.amd.com/en/products/software/ryzen-ai-software.html

# Pythonパッケージのインストール
pip install onnxruntime-directml

Apple Core ML(macOS)

# coremltools のインストール
pip install coremltools

# Xcode Command Line Toolsが必要
xcode-select --install

5.2 設定ファイルの準備

以下の3種類の設定ファイルを用意しています。用途に応じて選択してください。

開発環境用(config.yaml)

# config.yaml - 開発環境用(このままコピーして使える)
# NPU推論の基本設定

runtime:
  backend: "npu"          # "cpu", "gpu", "npu" から選択
  device_id: 0            # デバイスID(通常は0)
  log_level: "DEBUG"      # DEBUG, INFO, WARNING, ERROR

model:
  path: "./models/model.onnx"
  precision: "INT8"       # FP32, FP16, INT8, INT4
  cache_dir: "./cache"    # コンパイル済みモデルのキャッシュ

inference:
  batch_size: 1
  num_threads: 4
  timeout_ms: 5000        # タイムアウト(ミリ秒)

本番環境用(config.production.yaml)

# config.production.yaml - 本番環境用(このままコピーして使える)
# パフォーマンスと安定性を重視した設定

runtime:
  backend: "npu"
  device_id: 0
  log_level: "WARNING"    # ログ出力を最小化

model:
  path: "${MODEL_PATH}"   # 環境変数から読み込み
  precision: "INT8"
  cache_dir: "/var/cache/npu_models"

inference:
  batch_size: 4           # バッチ処理で効率化
  num_threads: 8
  timeout_ms: 10000

monitoring:
  enable_metrics: true
  metrics_port: 9090
  health_check_interval: 30

テスト環境用(config.test.yaml)

# config.test.yaml - テスト/CI用(このままコピーして使える)
# 再現性と高速なフィードバックを重視

runtime:
  backend: "cpu"          # CI環境ではCPUフォールバック
  device_id: 0
  log_level: "DEBUG"

model:
  path: "./test_models/test_model.onnx"
  precision: "FP32"       # テストでは精度を優先
  cache_dir: "./test_cache"

inference:
  batch_size: 1
  num_threads: 2
  timeout_ms: 30000       # テストは余裕を持って

test:
  compare_baseline: true
  tolerance: 0.001        # 許容誤差
  sample_count: 100       # テストサンプル数

5.3 基本的な使い方

Intel OpenVINOでの推論

"""
Intel NPUでの画像分類サンプル
使い方: python intel_npu_inference.py
必要なパッケージ: pip install openvino opencv-python numpy
"""
import numpy as np
import cv2
from openvino.runtime import Core
import yaml
from pathlib import Path


def load_config(config_path: str = "config.yaml") -> dict:
    """設定ファイルを読み込む"""
    with open(config_path, "r") as f:
        return yaml.safe_load(f)


def preprocess_image(image_path: str, input_shape: tuple) -> np.ndarray:
    """画像の前処理"""
    image = cv2.imread(image_path)
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    image = cv2.resize(image, (input_shape[3], input_shape[2]))
    image = image.astype(np.float32) / 255.0
    image = np.transpose(image, (2, 0, 1))  # HWC -> CHW
    image = np.expand_dims(image, axis=0)   # バッチ次元追加
    return image


def run_inference_on_npu(
    model_path: str,
    image_path: str,
    device: str = "NPU"
) -> np.ndarray:
    """NPUで推論を実行"""
    # OpenVINO Core初期化
    core = Core()
    
    # 利用可能なデバイスを表示
    print(f"利用可能なデバイス: {core.available_devices}")
    
    # モデルの読み込み
    model = core.read_model(model_path)
    
    # NPU用にコンパイル
    compiled_model = core.compile_model(model, device)
    
    # 入力/出力情報の取得
    input_layer = compiled_model.input(0)
    output_layer = compiled_model.output(0)
    
    print(f"入力形状: {input_layer.shape}")
    print(f"出力形状: {output_layer.shape}")
    
    # 画像の前処理
    input_data = preprocess_image(image_path, input_layer.shape)
    
    # 推論実行
    result = compiled_model([input_data])
    
    return result[output_layer]


def main():
    # 設定読み込み
    config = load_config()
    
    # サンプル画像(存在しない場合はダミーデータ)
    image_path = "sample.jpg"
    if not Path(image_path).exists():
        # テスト用のダミー画像を作成
        dummy_image = np.random.randint(0, 255, (224, 224, 3), dtype=np.uint8)
        cv2.imwrite(image_path, dummy_image)
        print("テスト用ダミー画像を作成しました")
    
    # 推論実行
    try:
        result = run_inference_on_npu(
            model_path=config["model"]["path"],
            image_path=image_path,
            device=config["runtime"]["backend"].upper()
        )
        
        # 結果表示
        top5_indices = np.argsort(result[0])[-5:][::-1]
        print("\n推論結果(Top 5):")
        for i, idx in enumerate(top5_indices, 1):
            print(f"  {i}. クラス{idx}: {result[0][idx]:.4f}")
            
    except Exception as e:
        print(f"エラー: {e}")
        print("NPUが利用できない場合は、config.yamlのbackendを'cpu'に変更してください")


if __name__ == "__main__":
    main()

AMD Ryzen AIでの推論

"""
AMD Ryzen AI NPUでの推論サンプル
使い方: python amd_npu_inference.py
必要なパッケージ: pip install onnxruntime-directml numpy
"""
import numpy as np
import onnxruntime as ort
from pathlib import Path


def get_available_providers() -> list:
    """利用可能な実行プロバイダを取得"""
    providers = ort.get_available_providers()
    print(f"利用可能なプロバイダ: {providers}")
    return providers


def create_session_with_npu(model_path: str) -> ort.InferenceSession:
    """NPU(DirectML)を使用するセッションを作成"""
    providers = get_available_providers()
    
    # DirectMLが利用可能な場合はNPUを使用
    if "DmlExecutionProvider" in providers:
        session = ort.InferenceSession(
            model_path,
            providers=["DmlExecutionProvider", "CPUExecutionProvider"]
        )
        print("DirectML(NPU/GPU)で実行します")
    else:
        session = ort.InferenceSession(
            model_path,
            providers=["CPUExecutionProvider"]
        )
        print("CPUで実行します(DirectMLが利用できません)")
    
    return session


def run_inference(
    session: ort.InferenceSession,
    input_data: np.ndarray
) -> np.ndarray:
    """推論を実行"""
    input_name = session.get_inputs()[0].name
    output_name = session.get_outputs()[0].name
    
    result = session.run(
        [output_name],
        {input_name: input_data}
    )
    
    return result[0]


def main():
    model_path = "./models/model.onnx"
    
    # モデルファイルの存在確認
    if not Path(model_path).exists():
        print(f"モデルファイルが見つかりません: {model_path}")
        print("ONNXモデルを配置してから再実行してください")
        return
    
    # セッション作成
    session = create_session_with_npu(model_path)
    
    # 入力情報の取得
    input_info = session.get_inputs()[0]
    print(f"入力名: {input_info.name}")
    print(f"入力形状: {input_info.shape}")
    print(f"入力型: {input_info.type}")
    
    # ダミー入力データの作成
    input_shape = [1, 3, 224, 224]  # 一般的な画像分類モデルの入力形状
    input_data = np.random.randn(*input_shape).astype(np.float32)
    
    # 推論実行
    result = run_inference(session, input_data)
    
    print(f"\n出力形状: {result.shape}")
    print(f"推論完了!")


if __name__ == "__main__":
    main()

Apple Core MLでの推論

"""
Apple Neural Engineでの推論サンプル
使い方: python apple_npu_inference.py
必要なパッケージ: pip install coremltools numpy
動作環境: macOS 12.0以降 + Apple Silicon
"""
import numpy as np
import coremltools as ct
from pathlib import Path


def convert_onnx_to_coreml(
    onnx_path: str,
    output_path: str,
    compute_units: str = "ALL"
) -> ct.models.MLModel:
    """
    ONNXモデルをCore ML形式に変換
    
    compute_units:
        - "ALL": Neural Engine + GPU + CPU(推奨)
        - "CPU_AND_NE": Neural Engine + CPU
        - "CPU_ONLY": CPUのみ
    """
    import coremltools.converters.onnx as onnx_converter
    
    # 変換オプション
    compute_units_map = {
        "ALL": ct.ComputeUnit.ALL,
        "CPU_AND_NE": ct.ComputeUnit.CPU_AND_NE,
        "CPU_ONLY": ct.ComputeUnit.CPU_ONLY,
    }
    
    # ONNX → Core ML変換
    model = ct.convert(
        onnx_path,
        compute_units=compute_units_map.get(compute_units, ct.ComputeUnit.ALL),
        minimum_deployment_target=ct.target.macOS13,
    )
    
    # 保存
    model.save(output_path)
    print(f"変換完了: {output_path}")
    
    return model


def run_inference_on_neural_engine(
    model_path: str,
    input_data: dict
) -> dict:
    """Neural Engineで推論を実行"""
    # モデル読み込み
    model = ct.models.MLModel(model_path)
    
    # モデル情報の表示
    spec = model.get_spec()
    print(f"モデル説明: {spec.description}")
    
    # 推論実行
    result = model.predict(input_data)
    
    return result


def check_neural_engine_availability():
    """Neural Engineが利用可能か確認"""
    import platform
    
    if platform.system() != "Darwin":
        print("警告: macOS以外ではNeural Engineは利用できません")
        return False
    
    # Apple Silicon確認
    if platform.processor() == "arm":
        print("Apple Silicon検出: Neural Engine利用可能")
        return True
    else:
        print("Intel Mac検出: Neural Engineは利用できません")
        return False


def main():
    # 環境確認
    if not check_neural_engine_availability():
        return
    
    # モデルパス
    coreml_model_path = "./models/model.mlpackage"
    
    if not Path(coreml_model_path).exists():
        print(f"Core MLモデルが見つかりません: {coreml_model_path}")
        print("ONNXモデルから変換するか、.mlpackageを配置してください")
        return
    
    # ダミー入力
    input_data = {
        "input": np.random.randn(1, 3, 224, 224).astype(np.float32)
    }
    
    # 推論実行
    result = run_inference_on_neural_engine(coreml_model_path, input_data)
    
    print(f"\n推論結果: {result}")


if __name__ == "__main__":
    main()

5.4 実行結果

上記のコードを実行すると、以下のような出力が得られます:

# Intel OpenVINOの場合
$ python intel_npu_inference.py
利用可能なデバイス: ['CPU', 'GPU', 'NPU']
入力形状: [1, 3, 224, 224]
出力形状: [1, 1000]

推論結果(Top 5):
  1. クラス281: 0.8234
  2. クラス285: 0.0521
  3. クラス282: 0.0312
  4. クラス287: 0.0156
  5. クラス283: 0.0098

5.5 よくあるエラーと対処法

エラー 原因 対処法
RuntimeError: NPU device not found NPUドライバ未インストール 各社公式サイトから最新ドライバをインストール
NotImplementedError: Operator not supported NPU非対応のオペレータ使用 モデルを修正するか、CPU/GPUにフォールバック
CUDA out of memory(GPU使用時) GPUメモリ不足 バッチサイズを小さくするか、NPUに切り替え
Model compilation timeout モデルが大きすぎる モデルを分割するか、量子化を適用
Precision mismatch 入力データの型不一致 astype(np.float32)で型を明示的に指定

基本的な使い方をマスターしたので、次は応用的なユースケースを見ていきましょう。


6. ユースケース別ガイド

6.1 ユースケース1: ローカルLLM推論

想定読者: ChatGPTのようなLLMをプライバシー重視でローカル実行したい方

推奨構成:

  • NPU: 45 TOPS以上
  • メモリ: 32GB以上
  • 推奨モデル: Llama 3.2 1B/3B(量子化版)

サンプルコード:

"""
NPUでローカルLLM推論
必要なパッケージ: pip install openvino-genai
"""
from openvino_genai import LLMPipeline
import openvino as ov


def run_local_llm_on_npu(
    model_path: str,
    prompt: str,
    max_tokens: int = 100
) -> str:
    """NPUでLLMを実行"""
    # パイプライン作成(NPU指定)
    pipe = LLMPipeline(model_path, device="NPU")
    
    # 生成パラメータ
    config = pipe.get_generation_config()
    config.max_new_tokens = max_tokens
    config.temperature = 0.7
    
    # 推論実行
    response = pipe.generate(prompt, config)
    
    return response


def main():
    model_path = "./models/llama-3.2-1b-instruct-int4-ov"
    prompt = "日本の首都について教えてください。"
    
    print(f"プロンプト: {prompt}")
    print("生成中...\n")
    
    response = run_local_llm_on_npu(model_path, prompt)
    
    print(f"応答: {response}")


if __name__ == "__main__":
    main()

6.2 ユースケース2: リアルタイム画像処理

想定読者: Webカメラ映像のリアルタイム処理(背景ぼかし、ノイズ除去)をしたい方

推奨構成:

  • NPU: 11 TOPS以上で十分
  • 低遅延が重要(<30ms)
  • 推奨モデル: 軽量セグメンテーションモデル

サンプルコード:

"""
NPUでリアルタイム背景ぼかし
必要なパッケージ: pip install openvino opencv-python numpy
"""
import cv2
import numpy as np
from openvino.runtime import Core
import time


class RealtimeBackgroundBlur:
    def __init__(self, model_path: str, device: str = "NPU"):
        self.core = Core()
        self.model = self.core.read_model(model_path)
        self.compiled_model = self.core.compile_model(self.model, device)
        
        self.input_layer = self.compiled_model.input(0)
        self.output_layer = self.compiled_model.output(0)
    
    def preprocess(self, frame: np.ndarray) -> np.ndarray:
        """フレームの前処理"""
        input_shape = self.input_layer.shape
        resized = cv2.resize(frame, (input_shape[3], input_shape[2]))
        normalized = resized.astype(np.float32) / 255.0
        transposed = np.transpose(normalized, (2, 0, 1))
        batched = np.expand_dims(transposed, axis=0)
        return batched
    
    def apply_blur(self, frame: np.ndarray, mask: np.ndarray) -> np.ndarray:
        """マスクに基づいて背景をぼかす"""
        blurred = cv2.GaussianBlur(frame, (21, 21), 0)
        mask_3ch = np.stack([mask] * 3, axis=-1)
        result = frame * mask_3ch + blurred * (1 - mask_3ch)
        return result.astype(np.uint8)
    
    def process_frame(self, frame: np.ndarray) -> np.ndarray:
        """1フレームを処理"""
        # 前処理
        input_data = self.preprocess(frame)
        
        # NPU推論
        result = self.compiled_model([input_data])
        mask = result[self.output_layer][0, 0]
        
        # マスクをリサイズ
        mask_resized = cv2.resize(mask, (frame.shape[1], frame.shape[0]))
        
        # 背景ぼかし適用
        output = self.apply_blur(frame, mask_resized)
        
        return output


def main():
    model_path = "./models/segmentation_model.xml"
    
    processor = RealtimeBackgroundBlur(model_path, device="NPU")
    cap = cv2.VideoCapture(0)
    
    print("Webカメラ映像処理中... 'q'キーで終了")
    
    while True:
        ret, frame = cap.read()
        if not ret:
            break
        
        start_time = time.time()
        output = processor.process_frame(frame)
        elapsed = (time.time() - start_time) * 1000
        
        # FPS表示
        cv2.putText(
            output, 
            f"NPU: {elapsed:.1f}ms", 
            (10, 30),
            cv2.FONT_HERSHEY_SIMPLEX, 
            1, 
            (0, 255, 0), 
            2
        )
        
        cv2.imshow("Background Blur (NPU)", output)
        
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    
    cap.release()
    cv2.destroyAllWindows()


if __name__ == "__main__":
    main()

6.3 ユースケース3: 音声認識(Whisper)

想定読者: 会議の文字起こしやポッドキャストの書き起こしをローカルで行いたい方

推奨構成:

  • NPU: 30 TOPS以上推奨
  • メモリ: 16GB以上
  • 推奨モデル: Whisper tiny/base/small

サンプルコード:

"""
NPUでWhisper音声認識
必要なパッケージ: pip install openvino optimum-intel soundfile
"""
import soundfile as sf
import numpy as np
from optimum.intel import OVModelForSpeechSeq2Seq
from transformers import AutoProcessor


def transcribe_audio_on_npu(
    audio_path: str,
    model_id: str = "openai/whisper-small",
    device: str = "NPU"
) -> str:
    """NPUで音声をテキストに変換"""
    # プロセッサとモデルの読み込み
    processor = AutoProcessor.from_pretrained(model_id)
    
    # OpenVINO最適化モデルの読み込み
    model = OVModelForSpeechSeq2Seq.from_pretrained(
        model_id,
        export=True,
        device=device
    )
    
    # 音声ファイルの読み込み
    audio, sample_rate = sf.read(audio_path)
    
    # 前処理
    inputs = processor(
        audio,
        sampling_rate=sample_rate,
        return_tensors="pt"
    )
    
    # 推論
    generated_ids = model.generate(
        inputs["input_features"],
        max_new_tokens=256
    )
    
    # デコード
    transcription = processor.batch_decode(
        generated_ids,
        skip_special_tokens=True
    )[0]
    
    return transcription


def main():
    audio_path = "./sample_audio.wav"
    
    print("音声認識を開始します...")
    print(f"入力: {audio_path}")
    
    result = transcribe_audio_on_npu(audio_path)
    
    print(f"\n認識結果:\n{result}")


if __name__ == "__main__":
    main()

ユースケースが把握できたところで、この記事を読んだ後の学習パスを確認しましょう。


7. 学習ロードマップ

この記事を読んだ後、次のステップとして以下をおすすめします。

初級者向け(まずはここから)

  1. 自分のPCのNPUを確認する

    • Windows: タスクマネージャー → パフォーマンス → NPU
    • macOS: アクティビティモニタ → Neural Engine(Apple Silicon)
  2. 公式チュートリアルを試す

中級者向け(実践に進む)

  1. 既存のAIモデルをNPU向けに最適化する

    • ONNX形式への変換
    • INT8量子化の適用
    • ベンチマーク測定
  2. Hugging Face Optimumを活用する

上級者向け(さらに深く)

  1. カスタムオペレータの実装

    • OpenVINO Custom Layers
    • ONNX Custom Operators
  2. NPU性能の最適化

    • メモリアクセスパターンの最適化
    • バッチサイズのチューニング
    • 非同期推論の実装

8. まとめ

この記事では、NPU(Neural Processing Unit)について以下を解説しました:

  1. NPUの基本概念: AI推論に特化した省エネプロセッサ
  2. 各社アーキテクチャの比較: Intel、AMD、Apple、Qualcomm、Googleの特徴
  3. 実装方法: OpenVINO、Ryzen AI、Core MLでの具体的なコード例
  4. ユースケース: ローカルLLM、リアルタイム画像処理、音声認識

私の所感

各社のNPUを試してみて感じたのは、「TOPSだけでは性能は測れない」 ということです。

Apple M4のNeural Engineは38 TOPSですが、実際のベンチマークでは45 TOPSのQualcomm Snapdragon X Eliteを上回ることがあります。これは、Unified Memory Architectureによるデータ転送効率と、Core MLによるソフトウェア最適化の賜物です。

一方、AMD XDNA 2のBlock FP16サポートは、量子化作業を不要にするという点で開発者体験を大きく向上させています。

2025年現在、NPUはまだ「黎明期」にあると感じます。ソフトウェアエコシステムの成熟度はGPUに比べてまだ低く、対応アプリケーションも限られています。しかし、Copilot+ PCの普及により、今後急速に進化していくことは間違いありません。

今のうちにNPU開発に慣れておくことで、ローカルAIの波に乗り遅れないようにしましょう。


参考文献

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?