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

> W&B Artifact を作成してログします。Artifact に 1 つ以上のファイルまたは URI reference を追加する方法を説明します。

# Artifact を作成する

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

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

<div id="construct-an-artifact">
  ## artifact を作成する
</div>

[W\&B Artifact](/ja/models/ref/python/experiments/artifact) は、次の 3 つの step で作成します。

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

<div id="1-create-an-artifact-python-object-with-wandbartifact">
  ### 1. `wandb.Artifact()` を使って artifact Python オブジェクトを作成する
</div>

artifact オブジェクトを作成するには、[`wandb.Artifact()`](/ja/models/ref/python/experiments/artifact) クラスを初期化します。次のパラメーターを指定します。

* **Name**: artifact の名前です。名前は一意で、内容がわかりやすく、覚えやすいものにしてください。
* **Type**: artifact のタイプです。タイプはシンプルでわかりやすく、機械学習パイプライン内の単一の step に対応している必要があります。一般的な artifact タイプには `'dataset'` や `'model'` があります。

<Note>
  W\&B は、指定した "name" と "type" を使用して、W\&B App に有向非巡回グラフを作成します。詳細は、[artifact グラフの探索とたどり方](./explore-and-traverse-an-artifact-graph)を参照してください。
</Note>

<Warning>
  Artifacts には、タイプに関係なく同じ名前を付けることはできません。つまり、`dataset` タイプの `cats` という名前の artifact と、`model` タイプの同じ名前の artifact を別に作成することはできません。
</Warning>

artifact オブジェクトを初期化する際に、必要に応じて説明やメタデータを指定することもできます。使用可能な属性とパラメーターの詳細については、Python SDK Reference Guide の [`wandb.Artifact`](/ja/models/ref/python/experiments/artifact) クラス定義を参照してください。

次の code snippet をコピー＆ペーストして artifact オブジェクトを作成します。`<name>` と `<type>` のプレースホルダーを自分の値に置き換えてください。

```python theme={null}
import wandb

# artifactオブジェクトを作成する
artifact = wandb.Artifact(name="<name>", type="<type>")
```

<div id="2-add-one-more-files-to-the-artifact">
  ### 2. artifact にさらにファイルを追加する
</div>

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

単一のファイルを追加するには、artifact オブジェクトの [`Artifact.add_file()`](/ja/models/ref/python/experiments/artifact#add_file) method を使用します。

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

ディレクトリを追加するには、[`Artifact.add_dir()`](/ja/models/ref/python/experiments/artifact#add_dir) methodを使用します。

```python theme={null}
artifact.add_dir(local_path="path/to/directory", name="<name>")
```

artifact に種類の異なるファイルを追加する方法について詳しくは、次のセクション「[artifact へのファイルの追加](/ja/models/artifacts/construct-an-artifact#add-files-to-an-artifact)」を参照してください。

<div id="3-save-your-artifact-to-the-wb-server">
  ### 3. artifactをW\&B Serverに保存する
</div>

artifactをW\&B Serverに保存します。artifactを保存するには、run オブジェクトの [`wandb.Run.log_artifact()`](/ja/models/ref/python/experiments/run#log_artifact) method を使用します。

```python theme={null}
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={null}
import wandb

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

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

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

<Warning>
  W\&B では、アップロード性能を高めるために `wandb.Run.log_artifact()` を非同期で実行します。そのため、ループ内で artifact をログすると、想定外の動作が発生することがあります。例:

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

  artifact のバージョン **v0** のメタデータに含まれる index が 0 になるとは限りません。artifact は任意の順序でログされる可能性があるためです。
</Warning>

<div id="add-files-to-an-artifact">
  ## artifact にファイルを追加する
</div>

以下のセクションでは、artifact にさまざまなタイプのオブジェクトを追加する方法を示します。以降の例を読むにあたって、次のような構造のディレクトリがあるものとします。

```
root-directory
| - hello.txt
| - images/
| -- | cat.png
| -- | dog.png
| - checkpoints/
| -- | model.h5
| - models/
| -- | model.h5
```

<div id="add-a-single-file">
  ### 単一ファイルを追加
</div>

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

```python theme={null}
import wandb

# artifactオブジェクトを初期化する
artifact = wandb.Artifact(name="<name>", type="<type>")

# single fileを追加する
artifact.add_file(local_path="path/file.format")
```

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

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

artifact には現在、以下の内容が含まれています。

```
hello.txt
```

必要に応じて、`name` パラメーターに別の名前を渡すと、artifact オブジェクト内でのファイル名を変更できます。前の例の続きは次のとおりです。

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

artifactは次のように保存されます:

```
new/path/hello_world.txt
```

次の表は、異なる API 呼び出しによって artifact に格納される内容がどのように変わるかを示しています。

| API 呼び出し                                                  | 生成される artifact      |
| --------------------------------------------------------- | ------------------- |
| `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` |

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

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

```python theme={null}
import wandb

# artifactオブジェクトを初期化する
artifact = wandb.Artifact(name="<name>", type="<type>")

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

次の表は、異なるAPI callによって生成されるartifactの内容がどのように異なるかを示しています。

| API Call                                    | 生成されるartifact                                                        |
| ------------------------------------------- | -------------------------------------------------------------------- |
| `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> |

<div id="add-a-uri-reference">
  ### URI referenceを追加する
</div>

URI に W\&B ライブラリが処理できるスキームが含まれている場合、Artifacts は再現性のためにチェックサムやその他の情報をトラッキングします。

[`wandb.Artifact.add_reference()`](/ja/models/ref/python/experiments/artifact#method-artifact-add-reference) method を使用して、artifact に外部 URI reference を追加します。`'uri'` 文字列はご自身の URI に置き換えてください。必要に応じて、name パラメーターに artifact 内の任意のパスを指定できます。

```python theme={null}
# URI referenceを追加する
artifact.add_reference(uri="uri", name="optional-name")
```

Artifacts は現在、次の URI スキームをサポートしています。

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

次の表は、API 呼び出しによって artifact の内容がどのように変わるかを示しています。

| API 呼び出し                                                                      | 生成される artifact の内容                                                   |
| ----------------------------------------------------------------------------- | -------------------------------------------------------------------- |
| `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> |

<div id="add-files-to-artifacts-from-parallel-runs">
  ### 並列 run から artifact にファイルを追加する
</div>

大規模なデータセットや分散トレーニングでは、複数の並列 run が 1 つの artifact にそれぞれファイルを追加する必要がある場合があります。

```python theme={null}
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):
    """
    ライタージョブ。各ライターはartifactに1つの画像を追加します。
    """
    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内のフォルダに表を追加します
        artifact.add(table, "{}/table_{}".format(parts_path, i))

        # artifactをアップサートすると、artifactにデータが作成または追加されます
        run.upsert_artifact(artifact)


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

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

# すべてのライターが完了したら、artifactを完了して
# 使用可能な状態としてマークします。
with wandb.init(group=group_name) as run:
    artifact = wandb.Artifact(artifact_name, type=artifact_type)

    # 表のフォルダを指す "PartitionTable" を作成し、
    # artifactに追加します。
    artifact.add(wandb.data_types.PartitionedTable(parts_path), table_name)

    # finish_artifactはartifactを確定し、このバージョンへの
    # 以降の "upsert" を禁止します。
    run.finish_artifact(artifact)
```

<div id="find-path-for-logged-artifacts-and-other-metadata">
  ## ログ済みの artifact やその他のメタデータのパスを検索する
</div>

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

```python theme={null}
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}")
    print(f"ファイルURL: {file.url}")
    print(f"bucket内のファイルパス: {file.direct_url}")
```

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