🔀|要約は手元のGemma、公開できる実装はクラウドへ。GPU 1台で回す振り分け表

gpu llm ollama codex

こんにちは、mocoです。ふだんは手元のPCで、文章をまとめたり、小さな道具を作ったりしています。要約とコードの依頼が混ざると、私は行き先を決めるだけで手が止まることがあります。そこで、入力を外に出せるかと、何を頼むかの二つだけで振り分ける表を作りました。

迷ったときに保留できる振り分け表

ケース 入力の区分 頼む作業 行き先
A ローカル限定と仮定 要約 ローカルのOllama
B 公開可 実装 クラウドのCodex
C 不明 実装 保留
D ローカル限定と仮定 実装 保留
E 公開可 要約 保留

入力の区分は人が付けます。Cは公開可否の確認待ちです。Dは、手元のモデルが出したコードをテストして採用する手順をこの構成では用意していないので、保留にしています。人が公開できる仕様に書き直せたら、そこでBとして振り分け直せます。Eは公開可否の問題がなくても、手元のGPUを使うかクラウドに回すかの基準をまだ決めていないので、保留にしました。

GPU 1台を交代で使う

自主制作では、VRAM 16GBクラスのGPUを共用します。昼は要約と音声処理を順番に回し、夜は動画のバッチをまとめて流すのが基本です。表は私が決めている運用ルールです。VRAMの数字は運用の目安です。

作業 VRAMの目安 同時運転
動画生成 12〜16GB 単独
画像生成・Unityビルド 8〜10GB 小型機1台まで
12BクラスのローカルLLM 7〜9GB 音声処理とは重ねない

疑似コードでは、予約からアンロード完了までを一続きで扱います。

同時運転の表に従って、空くまで待ってGPUを予約する
ジョブを実行する
成功・失敗にかかわらず、モデルをアンロードして完了を確かめる
GPUの予約を解除する

再現コードでは、Ollamaのリクエストに keep_alive: 0 を付けます。実行後は http://127.0.0.1:11434/api/ps を手で開き、models が空になったことを確かめます。ほかの作業との予約調整も実行する人が行います。

模擬経路を試す

記事の最後にある「再現コード」を repro/demo.mjs として保存し、親フォルダから node repro/demo.mjs を実行します。この版はNode.js v24.22.1で模擬モードを確認しました。架空の文化祭を例に、同じPC上のHTTPサーバーへリクエストを送り、受信した経路と入力を照合します。応答は固定で、GPUやクラウドアカウントなしで試せます。

最後に PASS: 5 cases, 2 loopback requests と出れば成功です。5件の振り分けと、A・Bのリクエストが届いたことを確認できています。

実モデルに切り替える

  1. GPUの利用枠を確保し、前の処理のモデルが下りたことを確認します。Ollamaを http://127.0.0.1:11434 で起動し、既定の gemma4:12b-it-qat(12Bクラス)を用意します。別のモデルを使う場合は環境変数 OLLAMA_MODEL を設定します。
  2. Codex CLIにログインしておきます。Windowsではユーザー領域のnpm版、またはPATH上の codex.exe を使います。モデル名を指定する場合は CODEX_MODEL を設定します。認証はログイン済みのCLIに任せます。
  3. node repro/demo.mjs --real を実行します。AはOllamaの /api/generate、Bは読み取り専用サンドボックスの codex exec に渡ります。入力はどちらも架空の公開用データです。
  4. repro/measured.json に各経路の結果が保存されます。取れない項目は null です。GPUの使用量は nvidia-smi でGPU全体を観測します。所要時間はそれぞれの呼び出しにかかった時間を記録します。

実機での結果

2026年11月28日 19:19:40(日本時間)に、Windows(x64、10.0.26300)、Node.js v24.22.1、NVIDIA GeForce RTX 5060 Ti(総VRAM 16,311 MiB)で実行しました。A・Bを各1回実行し、両方とも status: ok でした。同日の後刻にバージョンを確認したところ、Ollamaは 0.40.17、Codex CLIは codex-cli 0.171.0 でした。

