mcpField
T
transformers-js

transformers-js

github.com/huggingface開発11.2k2.1k 回インストール5 日前に更新
リポジトリ

transformers-js について

transformers-jsは、ブラウザーやNode.js、Bun、Denoなどのサーバー環境で機械学習モデルを実行するJavaScriptスキルです。Pythonサーバーなしで、テキスト、画像、音声、マルチモーダルの各タスクに対応します。

主な機能

  1. 01ブラウザーとサーバーでの推論
  2. 02テキスト分析・生成・翻訳
  3. 03画像分類・検出・セグメンテーション
  4. 04音声認識と音声処理
  5. 05マルチモーダルパイプライン
  6. 06CPU、WebGPU、量子化の選択

活用シーン

  1. 01JavaScriptアプリでのテキスト分析や生成
  2. 02ブラウザーでの画像・音声モデル実行
  3. 03バックエンドなしのマルチモーダルアプリ構築

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/huggingface/skills --skill transformers-js

インストール後、Claude Code で/transformers-jsを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

references/
CACHE.md
CONFIGURATION.md
EXAMPLES.md
MODEL_ARCHITECTURES.md
MODEL_REGISTRY.md
PIPELINE_OPTIONS.md
TEXT_GENERATION.md

詳細

Transformers.js - JavaScript 向け機械学習

Transformers.js を使うと、Python サーバーを必要とせず、ブラウザーやサーバーサイドのランタイム(Node.js、Bun、Deno)で、最先端の機械学習モデルを JavaScript から直接実行できます。

このスキルを使う場面

次のような場合に、このスキルを使用してください。

  • JavaScript でテキスト分析、生成、翻訳用の ML モデルを実行する
  • 画像分類、物体検出、セグメンテーションを行う
  • 音声認識やオーディオ処理を実装する
  • マルチモーダル AI アプリケーション(テキストから画像、画像からテキストなど)を構築する
  • バックエンドなしで、ブラウザー上のクライアント側でモデルを実行する

インストール

NPM によるインストール
npm install @huggingface/transformers
ブラウザーでの使用(CDN)
<script type="module">
  import { pipeline } from 'https://cdn.jsdelivr.net/npm/@huggingface/transformers';
</script>

基本概念

1. Pipeline API

Pipeline API は、モデルを使用する最も簡単な方法です。前処理、モデル推論、後処理をまとめて実行します。

import { pipeline } from '@huggingface/transformers';

// Create a pipeline for a specific task
const pipe = await pipeline('sentiment-analysis');

// Use the pipeline
const result = await pipe('I love transformers!');
// Output: [{ label: 'POSITIVE', score: 0.999817686 }]

// IMPORTANT: Always dispose when done to free memory
await pipe.dispose();

⚠️ メモリ管理: メモリリークを防ぐため、使用後はすべてのパイプラインで pipe.dispose() を呼び出して破棄する必要があります。さまざまな環境でのクリーンアップ方法については、コード例をご覧ください。

2. モデルの選択

2 番目の引数にカスタムモデルを指定できます。

const pipe = await pipeline(
  'sentiment-analysis',
  'Xenova/bert-base-multilingual-uncased-sentiment'
);

モデルの検索:

Hugging Face Hub で利用可能な Transformers.js モデルをご覧ください。

ヒント: タスクの種類で絞り込み、トレンド順またはダウンロード数順に並べ替え、モデルカードでパフォーマンス指標や使用例を確認してください。

3. デバイスの選択

モデルを実行する場所を選択します。

// Run on CPU (default for WASM)
const pipe = await pipeline('sentiment-analysis', 'model-id');

// Run on GPU (WebGPU)
const pipe = await pipeline('sentiment-analysis', 'model-id', {
  device: 'webgpu',
});
4. 量子化オプション

モデルの精度とパフォーマンスを調整します。

// Use quantized model (faster, smaller)
const pipe = await pipeline('sentiment-analysis', 'model-id', {
  dtype: 'q4',  // Options: 'fp32', 'fp16', 'q8', 'q4'
});

