> ## Documentation Index
> Fetch the complete documentation index at: https://wb-21fd5541-feature-automate-reference-docs-generation.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Huggingface

<Warning>
  このページに表示されているすべてのコードサンプルはPythonで書かれています。
</Warning>

このページでは、[Hugging Face Hub](https://hf.co/) をW\&B Weaveと統合して、機械学習アプリケーションを追跡および分析する方法について説明します。モデルの推論をログに記録し、関数呼び出しをモニタリングし、Weaveのトレースおよびバージョン管理機能を使用して実験を整理する方法を学びます。提供されている例に従うことで、貴重な洞察を取得し、アプリケーションを効率的にデバッグし、異なるモデル構成を比較することができます—すべてWeaveウェブインターフェイス内で。

<Tip>
  **Google ColabでWeaveとHugging Face Hubを試す**
  セットアップなしでHugging Face HubとWeaveを試してみたいですか？ここで紹介するコードサンプルをGoogle Colab上のJupyter Notebookとして試すことができます。

  <a target="_blank" href="https://colab.research.google.com/github/wandb/examples/blob/master/weave/docs/quickstart_huggingface.ipynb">
    <img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab" />
  </a>
</Tip>

## 概要

[Hugging Face Hub](https://hf.co/) は、クリエイターやコラボレーター向けの機械学習プラットフォームであり、さまざまなプロジェクト用の事前トレーニング済みモデルとデータセットの膨大なコレクションを提供しています。

この`huggingface_hub` Pythonライブラリは、Hub上でホストされているモデルに対して複数のサービスにわたる推論を実行するための統一されたインターフェースを提供します。これらのモデルは[`InferenceClient`](https://huggingface.co/docs/huggingface_hub/en/package_reference/inference_client).

Weaveは自動的に[`InferenceClient`](https://huggingface.co/docs/huggingface_hub/en/package_reference/inference_client)のトレースをキャプチャします。追跡を開始するには、`weave.init()` を呼び出し、通常通りライブラリを使用します。

## 前提条件

1. Weaveで`huggingface_hub` を使用する前に、必要なライブラリをインストールするか、最新バージョンにアップグレードする必要があります。次のコマンドは`huggingface_hub` と`weave` をインストールするか、すでにインストールされている場合は最新バージョンにアップグレードし、インストール出力を減らします。

   ```python
   pip install -U huggingface_hub weave -qqq
   ```

2. Hugging Face Hub上のモデルで推論を使用するには、[User Access Token](https://huggingface.co/docs/hub/security-tokens)を設定します。トークンは[Hugging Face Hub Settings page](https://huggingface.co/settings/tokens) から設定するか、プログラムで設定することができます。次のコードサンプルは、ユーザーに`HUGGINGFACE_TOKEN` の入力を求め、トークンを環境変数として設定します。

   ```python
   import os
   import getpass

   os.environ["HUGGINGFACE_TOKEN"] = getpass.getpass("Enter your Hugging Face Hub Token: ")
   ```

## 基本的なトレース

言語モデルアプリケーションのトレースを中央の場所に保存することは、開発中および本番環境で不可欠です。これらのトレースはデバッグに役立ち、アプリケーションを改善するための貴重なデータセットとして機能します。

Weaveは自動的に[`InferenceClient`](https://huggingface.co/docs/huggingface_hub/en/package_reference/inference_client)のトレースをキャプチャします。追跡を開始するには、`weave.init()` を呼び出してWeaveを初期化し、その後通常通りライブラリを使用します。

次の例は、Weaveを使用してHugging Face Hubへの推論呼び出しをログに記録する方法を示しています：

```python
import weave
from huggingface_hub import InferenceClient

# Initialize Weave
weave.init(project_name="quickstart-huggingface")

# Initialize Hugging Face Inference Client
huggingface_client = InferenceClient(
    api_key=os.environ.get("HUGGINGFACE_TOKEN")
)

# Make a chat completion inference call to the Hugging Face Hub with the Llama-3.2-11B-Vision-Instruct model
image_url = "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg"
response = huggingface_client.chat_completion(
    model="meta-llama/Llama-3.2-11B-Vision-Instruct",
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "image_url", "image_url": {"url": image_url}},
                {"type": "text", "text": "Describe this image in one sentence."},
            ],
        }
    ],
    max_tokens=500,
    seed=42,
)
```

上記のコードが実行された後、WeaveはHugging Face Inference Clientで行われたすべてのLLM呼び出しを追跡してログに記録します。これらのトレースはWeaveウェブインターフェイスで確認できます。

![Weave logs each inference call, providing details about inputs, outputs, and metadata.](https://mintlify.s3.us-west-1.amazonaws.com/wb-21fd5541-feature-automate-reference-docs-generation/ja/guides/integrations/imgs/huggingface/trace_call.png)

Weaveは各推論呼び出しをログに記録し、入力、出力、およびメタデータに関する詳細を提供します。

![Weave also renders the call as a chat view in the UI, displaying the entire chat history with the model.](https://mintlify.s3.us-west-1.amazonaws.com/wb-21fd5541-feature-automate-reference-docs-generation/ja/guides/integrations/imgs/huggingface/trace_chat.png)

WeaveはUIでの呼び出しをチャットビューとしてレンダリングし、モデルとの完全なチャット履歴を表示します。

## 関数をトレースする

アプリケーションを通じてデータがどのように流れるかについてより深い洞察を得るために、`@weave.op` を使用して関数呼び出しを追跡できます。これにより、入力、出力、および実行ロジックがキャプチャされ、デバッグとパフォーマンス分析に役立ちます。

複数のopsをネストすることで、追跡された関数の構造化されたツリーを構築できます。Weaveはコードも自動的にバージョン管理し、実験中の中間状態を保存します。これはGitに変更をコミットする前でも行われます。

追跡を開始するには、追跡したい関数を`@weave.op`でデコレートします。

次の例では、Weaveは3つの関数を追跡します：`generate_image`、`check_image_correctness`、および`generate_image_and_check_correctness`。これらの関数は画像を生成し、それが与えられたプロンプトに一致するかどうかを検証します。

```python
import base64
from PIL import Image


def encode_image(pil_image):
    import io
    buffer = io.BytesIO()
    pil_image.save(buffer, format="JPEG")
    buffer.seek(0)
    encoded_image = base64.b64encode(buffer.read()).decode("utf-8")
    return f"data:image/jpeg;base64,{encoded_image}"


@weave.op
def generate_image(prompt: str):
    return huggingface_client.text_to_image(
        prompt=prompt,
        model="black-forest-labs/FLUX.1-schnell",
        num_inference_steps=4,
    )


@weave.op
def check_image_correctness(image: Image.Image, image_generation_prompt: str):
    return huggingface_client.chat_completion(
        model="meta-llama/Llama-3.2-11B-Vision-Instruct",
        messages=[
            {
                "role": "user",
                "content": [
                    {"type": "image_url", "image_url": {"url": encode_image(image)}},
                    {
                        "type": "text",
                        "text": f"Is this image correct for the prompt: {image_generation_prompt}? Answer with only one word: yes or no",
                    },
                ],
            }
        ],
        max_tokens=500,
        seed=42,
    ).choices[0].message.content


@weave.op
def generate_image_and_check_correctness(prompt: str):
    image = generate_image(prompt)
    return {
        "image": image,
        "is_correct": check_image_correctness(image, prompt),
    }


response = generate_image_and_check_correctness("A cute puppy")
```

Weaveは`@weave.op`でラップされたすべての関数呼び出しをログに記録し、Weave UIで実行の詳細を分析できるようにします。

![Weave now logs all function calls wrapped with @weave.op, allowing you to analyze execution details in the Weave UI. Weave also captures and visualizes function execution, helping you to understand data flow and logic within your application.](https://mintlify.s3.us-west-1.amazonaws.com/wb-21fd5541-feature-automate-reference-docs-generation/ja/guides/integrations/imgs/huggingface/trace_ops.png)

Weaveは関数の実行もキャプチャして視覚化し、アプリケーション内のデータフローとロジックを理解するのに役立ちます。

## `Model`を実験に使用する

複数のコンポーネントが関与する場合、LLM実験の管理は難しくなることがあります。Weaveの[`Model`](../core-types/models.mdx) クラスは、システムプロンプトやモデル構成などの実験の詳細をキャプチャして整理するのに役立ち、異なるイテレーションを簡単に比較できるようにします。

コードのバージョン管理と入出力のキャプチャに加えて、`Model` はアプリケーションの動作を制御する構造化されたパラメータを保存します。これにより、どの構成が最良の結果をもたらしたかを追跡しやすくなります。Weave`Model` をWeave[Serve](../tools/serve.mdx) および[Evaluations](../evaluation/scorers.mdx) と統合して、さらなる洞察を得ることもできます。

以下の例では、旅行の推薦のための`CityVisitRecommender` モデルを定義しています。そのパラメータを変更するたびに新しいバージョンが生成され、実験が容易になります。

```python
import rich


class CityVisitRecommender(weave.Model):
    model: str
    temperature: float = 0.7
    max_tokens: int = 500
    seed: int = 42

    @weave.op()
    def predict(self, city: str) -> str:
        return huggingface_client.chat_completion(
            model=self.model,
            messages=[
                {
                    "role": "system",
                    "content": "You are a helpful assistant meant to suggest places to visit in a city",
                },
                {"role": "user", "content": city},
            ],
            max_tokens=self.max_tokens,
            temperature=self.temperature,
            seed=self.seed,
        ).choices[0].message.content


city_visit_recommender = CityVisitRecommender(
    model="meta-llama/Llama-3.2-11B-Vision-Instruct",
    temperature=0.7,
    max_tokens=500,
    seed=42,
)
rich.print(city_visit_recommender.predict("New York City"))
rich.print(city_visit_recommender.predict("Paris"))
```

Weaveは自動的にモデルをログに記録し、異なるバージョンを追跡するため、パフォーマンスと実験履歴を簡単に分析できます。

![Weave automatically logs models and tracks different versions, making it easy to analyze performance and experiment history.](https://mintlify.s3.us-west-1.amazonaws.com/wb-21fd5541-feature-automate-reference-docs-generation/ja/guides/integrations/imgs/huggingface/trace_model.png)