Aの所要時間は、モデルの読み込みを含めた生成1回分です。Bは、Codex CLIを起動してから答えが返るまでの1回分です。頼んだ作業も入力も違うので、この表からAとBの速さは比べられません。

経路 指定したモデル 量子化 所要時間 入力トークン 出力トークン 実行前のVRAM 実行中の最大VRAM
A(ローカル) gemma4:12b-it-qat Q4_0 26.908秒 39 393 1,328 MiB 11,732 MiB
B(クラウド) gpt-6.2-sol 未計測 7.540秒 33,987 18 1,327 MiB 1,335 MiB

Bのモデル名は CODEX_MODEL で指定した値です。CLIが実際に使ったモデル名は記録していません。

VRAMは手元PCのGPU全体の使用量で、実行中の列には nvidia-smi で観測した最大値を載せています。Aのこの1回では、GPU全体の使用量が実行前より約10GB増えました。ほかの処理の分は分けていません。運用上の目安(7〜9GB)は今後見直すつもりです。

料金とクラウド側のGPU使用量は未計測です。実行直後の19:20ごろ(日本時間)にOllamaの /api/ps を手で確認すると、応答は {"models":[]} でした。

A(ローカル)の入出力

入力は「架空の文化祭の案内です。工作室は午後に開きます。一文で要約してください。」。返った本文は「文化祭の工作室は午後に開場します。」の17文字で、ログ上の出力は393トークンでした。このトークン数になった理由は、今回確かめていません。

B(クラウド)の入出力

入力は「架空の文化祭用に、文字列 13:00 を返す JavaScript 関数を回答本文だけに書いてください。ファイルやツールは使わないでください。」。この短い依頼文に対し、ログ上の入力は33,987トークンでした。このトークン数になった理由も、今回確かめていません。返った本文は次のとおりです。

function getFestivalTime() {
  return "13:00";
}

やってみて

振り分け表があると、公開してよいか迷う依頼を、いったん保留にできます。今回、ローカルでは工作室の案内が一文にまとまり、クラウドからは指定した時刻を返す関数が返ってきました。

試したのはそれぞれ1回です。普段の待ち時間や費用がどのくらいになるかは、まだ分かりません。次は架空の案内文をもう少し長くして、要約に必要な情報が残るかを見てみたいです。

再現コード

import assert from 'node:assert/strict';
import { execFile, spawn } from 'node:child_process';
import { once } from 'node:events';
import { existsSync } from 'node:fs';
import { mkdtemp, rmdir, writeFile } from 'node:fs/promises';
import { createServer } from 'node:http';
import { release, tmpdir, userInfo } from 'node:os';
import { join } from 'node:path';
import { promisify } from 'node:util';

function routeFor(visibility, task) {
  if (visibility === 'local-only' && task === 'summarize') return 'local';
  if (visibility === 'public' && task === 'implement') return 'cloud';
  return 'hold';
}

// すべて架空の公開用データ。local-only は経路確認用のラベル。
const examples = [
  ['A', 'local-only', 'summarize', '架空の文化祭の案内です。工作室は午後に開きます。一文で要約してください。', 'local'],
  ['B', 'public', 'implement', '架空の文化祭用に、文字列 13:00 を返す JavaScript 関数を回答本文だけに書いてください。ファイルやツールは使わないでください。', 'cloud'],
  ['C', 'unknown', 'implement', '予定を表示してください。', 'hold'],
  ['D', 'local-only', 'implement', '案内を表示する関数を書いてください。', 'hold'],
  ['E', 'public', 'summarize', '工作室の案内を要約してください。', 'hold'],
];

async function post(base, path, body, timeout = 5000) {
  const response = await fetch(base + path, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json; charset=utf-8' },
    body: JSON.stringify(body),
    redirect: 'error',
    signal: AbortSignal.timeout(timeout),
  });
  if (!response.ok) throw new Error('HTTP request failed');
  return response.json();
}