サポートされているタスク

注: 以下の例は、すべて基本的な使い方を示しています。

自然言語処理
テキスト分類
const classifier = await pipeline('text-classification');
const result = await classifier('This movie was amazing!');
固有表現認識(NER)
const ner = await pipeline('token-classification');
const entities = await ner('My name is John and I live in New York.');
質問応答
const qa = await pipeline('question-answering');
const answer = await qa({
  question: 'What is the capital of France?',
  context: 'Paris is the capital and largest city of France.'
});
テキスト生成
const generator = await pipeline('text-generation', 'onnx-community/gemma-3-270m-it-ONNX');
const text = await generator('Once upon a time', {
  max_new_tokens: 100,
  temperature: 0.7
});

ストリーミングとチャットについて: 以下の内容については、テキスト生成ガイド をご覧ください。

  • TextStreamer を使ったトークン単位のストリーミング出力
  • システム/ユーザー/アシスタントのロールを使ったチャット/会話形式
  • 生成パラメーター(temperature、top_k、top_p)
  • ブラウザーと Node.js の例
  • React コンポーネントと API エンドポイント
翻訳
const translator = await pipeline('translation', 'Xenova/nllb-200-distilled-600M');
const output = await translator('Hello, how are you?', {
  src_lang: 'eng_Latn',
  tgt_lang: 'fra_Latn'
});
要約
const summarizer = await pipeline('summarization');
const summary = await summarizer(longText, {
  max_length: 100,
  min_length: 30
});
ゼロショット分類
const classifier = await pipeline('zero-shot-classification');
const result = await classifier('This is a story about sports.', ['politics', 'sports', 'technology']);
コンピュータービジョン
画像分類
const classifier = await pipeline('image-classification');
const result = await classifier('https://example.com/image.jpg');
// Or with local file
const result = await classifier(imageUrl);
物体検出
const detector = await pipeline('object-detection');
const objects = await detector('https://example.com/image.jpg');
// Returns: [{ label: 'person', score: 0.95, box: { xmin, ymin, xmax, ymax } }, ...]
画像セグメンテーション
const segmenter = await pipeline('image-segmentation');
const segments = await segmenter('https://example.com/image.jpg');
深度推定
const depthEstimator = await pipeline('depth-estimation');
const depth = await depthEstimator('https://example.com/image.jpg');
ゼロショット画像分類
const classifier = await pipeline('zero-shot-image-classification');
const result = await classifier('image.jpg', ['cat', 'dog', 'bird']);
オーディオ処理
自動音声認識
const transcriber = await pipeline('automatic-speech-recognition');
const result = await transcriber('audio.wav');
// Returns: { text: 'transcribed text here' }
オーディオ分類
const classifier = await pipeline('audio-classification');
const result = await classifier('audio.wav');
テキスト読み上げ
const synthesizer = await pipeline('text-to-speech', 'Xenova/speecht5_tts');
const audio = await synthesizer('Hello, this is a test.', {
  speaker_embeddings: speakerEmbeddings
});
マルチモーダル
画像からテキスト(画像キャプション生成)
const captioner = await pipeline('image-to-text');
const caption = await captioner('image.jpg');
ドキュメントに関する質問応答
const docQA = await pipeline('document-question-answering');
const answer = await docQA('document-image.jpg', 'What is the total amount?');
ゼロショット物体検出
const detector = await pipeline('zero-shot-object-detection');
const objects = await detector('image.jpg', ['person', 'car', 'tree']);
特徴抽出(埋め込み)
const extractor = await pipeline('feature-extraction');
const embeddings = await extractor('This is a sentence to embed.');
// Returns: tensor of shape [1, sequence_length, hidden_size]

// For sentence embeddings (mean pooling)
const extractor = await pipeline('feature-extraction', 'onnx-community/all-MiniLM-L6-v2-ONNX');
const embeddings = await extractor('Text to embed', { pooling: 'mean', normalize: true });

