> ## Documentation Index
> Fetch the complete documentation index at: https://wb-21fd5541-sdk-testing-latest.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">
  ## アーティファクト を作成する
</div>

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

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

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

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

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

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

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

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

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

```python theme={null}
import wandb

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

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

アーティファクト オブジェクトには、[ファイル、ディレクトリ、外部 URI reference (Amazon S3 など) などを追加](/ja/models/artifacts/construct-an-artifact#add-files-to-an-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>")
```

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

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

アーティファクトをW\&B Serverに保存します。アーティファクトを保存するには、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)
```

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

<Warning>
  W\&B では、アップロード性能を高めるために `wandb.Run.log_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)
  ```

  アーティファクト は任意の順序でログされる可能性があるため、アーティファクト のバージョン **v0** のメタデータに含まれる index が 0 でない場合があります。
</Warning>

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

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

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

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

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

```python theme={null}
import wandb

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

# 単一ファイルを追加する
artifact.add_file(local_path="path/file.format")
```

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

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

アーティファクト には現在、以下の内容が含まれています。

```text theme={null}
hello.txt
```

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

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

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

```text theme={null}
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` |

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

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

```python theme={null}
import wandb

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

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

次の表は、異なるAPI callによって生成されるアーティファクトの内容がどのように異なるかを示しています。

| 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> |

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

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

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

```python theme={null}
# URI referenceを追加する
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> |

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

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

```python theme={null}
import wandb
import time

# この例では、デモンストレーション目的で
# Ray を使用して並列実行します。
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 内のフォルダーに表を追加します。
        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)

    # artifact を完了すると artifact が確定され、このバージョンへの
    # 以降の "upsert" が禁止されます。
    run.finish_artifact(artifact)
```

<div id="find-path-for-logged-artifacts-and-other-metadata">
  ## ログ済みの アーティファクト やその他のメタデータのパスを検索する
</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: {file.name}")
    print(f"File URL: {file.url}")
    print(f"Path to file in the bucket: {file.direct_url}")
```

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