async function runMock() {
  const replies = { '/local': '開室は午後です。', '/cloud': '() => "13:00"' };
  const received = [];
  const server = createServer(async (req, res) => {
    if (req.method !== 'POST' || !Object.hasOwn(replies, req.url)) {
      res.writeHead(404).end();
      return;
    }
    req.setEncoding('utf8');
    let body = '';
    for await (const chunk of req) body += chunk;
    received.push({ path: req.url, input: JSON.parse(body).input });
    res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
    res.end(JSON.stringify({ output: replies[req.url] }));
  });
  server.listen(0, '127.0.0.1');
  await once(server, 'listening');
  try {
    const base = 'http://127.0.0.1:' + server.address().port;
    for (const [id, visibility, task, input, expected] of examples) {
      const before = received.length;
      const route = routeFor(visibility, task);
      assert.equal(route, expected);
      if (route === 'hold') {
        assert.equal(received.length, before);
        console.log(JSON.stringify({ id, route, requests: 0 }));
        continue;
      }
      const path = '/' + route;
      const { output } = await post(base, path, { input });
      assert.equal(output, replies[path]);
      assert.deepEqual(received.slice(before), [{ path, input }]);
      console.log(JSON.stringify({ id, route, output, requests: 1 }));
    }
    assert.deepEqual(received.map(({ path }) => path), ['/local', '/cloud']);
    console.log('PASS: 5 cases, 2 loopback requests');
  } finally {
    server.close();
  }
}

const runCommand = promisify(execFile);
const ollama = 'http://127.0.0.1:11434';
const localModel = process.env.OLLAMA_MODEL || 'gemma4:12b-it-qat';
const cloudModel = process.env.CODEX_MODEL || null;

function publicOutput(value) {
  if (typeof value !== 'string' || !value.trim()) return null;
  const username = userInfo().username.toLowerCase();
  const hasPath = /(?:[a-z]:[\\/]|\\\\|\/(?:home|Users|mnt|tmp|var|private)\/)/i.test(value);
  if (hasPath || (username && value.toLowerCase().includes(username))) return null;
  return value;
}

async function readGpu() {
  try {
    const { stdout } = await runCommand('nvidia-smi', [
      '--query-gpu=index,name,memory.total,memory.used',
      '--format=csv,noheader,nounits',
    ], { timeout: 3000, windowsHide: true });
    const rows = stdout.trim().split(/\r?\n/).filter(Boolean);
    return rows.length ? rows.map(row => {
      const [index, name, total, used] = row.split(',').map(value => value.trim());
      const mib = value => /^\d+$/.test(value ?? '') ? Number(value) : null;
      return { index: mib(index), name: name || null, totalMiB: mib(total), usedMiB: mib(used) };
    }) : null;
  } catch {
    return null;
  }
}

async function callOllama(input, record) {
  try {
    const { details } = await post(ollama, '/api/show', { model: localModel });
    record.quantization = details?.quantization_level ?? null;
  } catch {
    // A metadata failure does not prevent generation.
  }
  return measure(record, async () => {
    const response = await post(ollama, '/api/generate', {
      model: localModel, prompt: input, stream: false, keep_alive: 0,
    }, 180000);
    record.output = publicOutput(response.response);
    record.inputTokens = response.prompt_eval_count ?? null;
    record.outputTokens = response.eval_count ?? null;
    if (record.output === null) throw new Error('Missing Ollama output');
  });
}

function codexCommand() {
  if (process.platform !== 'win32') return ['codex'];
  const npmEntry = process.env.APPDATA && join(
    process.env.APPDATA, 'npm', 'node_modules', '@openai', 'codex', 'bin', 'codex.js',
  );
  return npmEntry && existsSync(npmEntry) ? [process.execPath, npmEntry] : ['codex.exe'];
}