モデルの検索と選択

Hugging Face Hub のモデルを探す

Hugging Face Hub で、Transformers.js と互換性のあるモデルを見つけます。

ベース URL(すべてのモデル):

https://huggingface.co/models?library=transformers.js&sort=trending

pipeline_tag パラメーターでタスクを絞り込む:

タスクURL
テキスト生成https://huggingface.co/models?pipeline_tag=text-generation&library=transformers.js&sort=trending
テキスト分類https://huggingface.co/models?pipeline_tag=text-classification&library=transformers.js&sort=trending
翻訳https://huggingface.co/models?pipeline_tag=translation&library=transformers.js&sort=trending
要約https://huggingface.co/models?pipeline_tag=summarization&library=transformers.js&sort=trending
質問応答https://huggingface.co/models?pipeline_tag=question-answering&library=transformers.js&sort=trending
画像分類https://huggingface.co/models?pipeline_tag=image-classification&library=transformers.js&sort=trending
物体検出https://huggingface.co/models?pipeline_tag=object-detection&library=transformers.js&sort=trending
画像セグメンテーションhttps://huggingface.co/models?pipeline_tag=image-segmentation&library=transformers.js&sort=trending
音声認識https://huggingface.co/models?pipeline_tag=automatic-speech-recognition&library=transformers.js&sort=trending
音声分類https://huggingface.co/models?pipeline_tag=audio-classification&library=transformers.js&sort=trending
画像からテキストへの変換https://huggingface.co/models?pipeline_tag=image-to-text&library=transformers.js&sort=trending
特徴抽出https://huggingface.co/models?pipeline_tag=feature-extraction&library=transformers.js&sort=trending
ゼロショット分類https://huggingface.co/models?pipeline_tag=zero-shot-classification&library=transformers.js&sort=trending

並べ替えオプション:

  • &sort=trending - 最近最も人気
  • &sort=downloads - 全期間で最もダウンロード数が多い
  • &sort=likes - コミュニティから最も多く「いいね」されている
  • &sort=modified - 最近更新されたもの
適切なモデルの選び方

モデルを選ぶ際は、次の要素を考慮してください。

1. モデルサイズ

  • 小(< 100MB):高速で、ブラウザーに適していますが、精度は限定的です
  • 中(100MB - 500MB):性能のバランスがよく、ほとんどの用途に適しています
  • 大(> 500MB):高精度ですが低速で、Node.js または高性能デバイスに適しています

2. 量子化 モデルには、異なる量子化レベルが用意されていることがよくあります。

  • fp32 - フル精度(最大サイズで、最も高精度)
  • fp16 - 半精度(サイズが小さく、精度も高い)
  • q8 - 8 ビット量子化(大幅に小型化されますが、精度はわずかに低下)
  • q4 - 4 ビット量子化(最小サイズですが、精度が目に見えて低下)

3. タスクとの互換性 モデルカードで次の項目を確認してください。

  • 対応タスク(複数のタスクに対応するモデルもあります)
  • 入力/出力形式
  • 言語の対応状況(多言語対応か英語のみか)
  • ライセンスの制限

4. 性能指標 モデルカードには通常、次の情報が記載されています。

  • 精度スコア
  • ベンチマーク結果
  • 推論速度
  • メモリ要件
例:テキスト生成モデルを探す
// 1. Visit: https://huggingface.co/models?pipeline_tag=text-generation&library=transformers.js&sort=trending

// 2. Browse and select a model (e.g., onnx-community/gemma-3-270m-it-ONNX)

// 3. Check model card for:
//    - Model size: ~270M parameters
//    - Quantization: q4 available
//    - Language: English
//    - Use case: Instruction-following chat

// 4. Use the model:
import { pipeline } from '@huggingface/transformers';

const generator = await pipeline(
  'text-generation',
  'onnx-community/gemma-3-270m-it-ONNX',
  { dtype: 'q4' } // Use quantized version for faster inference
);

