> ## Documentation Index
> Fetch the complete documentation index at: https://private-7c7dfe99-detect-table-modification.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

> LAION 5Bデータセットからの1000万個のベクトルを含むデータセット

# LAION 5Bデータセット

export const Image = ({img, alt, size = "lg", background}) => {
  const normalizedSize = ["sm", "md", "lg"].includes(size) ? size : "lg";
  const backgroundColor = background === "white" ? "white" : background === "black" ? "rgb(31 31 28)" : undefined;
  return <div className={`ch-image-${normalizedSize}`}>
      <Frame>
        <img src={img} alt={alt} style={{
    backgroundColor
  }} />
      </Frame>
    </div>;
};

<div id="introduction">
  ## はじめに
</div>

[LAION 5Bデータセット](https://laion.ai/blog/laion-5b/) には、58.5億件の画像・テキスト埋め込みと、
関連する画像メタデータが含まれています。これらの埋め込みは、`Open AI CLIP` モデル [ViT-L/14](https://huggingface.co/sentence-transformers/clip-ViT-L-14) を使用して生成されました。各
埋め込みベクトルの次元は `768` です。

このデータセットは、大規模な
実運用のベクトル検索アプリケーションにおける設計、サイジング、性能面の検討に利用できます。また、テキストから画像への検索と
画像から画像への検索の両方に使用できます。

<div id="dataset-details">
  ## データセットの詳細
</div>

完全なデータセットは、[opendatalab/laion5b-downloader](https://github.com/opendatalab/laion5b-downloader) を使用してダウンロードできます。

ClickHouse は、1,000 万件のベクトルのサブセットをパブリック `S3` バケットで公開しています。
このサブセットは 1 つの `Parquet` ファイルに保存されています。

このデータセットに必要なストレージ容量とメモリ要件を見積もるため、まず [ドキュメント](/ja/reference/engines/table-engines/mergetree-family/annindexes) を参照してサイジングを行うことを推奨します。

<div id="steps">
  ## 手順
</div>

<Steps>
  <Step title="テーブルを作成する" id="create-table">
    埋め込みとそれに関連する属性を格納する`laion_5b_10m`テーブルを作成します。

    ```sql theme={null}
    CREATE TABLE laion_5b_10m
    (
        id UInt32,
        image_path String,
        caption String,
        NSFW Nullable(String) default 'unknown',
        similarity Float32,
        LICENSE Nullable(String),
        url String,
        key String,
        status LowCardinality(String),
        width Int32,
        height Int32,
        original_width Int32,
        original_height Int32,
        exif Nullable(String),
        md5 String,
        vector Array(Float32) CODEC(NONE)
    ) ENGINE = MergeTree ORDER BY (id)
    ```

    `id` は単純な連番の整数です。追加の属性は述語で使用でき、[ドキュメント](/ja/reference/engines/table-engines/mergetree-family/annindexes)で説明されている、後段フィルタリング／事前フィルタリングを組み合わせたベクトル類似度検索を理解するのに役立ちます。
  </Step>

  <Step title="データを読み込む" id="load-table">
    データセットを読み込むには、次の SQL ステートメントを実行します。

    ```sql theme={null}
    INSERT INTO laion_5b_10m SELECT * FROM s3('https://clickhouse-datasets.s3.amazonaws.com/laion-5b/laion5b_100m_part_1_of_10.parquet', NOSIGN);
    ```

    1,000 万行をテーブルに読み込むには、数分かかります。
  </Step>

  <Step title="総当たり方式でベクトル類似度検索を実行する" id="run-a-brute-force-vector-similarity-search">
    KNN (k近傍探索) または総当たり検索では、データセット内の各ベクトルと検索対象の埋め込みベクトルとの距離を計算し、距離順に並べることで最近傍を取得します。検索ベクトルには、データセット内のベクトルの1つを使用できます。例:

    ```sql title="Query" theme={null}
    SELECT id, url 
    FROM laion_5b_10m
    ORDER BY cosineDistance( vector, (SELECT vector FROM laion_5b_10m WHERE id = 9999) ) ASC
    LIMIT 20

    The vector in the row with id = 9999 is the embedding for an image of a Deli restaurant.
    ```

    ANN (ベクトル索引を使用) のクエリレイテンシと比較できるよう、クエリレイテンシを記録してください。
    1,000万行の場合、ベクトル索引を使用しない上記のクエリは完了までに数秒から数分かかることがあります。
  </Step>

  <Step title="ベクトル類似度索引を構築する" id="build-vector-similarity-index">
    以下の SQL を実行して、`laion_5b_10m` テーブルの `vector` カラムにベクトル類似度索引を定義し、構築します。

    ```sql theme={null}
    ALTER TABLE laion_5b_10m ADD INDEX vector_index vector TYPE vector_similarity('hnsw', 'cosineDistance', 768, 'bf16', 64, 512);

    ALTER TABLE laion_5b_10m MATERIALIZE INDEX vector_index SETTINGS mutations_sync = 2;
    ```

    索引の作成と検索に関するパラメータおよびパフォーマンス上の考慮事項については、[ドキュメント](/ja/reference/engines/table-engines/mergetree-family/annindexes)を参照してください。
    上記のステートメントでは、HNSW ハイパーパラメータ `M` と `ef_construction` にそれぞれ 64 と 512 を使用しています。
    索引のビルド時間と検索結果の品質を評価し、これらのパラメータに最適な値を慎重に選択する必要があります。

    1,000 万行のサブセットでは、利用可能な CPU コア数とストレージ帯域幅によっては、索引のビルドと保存にかなりの時間がかかる場合があります。
  </Step>

  <Step title="ANN 検索を実行する" id="perform-ann-search">
    ベクトル類似度索引が構築されると、ベクトル検索クエリで自動的にこの索引が使用されます。

    ```sql title="Query" theme={null}
    SELECT id, url 
    FROM laion_5b_10m
    ORDER BY cosineDistance( vector, (SELECT vector FROM laion_5b_10m WHERE id = 9999) ) ASC
    LIMIT 20

    ```

    ベクトル索引を初めてメモリに読み込む際は、数秒から数分かかる場合があります。
  </Step>

  <Step title="検索クエリの埋め込みを生成する" id="generating-embeddings-for-search-query">
    `LAION 5b` データセットの埋め込みベクトルは、`OpenAI CLIP` モデル `ViT-L/14` を使用して生成されています。

    以下の Python スクリプトの例では、`CLIP` API を使用してプログラムから埋め込みベクトルを生成する方法を示します。生成した検索用埋め込みベクトルは、`SELECT` クエリ内の [`cosineDistance()`](/ja/reference/functions/regular-functions/distance-functions#cosineDistance) 関数に引数として渡します。

    `clip` パッケージのインストール方法については、[OpenAI の GitHub リポジトリ](https://github.com/openai/clip)を参照してください。

    ```python theme={null}
    import torch
    import clip
    import numpy as np
    import sys
    import clickhouse_connect

    device = "cuda" if torch.cuda.is_available() else "cpu"
    model, preprocess = clip.load("ViT-L/14", device=device)

    # Search for images that contain both a dog and a cat
    text = clip.tokenize(["a dog and a cat"]).to(device)

    with torch.no_grad():
        text_features = model.encode_text(text)
        np_arr = text_features.detach().cpu().numpy()

        # Pass ClickHouse credentials here
        chclient = clickhouse_connect.get_client()

        params = {'v1': list(np_arr[0])}
        result = chclient.query("SELECT id, url FROM laion_5b_10m ORDER BY cosineDistance(vector, %(v1)s) LIMIT 100",
                                parameters=params)

        # Write the results to a simple HTML page that can be opened in the browser. Some URLs may have become obsolete.
        print("<html>")
        for r in result.result_rows:
            print("<img src = ", r[1], 'width="200" height="200">')
        print("</html>")
    ```

    上記の検索結果は以下のとおりです。

    <Image img="https://mintcdn.com/private-7c7dfe99-detect-table-modification/bx6sZ_fx0ABo_aFe/images/getting-started/example-datasets/laion5b_visualization_1.webp?fit=max&auto=format&n=bx6sZ_fx0ABo_aFe&q=85&s=842074a2dda9e847838902129fa55df5" alt="ベクトル類似度検索の結果" size="md" width="3400" height="1794" data-path="images/getting-started/example-datasets/laion5b_visualization_1.webp" />
  </Step>
</Steps>
