> ## Documentation Index
> Fetch the complete documentation index at: https://docs.coreweave.com/llms.txt
> Use this file to discover all available pages before exploring further.

> W&B アーティファクト を作成してログします。アーティファクト に 1 つ以上のファイルまたは URI 参照を追加する方法を説明します。

# アーティファクトを作成する

W\&B Python SDK を使用すると、[W\&B run](/ja/products/wandb/ref/python/experiments/run) からアーティファクトを作成できます。アーティファクトには、[ファイル、ディレクトリ、URI、および並列 run のファイル](#add-files-to-an-artifact)を追加できます。ファイルを追加したら、そのアーティファクトを W\&B サーバー または[独自のプライベートサーバー](/ja/products/wandb/platform/hosting/hosting-options/self-managed)に保存します。各アーティファクトは 1 つの run に関連付けられます。

Amazon S3 に保存されたファイルなどの外部ファイルをトラッキングする方法については、[外部ファイルをトラッキングする](/ja/products/wandb/artifacts/track-external-files)ページを参照してください。

<h2 id="construct-an-artifact">
  アーティファクトを構築する
</h2>

[W\&B アーティファクト](/ja/products/wandb/ref/python/experiments/artifact) は、次の 3 つのステップで構築します。

1. [`wandb.Artifact()` でアーティファクトの Python オブジェクトを作成する](/ja/products/wandb/artifacts/construct-an-artifact#create-an-artifact-python-object-with-wandb-artifact)
2. [アーティファクトに 1 つ以上のファイルを追加する](/ja/products/wandb/artifacts/construct-an-artifact#add-one-or-more-files-to-the-artifact)
3. [アーティファクトを W\&B サーバーに保存する](/ja/products/wandb/artifacts/construct-an-artifact#save-your-artifact-to-the-w\&b-server)

<h3 id="create-an-artifact-python-object-with-wandbartifact">
  `wandb.Artifact()` でアーティファクトの Python オブジェクトを作成する
</h3>

[`wandb.Artifact()`](/ja/products/wandb/ref/python/experiments/artifact) クラスを初期化して、アーティファクト オブジェクトを作成します。次のパラメーターを指定してください。

* **Name**: アーティファクトの名前です。一意でわかりやすく、覚えやすい名前を付けてください。
* **Type**: アーティファクトのタイプです。シンプルでわかりやすく、機械学習パイプラインの 1 つのステップに対応するタイプを指定してください。一般的なアーティファクト タイプには `'dataset'` や `'model'` があります。

<Note>
  W\&B は、指定された「name」と「type」を使用して、W\&B App 内に有向非巡回グラフを作成します。詳細については、[Explore and traverse artifact graphs](/ja/products/wandb/artifacts/explore-and-traverse-an-artifact-graph) を参照してください。
</Note>

次のコード スニペットをコピー＆ペーストして、アーティファクト オブジェクトを作成します。プレースホルダー `"artifact-name"` と `"artifact-type"` は、実際の値に置き換えてください。

```python theme={"system"}
import wandb

# アーティファクト オブジェクトを作成します
artifact = wandb.Artifact(name="artifact-name", type="artifact-type")
```

<Info>
  タイプが異なる場合でも、同じ名前のアーティファクトを複数作成することはできません。たとえば、タイプが `dataset` の `cats` という名前のアーティファクトと、タイプが `model` の `cats` という名前の別のアーティファクトを作成することはできません。
</Info>

アーティファクト オブジェクトを初期化する際に、説明、メタデータ、ダイジェスト アルゴリズム、その他のパラメーターをオプションで指定できます。

たとえば、次のコード スニペットは、名前、タイプ、説明、メタデータ、ダイジェスト アルゴリズムを指定してアーティファクト オブジェクトを作成します。

```python theme={"system"}
import wandb
# アーティファクト オブジェクトを作成します
artifact = wandb.Artifact(
    name="my-dataset",
    type="dataset",
    description="This is my dataset artifact",
    metadata={"source": "generated", "version": 1},
    digest_algorithm="XXH128"
)
```

<Note>
  MD5 は引き続きデフォルトのダイジェストアルゴリズムです。W\&B Python SDK 0.29.0 以降では、`digest_algorithm="XXH128"` を設定することで、新しいアーティファクトに対してより高速なハッシュ処理を選択できます。MD5 を使用している既存のアーティファクト コレクションでは、引き続き MD5 が使用されます。0.29.0 より前のバージョンの SDK では、XXH128 のエントリを含むアーティファクトを `Artifact.verify()` で検証できません。
</Note>

使用可能な属性とパラメーターの詳細については、Python SDK リファレンスガイドにある [`wandb.Artifact`](/ja/products/wandb/ref/python/experiments/artifact) クラスの定義を参照してください。

<h3 id="add-one-or-more-files-to-the-artifact">
  アーティファクトに 1 つ以上のファイルを追加する
</h3>

アーティファクト オブジェクトには、[ファイル、ディレクトリ、外部 URI 参照 (Amazon S3 など) などを追加](/ja/products/wandb/artifacts/construct-an-artifact#add-files-to-an-artifact)できます。

ファイルを 1 つ追加するには、アーティファクト オブジェクトの [`Artifact.add_file()`](/ja/products/wandb/ref/python/experiments/artifact#add_file) メソッドを使用します。

```python theme={"system"}
artifact.add_file(local_path="path/to/file.txt", name="artifact-name")
```

ディレクトリを追加するには、[`Artifact.add_dir()`](/ja/products/wandb/ref/python/experiments/artifact#add_dir) メソッドを使用します：

```python theme={"system"}
artifact.add_dir(local_path="path/to/directory", name="artifact-name")
```

さまざまなタイプのファイルをアーティファクトに追加する方法について詳しくは、次のセクション「[アーティファクトにファイルを追加する](/ja/products/wandb/artifacts/construct-an-artifact#add-files-to-an-artifact)」を参照してください。

<h3 id="save-your-artifact-to-the-wb-server">
  アーティファクトを W\&B サーバーに保存する
</h3>

アーティファクトを W\&B サーバーに保存します。保存するには、Run オブジェクトの [`wandb.Run.log_artifact()`](/ja/products/wandb/ref/python/experiments/run#log_artifact) メソッドを使用します。

```python theme={"system"}
with wandb.init(project="<project>", job_type="<job-type>") as run:
    run.log_artifact(artifact)
```

<Tip>
  **`wandb.Run.log_artifact()` と `Artifact.save()` の使い分け**

  * 新しいアーティファクトを作成して特定の run に関連付けるには、`wandb.Run.log_artifact()` を使用します。
  * 新しい run を作成せずに既存のアーティファクトを更新するには、`Artifact.save()` を使用します。
</Tip>

ここまでの内容をまとめると、次のコードスニペットのようになります。データセットアーティファクトを作成し、そのアーティファクトにファイルを追加して、W\&B に保存します。

```python theme={"system"}
import wandb

artifact = wandb.Artifact(name="artifact-name", type="artifact-type")
artifact.add_file(local_path="path/to/file.txt", name="filename")
artifact.add_dir(local_path="path/to/directory", name="filename")

with wandb.init(project="<project>", job_type="<job-type>") as run:
    run.log_artifact(artifact)
```

同じ名前とタイプでアーティファクトをログするたびに、W\&B はそのアーティファクトの新しいバージョンを作成します。詳細については、[新しいアーティファクトのバージョンを作成する](/ja/products/wandb/artifacts/create-a-new-artifact-version)を参照してください。

<Warning>
  W\&B は、アップロードのパフォーマンスを高めるために `wandb.Run.log_artifact()` の呼び出しを非同期で実行します。そのため、ループ内でアーティファクトをログすると、予期しない動作が発生することがあります。例:

  ```python theme={"system"}
  with wandb.init() as run:
      for i in range(10):
          a = wandb.Artifact(name = "race",
              type="dataset",
              metadata={
                  "index": i,
              },
          )
          # ... アーティファクト a にファイルを追加 ...
          run.log_artifact(a)
  ```

  アーティファクトは任意の順序でログされる可能性があるため、アーティファクトのバージョン **v0** のメタデータのインデックスが 0 であるとは限りません。
</Warning>

<h2 id="add-files-to-an-artifact">
  アーティファクトにファイルを追加する
</h2>

以下のセクションでは、さまざまなタイプのオブジェクトをアーティファクトに追加する方法を説明します。以降の例では、次のような構造のディレクトリがあるものとします。

```text theme={"system"}
root-directory
| - hello.txt
| - images/
| -- | cat.png
| -- | dog.png
| - checkpoints/
| -- | model.h5
| - models/
| -- | model.h5
```

<h3 id="add-a-single-file">
  単一のファイルを追加する
</h3>

ローカルファイルを 1 つアーティファクトに追加するには、[`wandb.Artifact.add_file()`](/ja/products/wandb/ref/python/experiments/artifact#method-artifact-add-file) を使用します。`local_path` パラメーターにファイルのローカルパスを指定します：

```python theme={"system"}
import wandb

# アーティファクト オブジェクトを初期化します
artifact = wandb.Artifact(name="artifact-name", type="artifact-type")

# ファイルを 1 つ追加します
artifact.add_file(local_path="path/file.format")
```

たとえば、ローカルの作業ディレクトリに `'hello.txt'` というファイルがあるとします。

```python theme={"system"}
artifact.add_file("hello.txt")
```

これで、アーティファクトの内容は次のようになります。

```text theme={"system"}
hello.txt
```

必要に応じて、`name` パラメーターに別の名前を渡すと、アーティファクト オブジェクト内でファイルをリネームできます。前の例に続けて、次のように記述します。

```python theme={"system"}
artifact.add_file(
    local_path="hello.txt", 
    name="new/path/hello_world.txt"
    )
```

アーティファクトは次のように保存されます：

```text theme={"system"}
new/path/hello_world.txt
```

次の表は、API 呼び出しの違いによってアーティファクトの内容がどのように変わるかを示しています。

| API 呼び出し | 作成されるアーティファクト |
| - | - |
| `artifact.new_file('hello.txt')` | `hello.txt` |
| `artifact.add_file('model.h5')` | `model.h5` |
| `artifact.add_file('checkpoints/model.h5')` | `model.h5` |
| `artifact.add_file('model.h5', name='models/mymodel.h5')` | `models/mymodel.h5` |

<h3 id="add-multiple-files">
  複数のファイルを追加する
</h3>

ローカルディレクトリ内の複数のファイルをアーティファクトに追加するには、[`wandb.Artifact.add_dir()`](/ja/products/wandb/ref/python/experiments/artifact#method-artifact-add-dir) メソッドを使用します。`local_path` パラメーターには、対象ディレクトリのローカルパスを指定します。

```python theme={"system"}
import wandb

# アーティファクト オブジェクトを初期化します
artifact = wandb.Artifact(name="artifact-name", type="artifact-type")

# ローカル ディレクトリをアーティファクトに追加します
artifact.add_dir(local_path="path/file.format", name="optional-prefix")
```

次の表は、API 呼び出しによってアーティファクトの内容がどのように変わるかを示しています。

| API 呼び出し | 生成されるアーティファクト |
| - | - |
| `artifact.add_dir('images')` | <p><code>cat.png</code></p><p><code>dog.png</code></p> |
| `artifact.add_dir('images', name='images')` | <p><code>images/cat.png</code></p><p><code>images/dog.png</code></p> |

<h3 id="add-a-uri-reference">
  URI 参照を追加する
</h3>

URI のスキームが W\&B ライブラリでサポートされている場合、アーティファクトは再現性を確保するためにチェックサムなどの情報をトラッキングします。

[`wandb.Artifact.add_reference()`](/ja/products/wandb/ref/python/experiments/artifact#method-artifact-add-reference) メソッドを使用して、外部 URI 参照をアーティファクトに追加します。`'uri'` 文字列はご自身の URI に置き換えてください。必要に応じて、アーティファクト内の配置先パスを name パラメーターに指定することもできます。

```python theme={"system"}
# URI 参照を追加
artifact.add_reference(uri="uri", name="optional-name")
```

アーティファクトは、次の URI スキームをサポートしています。

* `http(s)://`: HTTP 経由でアクセスできるファイルへのパスです。HTTP サーバーが `ETag` および `Content-Length` 応答ヘッダーをサポートしている場合、アーティファクトは ETag 形式のチェックサムとサイズのメタデータをトラッキングします。
* `s3://`: S3 内のオブジェクトまたはオブジェクトの接頭辞へのパスです。アーティファクトは、参照先のオブジェクトのチェックサムとバージョン管理情報 (バケットでオブジェクトのバージョン管理が有効な場合) をトラッキングします。オブジェクトの接頭辞は、その接頭辞配下のオブジェクトを含むように展開されます (最大 10,000 オブジェクト)。
* `gs://`: GCS 内のオブジェクトまたはオブジェクトの接頭辞へのパスです。アーティファクトは、参照先のオブジェクトのチェックサムとバージョン管理情報 (バケットでオブジェクトのバージョン管理が有効な場合) をトラッキングします。オブジェクトの接頭辞は、その接頭辞配下のオブジェクトを含むように展開されます (最大 10,000 オブジェクト)。

次の表は、API 呼び出しごとにアーティファクトの内容がどのように変わるかを示しています。

| API 呼び出し | 生成されるアーティファクトの内容 |
| - | - |
| `artifact.add_reference('s3://my-bucket/model.h5')` | `model.h5` |
| `artifact.add_reference('s3://my-bucket/checkpoints/model.h5')` | `model.h5` |
| `artifact.add_reference('s3://my-bucket/model.h5', name='models/mymodel.h5')` | `models/mymodel.h5` |
| `artifact.add_reference('s3://my-bucket/images')` | <p><code>cat.png</code></p><p><code>dog.png</code></p> |
| `artifact.add_reference('s3://my-bucket/images', name='images')` | <p><code>images/cat.png</code></p><p><code>images/dog.png</code></p> |

<h3 id="add-files-to-artifacts-from-parallel-runs">
  並列 run からアーティファクトにファイルを追加する
</h3>

大規模なデータセットや分散トレーニングでは、複数の run を並列に実行し、それぞれの出力を 1 つのアーティファクトにまとめる必要がある場合があります。

```python theme={"system"}
import wandb
import time

# この例では、デモとして Ray を使用して
# run を並列実行します。
import ray

ray.init()

artifact_type = "dataset"
artifact_name = "parallel-artifact"
table_name = "distributed_table"
parts_path = "parts"
num_parallel = 5

# 並列ライターのバッチごとに、固有の
# グループ名を付けてください。
group_name = "writer-group-{}".format(round(time.time()))


@ray.remote
def train(i):
    """
    Our writer job. Each writer will add one image to the artifact.
    """
    with wandb.init(group=group_name) as run:
        artifact = wandb.Artifact(name=artifact_name, type=artifact_type)

        # wandb の表にデータを追加します。
        table = wandb.Table(columns=["a", "b", "c"], data=[[i, i * 2, 2**i]])

        # アーティファクト内のフォルダーに表を追加します
        artifact.add(table, "{}/table_{}".format(parts_path, i))

        # アーティファクトをアップサートすると、アーティファクトが作成されるか、既存のアーティファクトにデータが追加されます
        run.upsert_artifact(artifact)


# run を並列で起動します
result_ids = [train.remote(i) for i in range(num_parallel)]

# すべてのライターの完了を待ち、アーティファクトを
# 完了する前にファイルが追加済みであることを確認します。
ray.get(result_ids)

# すべてのライターが終了したら、アーティファクトを完了して
# 準備完了の状態にします。
with wandb.init(group=group_name) as run:
    artifact = wandb.Artifact(artifact_name, type=artifact_type)

    # 表のフォルダーを指す「PartitionTable」を作成し、
    # アーティファクトに追加します。
    artifact.add(wandb.data_types.PartitionedTable(parts_path), table_name)

    # finish_artifact はアーティファクトを確定し、このバージョンへの
    # 以降の「アップサート」をできないようにします。
    run.finish_artifact(artifact)
```

<h2 id="find-path-for-logged-artifacts-and-other-metadata">
  ログしたアーティファクトやその他のメタデータのパスを検索する
</h2>

次のコードスニペットは、[W\&B Public API](/ja/products/wandb/ref/python/public-api) を使用して run 内のファイルを一覧表示し、各ファイルの名前と URL を取得する方法を示しています。`<entity/project/run-id>` プレースホルダーをご自身の値に置き換えてください。

```python theme={"system"}
from wandb.apis.public.files import Files
from wandb.apis.public.api import Api

# run オブジェクトの例
run = Api().run("<entity/project/run-id>")

# run 内のファイルを反復処理するために Files オブジェクトを作成します
files = Files(api.client, run)

# ファイルを反復処理します
for file in files:
    print(f"File Name: {file.name}")
    print(f"File URL: {file.url}")
    print(f"Path to file in the bucket: {file.direct_url}")
```

利用可能な属性とメソッドの詳細については、[File](/ja/products/wandb/ref/python/public-api/file) クラスを参照してください。


## Related topics

- [Artifacts の概要](/ja/products/wandb/artifacts.md)