const output = await generator('Explain quantum computing in simple terms.', {
  max_new_tokens: 100
});

await generator.dispose();
モデル選択のヒント
  1. 小さく始める:まず小さなモデルでテストし、必要に応じてより大きなモデルに切り替えます
  2. ONNX 対応を確認する:モデルに ONNX ファイルがあることを確認します(モデルリポジトリ内の onnx フォルダーを探してください)
  3. モデルカードを読む:モデルカードには使用例、制限事項、ベンチマークが記載されています
  4. ローカルでテストする:お使いの環境で推論速度とメモリ使用量をベンチマークします
  5. ライブラリで絞り込む:library=transformers.js を使って互換性のあるモデルを見つけます:https://huggingface.co/models?library=transformers.js
  6. バージョンを固定する:本番環境で安定性を確保するため、特定の git コミットを使用します:
    const pipe = await pipeline('task', 'model-id', { revision: 'abc123' });
    

高度な設定

環境設定(env)

env オブジェクトを使うと、Transformers.js の実行、キャッシュ、モデルの読み込みを包括的に制御できます。

概要:

import { env, LogLevel } from '@huggingface/transformers';

// View version
console.log(env.version); // e.g., '4.x'

// Common settings
env.allowRemoteModels = true;  // Load from Hugging Face Hub
env.allowLocalModels = false;  // Load from file system
env.localModelPath = '/models/'; // Local model directory
env.useFSCache = true;         // Cache models on disk (Node.js)
env.useBrowserCache = true;    // Cache models in browser
env.cacheDir = './.cache';     // Cache directory location
// Optional: override logging level (default is LogLevel.WARNING)
env.logLevel = LogLevel.INFO;

// Optional: custom fetch for auth headers, retries, abort signals, etc.
env.fetch = (url, options) =>
  fetch(url, {
    ...options,
    headers: {
      ...options?.headers,
      Authorization: `Bearer ${HF_TOKEN}`,
    },
  });

設定パターン:

// Development: Fast iteration with remote models
env.allowRemoteModels = true;
env.useFSCache = true;

// Production: Local models only
env.allowRemoteModels = false;
env.allowLocalModels = true;
env.localModelPath = '/app/models/';

// Custom CDN
env.remoteHost = 'https://cdn.example.com/models';

// Disable caching (testing)
env.useFSCache = false;
env.useBrowserCache = false;

すべての設定オプション、キャッシュ戦略、キャッシュ管理、モデルの事前ダウンロードなどの詳細については、以下を参照してください。

→ 設定リファレンス

ModelRegistry(v4)

ModelRegistry を使うと、パイプラインを読み込む前にモデルのアセットを確認し、制御できます。ダウンロードサイズの見積もり、キャッシュの状態の確認、利用可能な dtype の確認、特定のタスク/モデル/オプションの組み合わせに対するキャッシュ済みアーティファクトの削除に利用できます。

import { ModelRegistry } from '@huggingface/transformers';

const task = 'feature-extraction';
const modelId = 'onnx-community/all-MiniLM-L6-v2-ONNX';
const modelOptions = { dtype: 'fp32' };

// List required files for this pipeline
const files = await ModelRegistry.get_pipeline_files(task, modelId, modelOptions);

// Check if assets are already cached
const cached = await ModelRegistry.is_pipeline_cached(task, modelId, modelOptions);

// Inspect precision formats available for this model
const dtypes = await ModelRegistry.get_available_dtypes(modelId);

console.log({ files: files.length, cached, dtypes });

本番環境でのパターンと API の全容については、**ModelRegistry リファレンス**を参照してください。

トークン化のみの処理(@huggingface/tokenizers)

トークン化のみのワークフローには、@huggingface/tokenizers を使用してください。これは軽量な独立パッケージで、モデルの推論パイプライン全体を読み込まずに高速なトークン化/エンコードが必要な場合に役立ちます。

npm install @huggingface/tokenizers
import { Tokenizer } from '@huggingface/tokenizers';
テンソルの操作
import { AutoTokenizer, AutoModel } from '@huggingface/transformers';