async function callCodex(input, record) {
  const cwd = await mkdtemp(join(tmpdir(), 'hybrid-demo-'));
  try {
    const [bin, ...prefix] = codexCommand();
    const args = [...prefix, '--ask-for-approval', 'never', 'exec',
      '--sandbox', 'read-only', '--skip-git-repo-check', '--ephemeral', '--json'];
    if (cloudModel) args.push('--model', cloudModel);
    const env = { ...process.env };
    delete env.OPENAI_API_KEY;
    delete env.CODEX_API_KEY;
    await measure(record, async () => {
      const stdout = await new Promise((resolve, reject) => {
        const child = spawn(bin, [...args, '-'], {
          cwd, env, timeout: 180000, windowsHide: true, stdio: ['pipe', 'pipe', 'ignore'],
        });
        let output = '';
        child.stdout.setEncoding('utf8');
        child.stdout.on('data', chunk => { output += chunk; });
        child.stdin.on('error', reject);
        child.on('error', reject);
        child.on('close', code => {
          if (code === 0) resolve(output);
          else reject(new Error('Codex execution failed'));
        });
        child.stdin.end(input, 'utf8');
      });
      for (const line of stdout.split(/\r?\n/).filter(Boolean)) {
        const event = JSON.parse(line);
        if (event.type === 'item.completed' && event.item?.type === 'agent_message') {
          record.output = publicOutput(event.item.text);
        }
        if (event.type === 'turn.completed') {
          record.inputTokens = event.usage?.input_tokens ?? null;
          record.outputTokens = event.usage?.output_tokens ?? null;
        }
      }
      if (record.output === null) throw new Error('Missing Codex output');
    });
  } finally {
    await rmdir(cwd);
  }
}

async function measure(record, operation) {
  record.gpuBefore = await readGpu();
  let sample;
  const gpuDuring = [];
  const timer = setInterval(() => {
    if (sample) return;
    sample = readGpu().then(gpus => {
      if (gpus) gpuDuring.push({ at: new Date().toISOString(), gpus });
    }).finally(() => { sample = undefined; });
  }, 500);
  const started = performance.now();
  try {
    await operation();
  } finally {
    record.elapsedMs = Math.round(performance.now() - started);
    clearInterval(timer);
    await sample;
    record.gpuDuring = gpuDuring.length ? gpuDuring : null;
  }
}

async function runReal() {
  const report = {
    measuredAt: new Date().toISOString(),
    os: { platform: process.platform, release: release(), arch: process.arch },
    node: process.version,
    results: [],
  };
  for (const [id, visibility, task, input] of examples) {
    const route = routeFor(visibility, task);
    if (route === 'hold') continue;
    const record = {
      id, route, input, model: route === 'local' ? localModel : cloudModel,
      quantization: null, elapsedMs: null, inputTokens: null, outputTokens: null,
      gpuBefore: null, gpuDuring: null, output: null, status: 'failed',
    };
    try {
      await (route === 'local' ? callOllama : callCodex)(input, record);
      record.status = 'ok';
    } catch {
      // Keep the other route runnable and omit raw errors from the report.
      process.exitCode = 1;
      console.error(`Case ${id} failed`);
    }
    report.results.push(record);
    await writeFile(new URL('./measured.json', import.meta.url), JSON.stringify(report, null, 2) + '\n');
  }
}

const mode = process.argv.slice(2);
if (mode.length === 0) await runMock();
else if (mode.length === 1 && mode[0] === '--real') await runReal();
else {
  console.error('Usage: node repro/demo.mjs [--real]');
  process.exitCode = 2;
}

セキュリティについて 私はAIを使う中で、新しい事故の事例や公開の指針を調べ、自分の決まりにし、点検して直すことを続けています。本コンテンツは、その実務の範囲で、AIを安全に使うために知っておきたいリスクと考え方を扱います。監査・認証や事故が起きたときの調査など、専門の対応が必要な場面では専門家にご相談ください。

投稿日: 2026/11/28 13:01:13

好き数: 0

投稿者: mocotcn
zenn.devで見る