// Load tokenizer and model separately for more control
const tokenizer = await AutoTokenizer.from_pretrained('bert-base-uncased');
const model = await AutoModel.from_pretrained('bert-base-uncased');

// Tokenize input
const inputs = await tokenizer('Hello world!');

// Run model
const outputs = await model(inputs);
バッチ処理
const classifier = await pipeline('sentiment-analysis');

// Process multiple texts
const results = await classifier([
  'I love this!',
  'This is terrible.',
  'It was okay.'
]);

ランタイム固有の考慮事項

WebGPU の使用

WebGPU は、ブラウザーやサーバーサイドのランタイム(サポートされている場合)で GPU アクセラレーションを提供します。

const pipe = await pipeline('text-generation', 'onnx-community/gemma-3-270m-it-ONNX', {
  device: 'webgpu',
  dtype: 'fp32'
});

注:利用可能な場合は webgpu を使用し、現在のランタイムでサポートされていない場合は WASM/CPU にフォールバックしてください。

WASM のパフォーマンス

WASM は、さまざまなランタイムで最も互換性の高い実行バックエンドです。

// Optimized for browsers with quantization
const pipe = await pipeline('sentiment-analysis', 'model-id', {
  dtype: 'q8'  // or 'q4' for even smaller size
});
進捗状況の追跡と読み込みインジケーター

モデルは数 MB から数 GB に及ぶ場合があり、複数のファイルで構成されています。pipeline() 関数にコールバックを渡して、ダウンロードの進捗状況を追跡できます。

import { pipeline } from '@huggingface/transformers';

// Track progress for each file
const fileProgress = {};

function onProgress(info) {
  if (info.status === 'progress_total') {
    console.log(`Total: ${info.progress.toFixed(1)}%`);
    return;
  }

  console.log(`${info.status}: ${info.file ?? ''}`);
  
  if (info.status === 'progress') {
    fileProgress[info.file] = info.progress;
    console.log(`${info.file}: ${info.progress.toFixed(1)}%`);
  }
  
  if (info.status === 'done') {
    console.log(`✓ ${info.file} complete`);
  }
}

// Pass callback to pipeline
const classifier = await pipeline('sentiment-analysis', null, {
  progress_callback: onProgress
});

進捗情報のプロパティ:

interface ProgressInfo {
  status: 'initiate' | 'download' | 'progress' | 'progress_total' | 'done' | 'ready';
  name: string;      // Model id or path
  file?: string;     // File being processed (per-file events)
  progress?: number; // Percentage (0-100, for 'progress' and 'progress_total')
  loaded?: number;   // Bytes downloaded (only for 'progress' status)
  total?: number;    // Total bytes (only for 'progress' status)
}

ブラウザー UI、React コンポーネント、CLI の進捗バー、再試行ロジックなどを含む完全な例については、以下を参照してください。

→ パイプラインのオプション - 進捗コールバック

エラー処理

try {
  const pipe = await pipeline('sentiment-analysis', 'model-id');
  const result = await pipe('text to analyze');
} catch (error) {
  if (error.message.includes('fetch')) {
    console.error('Model download failed. Check internet connection.');
  } else if (error.message.includes('ONNX')) {
    console.error('Model execution failed. Check model compatibility.');
  } else {
    console.error('Unknown error:', error);
  }
}

パフォーマンスのヒント

  1. パイプラインを再利用する:パイプラインは一度作成し、複数の推論で再利用します
  2. 量子化を使用する:より高速な推論を実現するため、まず q8 または q4 を使用します
  3. バッチ処理:可能な場合は、複数の入力をまとめて処理します
  4. モデルをキャッシュする:モデルは自動的にキャッシュされます(ブラウザーの Cache API、Node.js のファイルシステムキャッシュ、カスタム実装の詳細については、**キャッシュのリファレンス**を参照してください)
  5. 大規模モデルには WebGPU を使用する:GPU アクセラレーションの効果があるモデルには WebGPU を使用します
  6. コンテキストを制限する:テキスト生成では、メモリーの問題を避けるため max_new_tokens を制限します
  7. リソースをクリーンアップする:メモリーを解放するため、処理が完了したら pipe.dispose() を呼び出します

メモリー管理

**重要:**メモリーリークを防ぐため、処理が完了したら必ず pipe.dispose() を呼び出してください。

const pipe = await pipeline('sentiment-analysis');
const result = await pipe('Great product!');
await pipe.dispose();  // ✓ Free memory (100MB - several GB per model)

破棄するタイミング:

  • アプリケーションの終了時またはコンポーネントのアンマウント時
  • 別のモデルを読み込む前
  • 長時間稼働するアプリでのバッチ処理後

モデルは大量のメモリーを消費し、GPU/CPU リソースを保持します。破棄は、ブラウザーのメモリー制限を守り、サーバーの安定性を確保するうえで重要です。

詳細なパターン(React のクリーンアップ、サーバー、ブラウザー)については、**コード例**を参照してください。

トラブルシューティング

モデルが見つからない
  • モデルが Hugging Face Hub に存在することを確認してください
  • モデル名のスペルを確認してください
  • モデルに ONNX ファイルがあることを確認してください(モデルリポジトリ内の onnx フォルダーを確認します)
メモリーの問題
  • 小さなモデルまたは量子化済みモデル(dtype: 'q4')を使用してください
  • バッチサイズを小さくしてください
  • max_length でシーケンス長を制限してください
WebGPU のエラー
  • ブラウザーの互換性を確認してください(Chrome 113+、Edge 113+)
  • fp32 で失敗する場合は dtype: 'fp16' を試してください
  • WebGPU が利用できない場合は WASM にフォールバックしてください

リファレンスドキュメント

このスキル
公式 Transformers.js

ベストプラクティス

  1. パイプラインは必ず破棄する:メモリーリークを防ぐために、使用後は pipe.dispose() を呼び出します
  2. まずはパイプラインを使う:細かな制御が必要な場合を除き、パイプライン API を使用します
  3. まずローカルでテストする:デプロイ前に、小さな入力でモデルをテストします
  4. モデルサイズを確認する:Web アプリケーションでは、モデルのダウンロードサイズに注意します
  5. 読み込み状態を処理する:より良い UX のために、進行状況インジケーターを表示します
  6. バージョンを固定する:本番環境の安定性を確保するため、特定のモデルバージョンを固定します
  7. エラーバウンダリー:パイプラインの呼び出しは必ず try-catch ブロックで囲みます
  8. 段階的な機能強化:未対応のブラウザー向けにフォールバックを用意します
  9. モデルを再利用する:一度読み込んで何度も使い、不必要にパイプラインを再作成しないようにします
  10. 安全にシャットダウンする:サーバーでは SIGTERM/SIGINT 時にモデルを破棄します

クイックリファレンス:タスク ID

タスクタスク ID
テキスト分類text-classification or sentiment-analysis
トークン分類token-classification or ner
質問応答question-answering
マスク補完fill-mask
要約summarization
翻訳translation
テキスト生成text-generation
テキストからテキストへの生成text2text-generation
ゼロショット分類zero-shot-classification
画像分類image-classification
画像セグメンテーションimage-segmentation
物体検出object-detection
深度推定depth-estimation
画像から画像への変換image-to-image
ゼロショット画像分類zero-shot-image-classification
ゼロショット物体検出zero-shot-object-detection
自動音声認識automatic-speech-recognition
音声分類audio-classification
テキスト読み上げtext-to-speech or text-to-audio
画像からテキストへの変換image-to-text
ドキュメント質問応答document-question-answering
特徴抽出feature-extraction
文の類似度sentence-similarity

このスキルを使うと、別個の ML サーバーや Python 環境を用意することなく、最先端の機械学習機能を JavaScript アプリケーションに直接統合できます。

コメント