From 37cbd12672cf5e7ecd37ffe3a2a5b73e6d74660c Mon Sep 17 00:00:00 2001 From: Noah Luna <15202580+ngrayluna@users.noreply.github.com> Date: Wed, 29 Apr 2026 18:44:23 -0700 Subject: [PATCH] preview --- models/ref/python/automations/automation.mdx | 208 ++- models/ref/python/automations/donothing.mdx | 175 +- .../python/automations/metricchangefilter.mdx | 201 +- .../automations/metricthresholdfilter.mdx | 186 +- .../python/automations/metriczscorefilter.mdx | 182 +- .../ref/python/automations/newautomation.mdx | 193 +- .../python/automations/onaddartifactalias.mdx | 183 +- .../python/automations/oncreateartifact.mdx | 183 +- .../ref/python/automations/onlinkartifact.mdx | 183 +- models/ref/python/automations/onrunmetric.mdx | 183 +- models/ref/python/automations/onrunstate.mdx | 183 +- .../ref/python/automations/runstatefilter.mdx | 174 +- .../python/automations/sendnotification.mdx | 195 +- models/ref/python/automations/sendwebhook.mdx | 185 +- models/ref/python/custom-charts/bar.mdx | 59 +- .../python/custom-charts/confusion_matrix.mdx | 91 +- models/ref/python/custom-charts/histogram.mdx | 45 +- models/ref/python/custom-charts/line.mdx | 83 +- .../ref/python/custom-charts/line_series.mdx | 121 +- .../ref/python/custom-charts/plot_table.mdx | 70 +- models/ref/python/custom-charts/pr_curve.mdx | 82 +- models/ref/python/custom-charts/roc_curve.mdx | 71 +- models/ref/python/custom-charts/scatter.mdx | 63 +- models/ref/python/data-types/audio.mdx | 81 +- models/ref/python/data-types/box3d.mdx | 112 +- models/ref/python/data-types/histogram.mdx | 78 +- models/ref/python/data-types/html.mdx | 86 +- models/ref/python/data-types/image.mdx | 136 +- models/ref/python/data-types/molecule.mdx | 91 +- models/ref/python/data-types/object3d.mdx | 97 +- models/ref/python/data-types/plotly.mdx | 77 +- models/ref/python/data-types/table.mdx | 178 +- models/ref/python/data-types/video.mdx | 97 +- models/ref/python/experiments/artifact.mdx | 1179 +++--------- models/ref/python/experiments/run.mdx | 1262 +++---------- models/ref/python/experiments/settings.mdx | 918 +++++---- models/ref/python/functions/controller.mdx | 43 +- models/ref/python/functions/finish.mdx | 48 +- models/ref/python/functions/init.mdx | 168 +- models/ref/python/functions/login.mdx | 90 +- models/ref/python/functions/restore.mdx | 52 +- models/ref/python/functions/setup.mdx | 62 +- models/ref/python/functions/sweep.mdx | 55 +- models/ref/python/functions/teardown.mdx | 40 +- models/ref/python/public-api/api.mdx | 1657 ++--------------- .../python/public-api/artifactcollection.mdx | 174 +- .../python/public-api/artifactcollections.mdx | 41 +- .../ref/python/public-api/artifactfiles.mdx | 37 +- models/ref/python/public-api/artifacts.mdx | 49 +- models/ref/python/public-api/artifacttype.mdx | 78 +- .../ref/python/public-api/artifacttypes.mdx | 32 +- models/ref/python/public-api/automations.mdx | 37 +- models/ref/python/public-api/betareport.mdx | 142 +- .../public-api/downloadhistoryresult.mdx | 39 +- models/ref/python/public-api/file.mdx | 105 +- models/ref/python/public-api/files.mdx | 72 +- .../public-api/incompleterunhistoryerror.mdx | 34 +- models/ref/python/public-api/member.mdx | 38 +- models/ref/python/public-api/project.mdx | 137 +- .../public-api/projectartifactcollections.mdx | 46 +- models/ref/python/public-api/projects.mdx | 65 +- models/ref/python/public-api/registry.mdx | 455 +---- models/ref/python/public-api/reports.mdx | 61 +- models/ref/python/public-api/run.mdx | 768 ++------ models/ref/python/public-api/runartifacts.mdx | 32 +- models/ref/python/public-api/runs.mdx | 102 +- models/ref/python/public-api/sweep.mdx | 185 +- models/ref/python/public-api/sweeps.mdx | 58 +- models/ref/python/public-api/team.mdx | 105 +- models/ref/python/public-api/user.mdx | 101 +- 70 files changed, 5407 insertions(+), 7492 deletions(-) diff --git a/models/ref/python/automations/automation.mdx b/models/ref/python/automations/automation.mdx index 1bbc46cf71..d161274b4e 100644 --- a/models/ref/python/automations/automation.mdx +++ b/models/ref/python/automations/automation.mdx @@ -1,47 +1,189 @@ --- title: Automation -namespace: automations_namespace -python_object_type: class +kind: class +namespace: wandb.automations.automations --- + import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - + + + + +```python +*, +__typename: Literal['Trigger'] = 'Trigger', +id: typing.Annotated[str, Strict(strict=True)], +createdAt: datetime.datetime, +updatedAt: Optional[datetime.datetime] = None, +name: str, +description: Optional[str], +enabled: bool, +scope: Annotated[Union[wandb.automations.scopes._ArtifactSequenceScope, wandb.automations.scopes._ArtifactPortfolioScope, wandb.automations.scopes.ProjectScope], BeforeValidator(func=, json_schema_input_type=PydanticUndefined)], +event: wandb.automations.events.SavedEvent, +action: Annotated[Union[wandb.automations.actions.SavedLaunchJobAction, wandb.automations.actions.SavedNotificationAction, wandb.automations.actions.SavedWebhookAction, wandb.automations.actions.SavedNoOpAction], BeforeValidator(func=, json_schema_input_type=PydanticUndefined)] +``` +## Description -## class `Automation` A local instance of a saved W&B automation that supports editing. -### method `Automation.__init__` -```python -__init__( - typename__: 'Literal['Trigger']' = 'Trigger', - id: 'str', - created_at: 'datetime', - updated_at: 'datetime | None' = None, - name: 'str', - description: 'str | None', - enabled: 'bool', - scope: '_ArtifactSequenceScope | _ArtifactPortfolioScope | ProjectScope', - event: 'SavedEvent', - action: 'SavedLaunchJobAction | SavedNotificationAction | SavedWebhookAction | SavedNoOpAction' -) → None +## Args: + +- **__typename**: +- **id**: +- **createdAt**: +- **updatedAt**: +- **name**: +- **description**: +- **enabled**: +- **scope**: +- **event**: +- **action**: + + + + +## Methods: + +### construct + + + +### copy + +Returns a copy of the model. + +!!! warning "Deprecated" + This method is now deprecated; use `model_copy` instead. + +If you need `include` or `exclude`, use: + +```python {test="skip" lint="skip"} +data = self.model_dump(include=include, exclude=exclude, round_trip=True) +data = {**data, **(update or {})} +copied = self.model_validate(data) ``` -**Args:** - - - `typename__` (Literal['Trigger']): - - `id` (str): - - `created_at` (datetime): The date and time when this automation was created. - - `updated_at` (Optional[datetime]): The date and time when this automation was last updated, if applicable. - - `name` (str): The name of this automation. - - `description` (Optional[str]): An optional description of this automation. - - `enabled` (bool): Whether this automation is enabled. Only enabled automations will trigger. - - `scope` (Union[_ArtifactSequenceScope, _ArtifactPortfolioScope, ProjectScope]): The scope in which the triggering event must occur. - - `event` (SavedEvent): The event that will trigger this automation. - - `action` (Union[SavedLaunchJobAction, SavedNotificationAction, SavedWebhookAction, SavedNoOpAction]): The action that will execute when this automation is triggered. - -**Returns:** - An `Automation` object. +### dict + + + +### from_orm + + + +### json + + + +### model_construct + +Creates a new instance of the `Model` class with validated data. + +Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data. +Default values are respected, but no other validation is performed. + +!!! note + `model_construct()` generally respects the `model_config.extra` setting on the provided model. + That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__` + and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored. + Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in + an error if extra values are passed, but they will be ignored. + +### model_copy + +!!! abstract "Usage Documentation" + [`model_copy`](../concepts/serialization.md#model_copy) + +Returns a copy of the model. + +!!! note + The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This + might have unexpected side effects if you store anything in it, on top of the model + fields (e.g. the value of [cached properties][functools.cached_property]). + +### model_dump + +!!! abstract "Usage Documentation" + [`model_dump`](../concepts/serialization.md#modelmodel_dump) + +Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. + +### model_dump_json + +!!! abstract "Usage Documentation" + [`model_dump_json`](../concepts/serialization.md#modelmodel_dump_json) + +Generates a JSON representation of the model using Pydantic's `to_json` method. + +### model_json_schema + +Generates a JSON schema for a model class. + +### model_parametrized_name + +Compute the class name for parametrizations of generic classes. + +This method can be overridden to achieve a custom naming scheme for generic BaseModels. + +### model_post_init + +Override this method to perform additional initialization after `__init__` and `model_construct`. +This is useful if you want to do some validation that requires the entire model to be initialized. + +### model_rebuild + +Try to rebuild the pydantic-core schema for the model. + +This may be necessary when one of the annotations is a ForwardRef which could not be resolved during +the initial attempt to build the schema, and automatic rebuilding fails. + +### model_validate + +Validate a pydantic model instance. + +### model_validate_json + +!!! abstract "Usage Documentation" + [JSON Parsing](../concepts/json.md#json-parsing) + +Validate the given JSON data against the Pydantic model. + +### model_validate_strings + +Validate the given object with string data against the Pydantic model. + +### parse_file + + + +### parse_obj + + + +### parse_raw + + + +### schema + + + +### schema_json + + + +### update_forward_refs + + + +### validate + + + + + diff --git a/models/ref/python/automations/donothing.mdx b/models/ref/python/automations/donothing.mdx index 79caedf77a..a46fff03d0 100644 --- a/models/ref/python/automations/donothing.mdx +++ b/models/ref/python/automations/donothing.mdx @@ -1,32 +1,173 @@ --- title: DoNothing -namespace: automations_namespace -python_object_type: class +kind: class +namespace: wandb.automations.actions --- + import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - + + + + +```python +*, +no_op: typing.Annotated[bool, BeforeValidator(func=, json_schema_input_type=PydanticUndefined)] = True, +action_type: Literal[NO_OP] = NO_OP +``` +## Description -## class `DoNothing` Defines an automation action that intentionally does nothing. -### method `DoNothing.__init__` -```python -__init__( - no_op: 'bool' = True, - action_type: 'Literal[NO_OP]' = NO_OP -) → None +## Args: + +- **no_op**: +- **action_type**: + + + + +## Methods: + +### construct + + + +### copy + +Returns a copy of the model. + +!!! warning "Deprecated" + This method is now deprecated; use `model_copy` instead. + +If you need `include` or `exclude`, use: + +```python {test="skip" lint="skip"} +data = self.model_dump(include=include, exclude=exclude, round_trip=True) +data = {**data, **(update or {})} +copied = self.model_validate(data) ``` -**Args:** - - - `no_op` (bool): Placeholder field which exists only to satisfy backend schema requirements. - There should never be a need to set this field explicitly, as its value is ignored. - - `action_type` (Literal[NO_OP]): +### dict + + + +### from_orm + + + +### json + + + +### model_construct + +Creates a new instance of the `Model` class with validated data. + +Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data. +Default values are respected, but no other validation is performed. + +!!! note + `model_construct()` generally respects the `model_config.extra` setting on the provided model. + That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__` + and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored. + Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in + an error if extra values are passed, but they will be ignored. + +### model_copy + +!!! abstract "Usage Documentation" + [`model_copy`](../concepts/serialization.md#model_copy) + +Returns a copy of the model. + +!!! note + The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This + might have unexpected side effects if you store anything in it, on top of the model + fields (e.g. the value of [cached properties][functools.cached_property]). + +### model_dump + +!!! abstract "Usage Documentation" + [`model_dump`](../concepts/serialization.md#modelmodel_dump) + +Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. + +### model_dump_json + +!!! abstract "Usage Documentation" + [`model_dump_json`](../concepts/serialization.md#modelmodel_dump_json) + +Generates a JSON representation of the model using Pydantic's `to_json` method. + +### model_json_schema + +Generates a JSON schema for a model class. + +### model_parametrized_name + +Compute the class name for parametrizations of generic classes. + +This method can be overridden to achieve a custom naming scheme for generic BaseModels. + +### model_post_init + +Override this method to perform additional initialization after `__init__` and `model_construct`. +This is useful if you want to do some validation that requires the entire model to be initialized. + +### model_rebuild + +Try to rebuild the pydantic-core schema for the model. + +This may be necessary when one of the annotations is a ForwardRef which could not be resolved during +the initial attempt to build the schema, and automatic rebuilding fails. + +### model_validate + +Validate a pydantic model instance. + +### model_validate_json + +!!! abstract "Usage Documentation" + [JSON Parsing](../concepts/json.md#json-parsing) + +Validate the given JSON data against the Pydantic model. + +### model_validate_strings + +Validate the given object with string data against the Pydantic model. + +### parse_file + + + +### parse_obj + + + +### parse_raw + + + +### schema + + + +### schema_json + + + +### update_forward_refs + + + +### validate + + + + -**Returns:** - An `DoNothing` object. diff --git a/models/ref/python/automations/metricchangefilter.mdx b/models/ref/python/automations/metricchangefilter.mdx index 95dafd73a4..f8c2e416ca 100644 --- a/models/ref/python/automations/metricchangefilter.mdx +++ b/models/ref/python/automations/metricchangefilter.mdx @@ -1,47 +1,188 @@ --- title: MetricChangeFilter -namespace: automations_namespace -python_object_type: class +kind: class +namespace: wandb.automations._filters.run_metrics --- + import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - + + + + +```python +*, +name: str, +agg_op: Optional[wandb.automations._filters.run_metrics.Agg] = None, +current_window_size: typing.Annotated[int, Gt(gt=0)] = 1, +cmp: NoneType = None, +change_amount: Union[Annotated[int, Gt(gt=0)], Annotated[float, Gt(gt=0)]], +prior_window_size: typing.Annotated[int, Gt(gt=0)] = , +change_type: wandb.automations._filters.run_metrics.ChangeType, +change_dir: wandb.automations._filters.run_metrics.ChangeDir +``` +## Description -## class `MetricChangeFilter` Filter that compares a **change** in a metric value to a user-defined threshold. The change is calculated over "tumbling" windows, i.e. the difference between the current window and the non-overlapping prior window. -### method `MetricChangeFilter.__init__` -```python -__init__( - name: 'str', - agg: 'Agg | None' = None, - window: 'int' = 1, - cmp: 'None' = None, - threshold: 'Annotated | Annotated', - prior_window: 'int' = None, - change_type: 'ChangeType', - change_dir: 'ChangeDir' -) → None +## Args: + +- **name**: +- **agg_op**: +- **current_window_size**: +- **cmp**: +- **change_amount**: +- **prior_window_size**: +- **change_type**: +- **change_dir**: + + + + +## Methods: + +### construct + + + +### copy + +Returns a copy of the model. + +!!! warning "Deprecated" + This method is now deprecated; use `model_copy` instead. + +If you need `include` or `exclude`, use: + +```python {test="skip" lint="skip"} +data = self.model_dump(include=include, exclude=exclude, round_trip=True) +data = {**data, **(update or {})} +copied = self.model_validate(data) ``` -**Args:** - - - `name` (str): - - `agg` (Optional[Agg]): - - `window` (int): - - `cmp` (None): Ignored. - - `threshold` (Union[Annotated, Annotated]): - - `prior_window` (int): Size of the "prior" metric aggregation window (ignored if `agg` is ``None``). - If omitted, defaults to the size of the current window. - - `change_type` (ChangeType): - - `change_dir` (ChangeDir): - -**Returns:** - An `MetricChangeFilter` object. +### dict + + + +### from_orm + + + +### json + + + +### model_construct + +Creates a new instance of the `Model` class with validated data. + +Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data. +Default values are respected, but no other validation is performed. + +!!! note + `model_construct()` generally respects the `model_config.extra` setting on the provided model. + That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__` + and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored. + Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in + an error if extra values are passed, but they will be ignored. + +### model_copy + +!!! abstract "Usage Documentation" + [`model_copy`](../concepts/serialization.md#model_copy) + +Returns a copy of the model. + +!!! note + The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This + might have unexpected side effects if you store anything in it, on top of the model + fields (e.g. the value of [cached properties][functools.cached_property]). + +### model_dump + +!!! abstract "Usage Documentation" + [`model_dump`](../concepts/serialization.md#modelmodel_dump) + +Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. + +### model_dump_json + +!!! abstract "Usage Documentation" + [`model_dump_json`](../concepts/serialization.md#modelmodel_dump_json) + +Generates a JSON representation of the model using Pydantic's `to_json` method. + +### model_json_schema + +Generates a JSON schema for a model class. + +### model_parametrized_name + +Compute the class name for parametrizations of generic classes. + +This method can be overridden to achieve a custom naming scheme for generic BaseModels. + +### model_post_init + +Override this method to perform additional initialization after `__init__` and `model_construct`. +This is useful if you want to do some validation that requires the entire model to be initialized. + +### model_rebuild + +Try to rebuild the pydantic-core schema for the model. + +This may be necessary when one of the annotations is a ForwardRef which could not be resolved during +the initial attempt to build the schema, and automatic rebuilding fails. + +### model_validate + +Validate a pydantic model instance. + +### model_validate_json + +!!! abstract "Usage Documentation" + [JSON Parsing](../concepts/json.md#json-parsing) + +Validate the given JSON data against the Pydantic model. + +### model_validate_strings + +Validate the given object with string data against the Pydantic model. + +### parse_file + + + +### parse_obj + + + +### parse_raw + + + +### schema + + + +### schema_json + + + +### update_forward_refs + + + +### validate + + + + + diff --git a/models/ref/python/automations/metricthresholdfilter.mdx b/models/ref/python/automations/metricthresholdfilter.mdx index 9ba3bcdb56..c3c1a770ef 100644 --- a/models/ref/python/automations/metricthresholdfilter.mdx +++ b/models/ref/python/automations/metricthresholdfilter.mdx @@ -1,40 +1,182 @@ --- title: MetricThresholdFilter -namespace: automations_namespace -python_object_type: class +kind: class +namespace: wandb.automations._filters.run_metrics --- + import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - + + + + +```python +*, +name: str, +agg_op: Optional[wandb.automations._filters.run_metrics.Agg] = None, +window_size: typing.Annotated[int, Gt(gt=0)] = 1, +cmp_op: Literal['$gte', '$gt', '$lt', '$lte'], +threshold: Union[Annotated[int, Strict(strict=True)], Annotated[float, Strict(strict=True)]] +``` +## Description -## class `MetricThresholdFilter` Filter that compares an **absolute** metric value against a user-defined threshold. The value may be a single value or an aggregated result over a window of multiple values. -### method `MetricThresholdFilter.__init__` -```python -__init__( - name: 'str', - agg: 'Agg | None' = None, - window: 'int' = 1, - cmp: 'Literal['$gte', '$gt', '$lt', '$lte']', - threshold: 'Annotated | Annotated' -) → None +## Args: + +- **name**: +- **agg_op**: +- **window_size**: +- **cmp_op**: +- **threshold**: + + + + +## Methods: + +### construct + + + +### copy + +Returns a copy of the model. + +!!! warning "Deprecated" + This method is now deprecated; use `model_copy` instead. + +If you need `include` or `exclude`, use: + +```python {test="skip" lint="skip"} +data = self.model_dump(include=include, exclude=exclude, round_trip=True) +data = {**data, **(update or {})} +copied = self.model_validate(data) ``` -**Args:** - - - `name` (str): - - `agg` (Optional[Agg]): - - `window` (int): - - `cmp` (Literal['$gte', '$gt', '$lt', '$lte']): Comparison operator between the metric value (left) vs. the threshold (right). - - `threshold` (Union[Annotated, Annotated]): +### dict + + + +### from_orm + + + +### json + + + +### model_construct + +Creates a new instance of the `Model` class with validated data. + +Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data. +Default values are respected, but no other validation is performed. + +!!! note + `model_construct()` generally respects the `model_config.extra` setting on the provided model. + That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__` + and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored. + Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in + an error if extra values are passed, but they will be ignored. + +### model_copy + +!!! abstract "Usage Documentation" + [`model_copy`](../concepts/serialization.md#model_copy) + +Returns a copy of the model. + +!!! note + The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This + might have unexpected side effects if you store anything in it, on top of the model + fields (e.g. the value of [cached properties][functools.cached_property]). + +### model_dump + +!!! abstract "Usage Documentation" + [`model_dump`](../concepts/serialization.md#modelmodel_dump) + +Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. + +### model_dump_json + +!!! abstract "Usage Documentation" + [`model_dump_json`](../concepts/serialization.md#modelmodel_dump_json) + +Generates a JSON representation of the model using Pydantic's `to_json` method. + +### model_json_schema + +Generates a JSON schema for a model class. + +### model_parametrized_name + +Compute the class name for parametrizations of generic classes. + +This method can be overridden to achieve a custom naming scheme for generic BaseModels. + +### model_post_init + +Override this method to perform additional initialization after `__init__` and `model_construct`. +This is useful if you want to do some validation that requires the entire model to be initialized. + +### model_rebuild + +Try to rebuild the pydantic-core schema for the model. + +This may be necessary when one of the annotations is a ForwardRef which could not be resolved during +the initial attempt to build the schema, and automatic rebuilding fails. + +### model_validate + +Validate a pydantic model instance. + +### model_validate_json + +!!! abstract "Usage Documentation" + [JSON Parsing](../concepts/json.md#json-parsing) + +Validate the given JSON data against the Pydantic model. + +### model_validate_strings + +Validate the given object with string data against the Pydantic model. + +### parse_file + + + +### parse_obj + + + +### parse_raw + + + +### schema + + + +### schema_json + + + +### update_forward_refs + + + +### validate + + + + -**Returns:** - An `MetricThresholdFilter` object. diff --git a/models/ref/python/automations/metriczscorefilter.mdx b/models/ref/python/automations/metriczscorefilter.mdx index 7cfa73de00..3ddaa6abee 100644 --- a/models/ref/python/automations/metriczscorefilter.mdx +++ b/models/ref/python/automations/metriczscorefilter.mdx @@ -1,35 +1,177 @@ --- title: MetricZScoreFilter -namespace: automations_namespace -python_object_type: class +kind: class +namespace: wandb.automations._filters.run_metrics --- + import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - + + + + +```python +*, +name: str, +window_size: typing.Annotated[int, Gt(gt=0)] = 30, +threshold: Union[Annotated[int, Gt(gt=0)], Annotated[float, Gt(gt=0)]] = 3.0, +change_dir: wandb.automations._filters.run_metrics.ChangeDir = ANY +``` +## Description -## class `MetricZScoreFilter` Filter that compares a metric's z-score against a user-defined threshold. -### method `MetricZScoreFilter.__init__` -```python -__init__( - name: 'str', - window: 'int' = 30, - threshold: 'Annotated | Annotated' = 3.0, - change_dir: 'ChangeDir' = ANY -) → None +## Args: + +- **name**: +- **window_size**: +- **threshold**: +- **change_dir**: + + + + +## Methods: + +### construct + + + +### copy + +Returns a copy of the model. + +!!! warning "Deprecated" + This method is now deprecated; use `model_copy` instead. + +If you need `include` or `exclude`, use: + +```python {test="skip" lint="skip"} +data = self.model_dump(include=include, exclude=exclude, round_trip=True) +data = {**data, **(update or {})} +copied = self.model_validate(data) ``` -**Args:** - - - `name` (str): Name of the observed metric. - - `window` (int): Size of the window to calculate the metric mean and standard deviation over. - - `threshold` (Union[Annotated, Annotated]): Threshold for the z-score. - - `change_dir` (ChangeDir): Direction of the z-score change to watch for. +### dict + + + +### from_orm + + + +### json + + + +### model_construct + +Creates a new instance of the `Model` class with validated data. + +Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data. +Default values are respected, but no other validation is performed. + +!!! note + `model_construct()` generally respects the `model_config.extra` setting on the provided model. + That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__` + and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored. + Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in + an error if extra values are passed, but they will be ignored. + +### model_copy + +!!! abstract "Usage Documentation" + [`model_copy`](../concepts/serialization.md#model_copy) + +Returns a copy of the model. + +!!! note + The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This + might have unexpected side effects if you store anything in it, on top of the model + fields (e.g. the value of [cached properties][functools.cached_property]). + +### model_dump + +!!! abstract "Usage Documentation" + [`model_dump`](../concepts/serialization.md#modelmodel_dump) + +Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. + +### model_dump_json + +!!! abstract "Usage Documentation" + [`model_dump_json`](../concepts/serialization.md#modelmodel_dump_json) + +Generates a JSON representation of the model using Pydantic's `to_json` method. + +### model_json_schema + +Generates a JSON schema for a model class. + +### model_parametrized_name + +Compute the class name for parametrizations of generic classes. + +This method can be overridden to achieve a custom naming scheme for generic BaseModels. + +### model_post_init + +Override this method to perform additional initialization after `__init__` and `model_construct`. +This is useful if you want to do some validation that requires the entire model to be initialized. + +### model_rebuild + +Try to rebuild the pydantic-core schema for the model. + +This may be necessary when one of the annotations is a ForwardRef which could not be resolved during +the initial attempt to build the schema, and automatic rebuilding fails. + +### model_validate + +Validate a pydantic model instance. + +### model_validate_json + +!!! abstract "Usage Documentation" + [JSON Parsing](../concepts/json.md#json-parsing) + +Validate the given JSON data against the Pydantic model. + +### model_validate_strings + +Validate the given object with string data against the Pydantic model. + +### parse_file + + + +### parse_obj + + + +### parse_raw + + + +### schema + + + +### schema_json + + + +### update_forward_refs + + + +### validate + + + + -**Returns:** - An `MetricZScoreFilter` object. diff --git a/models/ref/python/automations/newautomation.mdx b/models/ref/python/automations/newautomation.mdx index 89fdbff204..75ceba718f 100644 --- a/models/ref/python/automations/newautomation.mdx +++ b/models/ref/python/automations/newautomation.mdx @@ -1,44 +1,185 @@ --- title: NewAutomation -namespace: automations_namespace -python_object_type: class +kind: class +namespace: wandb.automations.automations --- + import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - + + + + +```python +*, +name: Optional[str] = None, +description: Optional[str] = None, +enabled: Optional[bool] = None, +event: Optional[Annotated[Union[wandb.automations.events.OnLinkArtifact, wandb.automations.events.OnAddArtifactAlias, wandb.automations.events.OnCreateArtifact, wandb.automations.events.OnRunMetric, wandb.automations.events.OnRunState], FieldInfo(annotation=NoneType, required=True, discriminator='event_type')]] = None, +action: Optional[Annotated[Union[wandb.automations.actions.SendNotification, wandb.automations.actions.SendWebhook, wandb.automations.actions.DoNothing], BeforeValidator(func=, json_schema_input_type=PydanticUndefined), FieldInfo(annotation=NoneType, required=True, discriminator='action_type')]] = None +``` +## Description -## class `NewAutomation` A new automation to be created. -### method `NewAutomation.__init__` -```python -__init__( - name: 'str | None' = None, - description: 'str | None' = None, - enabled: 'bool | None' = None, - event: 'Annotated | None' = None, - action: 'Annotated | None' = None -) → None -``` +## Args: + +- **name**: +- **description**: +- **enabled**: +- **event**: +- **action**: -**Args:** - - - `name` (Optional[str]): The name of this automation. - - `description` (Optional[str]): An optional description of this automation. - - `enabled` (Optional[bool]): Whether this automation is enabled. Only enabled automations will trigger. - - `event` (Optional[Annotated]): The event that will trigger this automation. - - `action` (Optional[Annotated]): The action that will execute when this automation is triggered. -**Returns:** - An `NewAutomation` object. +## Properties: -### property `NewAutomation.scope` +### scope The scope in which the triggering event must occur. -**Returns:** - - `Optional[AutomationScope]`: The scope property value. + + +## Methods: + +### construct + + + +### copy + +Returns a copy of the model. + +!!! warning "Deprecated" + This method is now deprecated; use `model_copy` instead. + +If you need `include` or `exclude`, use: + +```python {test="skip" lint="skip"} +data = self.model_dump(include=include, exclude=exclude, round_trip=True) +data = {**data, **(update or {})} +copied = self.model_validate(data) +``` + +### dict + + + +### from_orm + + + +### json + + + +### model_construct + +Creates a new instance of the `Model` class with validated data. + +Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data. +Default values are respected, but no other validation is performed. + +!!! note + `model_construct()` generally respects the `model_config.extra` setting on the provided model. + That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__` + and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored. + Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in + an error if extra values are passed, but they will be ignored. + +### model_copy + +!!! abstract "Usage Documentation" + [`model_copy`](../concepts/serialization.md#model_copy) + +Returns a copy of the model. + +!!! note + The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This + might have unexpected side effects if you store anything in it, on top of the model + fields (e.g. the value of [cached properties][functools.cached_property]). + +### model_dump + +!!! abstract "Usage Documentation" + [`model_dump`](../concepts/serialization.md#modelmodel_dump) + +Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. + +### model_dump_json + +!!! abstract "Usage Documentation" + [`model_dump_json`](../concepts/serialization.md#modelmodel_dump_json) + +Generates a JSON representation of the model using Pydantic's `to_json` method. + +### model_json_schema + +Generates a JSON schema for a model class. + +### model_parametrized_name + +Compute the class name for parametrizations of generic classes. + +This method can be overridden to achieve a custom naming scheme for generic BaseModels. + +### model_post_init + +Override this method to perform additional initialization after `__init__` and `model_construct`. +This is useful if you want to do some validation that requires the entire model to be initialized. + +### model_rebuild + +Try to rebuild the pydantic-core schema for the model. + +This may be necessary when one of the annotations is a ForwardRef which could not be resolved during +the initial attempt to build the schema, and automatic rebuilding fails. + +### model_validate + +Validate a pydantic model instance. + +### model_validate_json + +!!! abstract "Usage Documentation" + [JSON Parsing](../concepts/json.md#json-parsing) + +Validate the given JSON data against the Pydantic model. + +### model_validate_strings + +Validate the given object with string data against the Pydantic model. + +### parse_file + + + +### parse_obj + + + +### parse_raw + + + +### schema + + + +### schema_json + + + +### update_forward_refs + + + +### validate + + + + + diff --git a/models/ref/python/automations/onaddartifactalias.mdx b/models/ref/python/automations/onaddartifactalias.mdx index 9f5eaec7b4..fed395e2db 100644 --- a/models/ref/python/automations/onaddartifactalias.mdx +++ b/models/ref/python/automations/onaddartifactalias.mdx @@ -1,18 +1,29 @@ --- title: OnAddArtifactAlias -namespace: automations_namespace -python_object_type: class +kind: class +namespace: wandb.automations.events --- + import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - + + + + +```python +*, +event_type: Literal[ADD_ARTIFACT_ALIAS] = ADD_ARTIFACT_ALIAS, +scope: Annotated[Union[wandb.automations.scopes._ArtifactSequenceScope, wandb.automations.scopes._ArtifactPortfolioScope, wandb.automations.scopes.ProjectScope], BeforeValidator(func=, json_schema_input_type=PydanticUndefined)], +filter: Annotated[Union[wandb.automations._filters.operators.And, wandb.automations._filters.operators.Or, wandb.automations._filters.operators.Nor, wandb.automations._filters.operators.Not, wandb.automations._filters.operators.Lt, wandb.automations._filters.operators.Gt, wandb.automations._filters.operators.Lte, wandb.automations._filters.operators.Gte, wandb.automations._filters.operators.Eq, wandb.automations._filters.operators.Ne, wandb.automations._filters.operators.In, wandb.automations._filters.operators.NotIn, wandb.automations._filters.operators.Exists, wandb.automations._filters.operators.Regex, wandb.automations._filters.operators.Contains, wandb.automations._filters.expressions.FilterExpr, Dict[str, Any]], Json, BeforeValidator(func=, json_schema_input_type=PydanticUndefined), PlainSerializer(func=, return_type=PydanticUndefined, when_used='always'), AfterValidator(func=)] = And(()) +``` +## Description -## class `OnAddArtifactAlias` A new alias is assigned to an artifact. -Examples: +## Examples: + Define an event that triggers whenever the alias "prod" is assigned to any artifact in the collection "my-collection": @@ -29,22 +40,156 @@ event = OnAddArtifactAlias( ) ``` +## Args: -### method `OnAddArtifactAlias.__init__` +- **event_type**: +- **scope**: +- **filter**: -```python -__init__( - event_type: 'Literal[ADD_ARTIFACT_ALIAS]' = ADD_ARTIFACT_ALIAS, - scope: '_ArtifactSequenceScope | _ArtifactPortfolioScope | ProjectScope', - filter: 'And | Or | Nor | Not | Lt | Gt | Lte | Gte | Eq | Ne | In | NotIn | Exists | Regex | Contains | FilterExpr | dict[str, Any]' = And(()) -) → None + + + +## Methods: + +### construct + + + +### copy + +Returns a copy of the model. + +!!! warning "Deprecated" + This method is now deprecated; use `model_copy` instead. + +If you need `include` or `exclude`, use: + +```python {test="skip" lint="skip"} +data = self.model_dump(include=include, exclude=exclude, round_trip=True) +data = {**data, **(update or {})} +copied = self.model_validate(data) ``` -**Args:** - - - `event_type` (Literal[ADD_ARTIFACT_ALIAS]): - - `scope` (Union[_ArtifactSequenceScope, _ArtifactPortfolioScope, ProjectScope]): The scope of the event. - - `filter` (Union[And, Or, Nor, Not, Lt, Gt, Lte, Gte, Eq, Ne, In, NotIn, Exists, Regex, Contains, FilterExpr, Dict[str, Any]]): Additional conditions(s), if any, that are required for this event to trigger. +### dict + + + +### from_orm + + + +### json + + + +### model_construct + +Creates a new instance of the `Model` class with validated data. + +Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data. +Default values are respected, but no other validation is performed. + +!!! note + `model_construct()` generally respects the `model_config.extra` setting on the provided model. + That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__` + and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored. + Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in + an error if extra values are passed, but they will be ignored. + +### model_copy + +!!! abstract "Usage Documentation" + [`model_copy`](../concepts/serialization.md#model_copy) + +Returns a copy of the model. + +!!! note + The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This + might have unexpected side effects if you store anything in it, on top of the model + fields (e.g. the value of [cached properties][functools.cached_property]). + +### model_dump + +!!! abstract "Usage Documentation" + [`model_dump`](../concepts/serialization.md#modelmodel_dump) + +Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. + +### model_dump_json + +!!! abstract "Usage Documentation" + [`model_dump_json`](../concepts/serialization.md#modelmodel_dump_json) + +Generates a JSON representation of the model using Pydantic's `to_json` method. + +### model_json_schema + +Generates a JSON schema for a model class. + +### model_parametrized_name + +Compute the class name for parametrizations of generic classes. + +This method can be overridden to achieve a custom naming scheme for generic BaseModels. + +### model_post_init + +Override this method to perform additional initialization after `__init__` and `model_construct`. +This is useful if you want to do some validation that requires the entire model to be initialized. + +### model_rebuild + +Try to rebuild the pydantic-core schema for the model. + +This may be necessary when one of the annotations is a ForwardRef which could not be resolved during +the initial attempt to build the schema, and automatic rebuilding fails. + +### model_validate + +Validate a pydantic model instance. + +### model_validate_json + +!!! abstract "Usage Documentation" + [JSON Parsing](../concepts/json.md#json-parsing) + +Validate the given JSON data against the Pydantic model. + +### model_validate_strings + +Validate the given object with string data against the Pydantic model. + +### parse_file + + + +### parse_obj + + + +### parse_raw + + + +### schema + + + +### schema_json + + + +### then + +Define a new Automation in which this event triggers the given action. + +### update_forward_refs + + + +### validate + + + + -**Returns:** - An `OnAddArtifactAlias` object. diff --git a/models/ref/python/automations/oncreateartifact.mdx b/models/ref/python/automations/oncreateartifact.mdx index bf8c53107d..821fa13f7a 100644 --- a/models/ref/python/automations/oncreateartifact.mdx +++ b/models/ref/python/automations/oncreateartifact.mdx @@ -1,18 +1,29 @@ --- title: OnCreateArtifact -namespace: automations_namespace -python_object_type: class +kind: class +namespace: wandb.automations.events --- + import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - + + + + +```python +*, +event_type: Literal[CREATE_ARTIFACT] = CREATE_ARTIFACT, +scope: Annotated[Union[wandb.automations.scopes._ArtifactSequenceScope, wandb.automations.scopes._ArtifactPortfolioScope], BeforeValidator(func=, json_schema_input_type=PydanticUndefined)], +filter: Annotated[Union[wandb.automations._filters.operators.And, wandb.automations._filters.operators.Or, wandb.automations._filters.operators.Nor, wandb.automations._filters.operators.Not, wandb.automations._filters.operators.Lt, wandb.automations._filters.operators.Gt, wandb.automations._filters.operators.Lte, wandb.automations._filters.operators.Gte, wandb.automations._filters.operators.Eq, wandb.automations._filters.operators.Ne, wandb.automations._filters.operators.In, wandb.automations._filters.operators.NotIn, wandb.automations._filters.operators.Exists, wandb.automations._filters.operators.Regex, wandb.automations._filters.operators.Contains, wandb.automations._filters.expressions.FilterExpr, Dict[str, Any]], Json, BeforeValidator(func=, json_schema_input_type=PydanticUndefined), PlainSerializer(func=, return_type=PydanticUndefined, when_used='always'), AfterValidator(func=)] = And(()) +``` +## Description -## class `OnCreateArtifact` A new artifact is created. -Examples: +## Examples: + Define an event that triggers when a new artifact is created in the collection "my-collection": @@ -26,22 +37,156 @@ collection = api.artifact_collection(name="my-collection", type_name="model") event = OnCreateArtifact(scope=collection) ``` +## Args: -### method `OnCreateArtifact.__init__` +- **event_type**: +- **scope**: +- **filter**: -```python -__init__( - event_type: 'Literal[CREATE_ARTIFACT]' = CREATE_ARTIFACT, - scope: '_ArtifactSequenceScope | _ArtifactPortfolioScope', - filter: 'And | Or | Nor | Not | Lt | Gt | Lte | Gte | Eq | Ne | In | NotIn | Exists | Regex | Contains | FilterExpr | dict[str, Any]' = And(()) -) → None + + + +## Methods: + +### construct + + + +### copy + +Returns a copy of the model. + +!!! warning "Deprecated" + This method is now deprecated; use `model_copy` instead. + +If you need `include` or `exclude`, use: + +```python {test="skip" lint="skip"} +data = self.model_dump(include=include, exclude=exclude, round_trip=True) +data = {**data, **(update or {})} +copied = self.model_validate(data) ``` -**Args:** - - - `event_type` (Literal[CREATE_ARTIFACT]): - - `scope` (Union[_ArtifactSequenceScope, _ArtifactPortfolioScope]): The scope of the event: must be an artifact collection. - - `filter` (Union[And, Or, Nor, Not, Lt, Gt, Lte, Gte, Eq, Ne, In, NotIn, Exists, Regex, Contains, FilterExpr, Dict[str, Any]]): Additional conditions(s), if any, that are required for this event to trigger. +### dict + + + +### from_orm + + + +### json + + + +### model_construct + +Creates a new instance of the `Model` class with validated data. + +Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data. +Default values are respected, but no other validation is performed. + +!!! note + `model_construct()` generally respects the `model_config.extra` setting on the provided model. + That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__` + and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored. + Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in + an error if extra values are passed, but they will be ignored. + +### model_copy + +!!! abstract "Usage Documentation" + [`model_copy`](../concepts/serialization.md#model_copy) + +Returns a copy of the model. + +!!! note + The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This + might have unexpected side effects if you store anything in it, on top of the model + fields (e.g. the value of [cached properties][functools.cached_property]). + +### model_dump + +!!! abstract "Usage Documentation" + [`model_dump`](../concepts/serialization.md#modelmodel_dump) + +Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. + +### model_dump_json + +!!! abstract "Usage Documentation" + [`model_dump_json`](../concepts/serialization.md#modelmodel_dump_json) + +Generates a JSON representation of the model using Pydantic's `to_json` method. + +### model_json_schema + +Generates a JSON schema for a model class. + +### model_parametrized_name + +Compute the class name for parametrizations of generic classes. + +This method can be overridden to achieve a custom naming scheme for generic BaseModels. + +### model_post_init + +Override this method to perform additional initialization after `__init__` and `model_construct`. +This is useful if you want to do some validation that requires the entire model to be initialized. + +### model_rebuild + +Try to rebuild the pydantic-core schema for the model. + +This may be necessary when one of the annotations is a ForwardRef which could not be resolved during +the initial attempt to build the schema, and automatic rebuilding fails. + +### model_validate + +Validate a pydantic model instance. + +### model_validate_json + +!!! abstract "Usage Documentation" + [JSON Parsing](../concepts/json.md#json-parsing) + +Validate the given JSON data against the Pydantic model. + +### model_validate_strings + +Validate the given object with string data against the Pydantic model. + +### parse_file + + + +### parse_obj + + + +### parse_raw + + + +### schema + + + +### schema_json + + + +### then + +Define a new Automation in which this event triggers the given action. + +### update_forward_refs + + + +### validate + + + + -**Returns:** - An `OnCreateArtifact` object. diff --git a/models/ref/python/automations/onlinkartifact.mdx b/models/ref/python/automations/onlinkartifact.mdx index 45572aa1ca..dccdfc62a4 100644 --- a/models/ref/python/automations/onlinkartifact.mdx +++ b/models/ref/python/automations/onlinkartifact.mdx @@ -1,18 +1,29 @@ --- title: OnLinkArtifact -namespace: automations_namespace -python_object_type: class +kind: class +namespace: wandb.automations.events --- + import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - + + + + +```python +*, +event_type: Literal[LINK_ARTIFACT] = LINK_ARTIFACT, +scope: Annotated[Union[wandb.automations.scopes._ArtifactSequenceScope, wandb.automations.scopes._ArtifactPortfolioScope, wandb.automations.scopes.ProjectScope], BeforeValidator(func=, json_schema_input_type=PydanticUndefined)], +filter: Annotated[Union[wandb.automations._filters.operators.And, wandb.automations._filters.operators.Or, wandb.automations._filters.operators.Nor, wandb.automations._filters.operators.Not, wandb.automations._filters.operators.Lt, wandb.automations._filters.operators.Gt, wandb.automations._filters.operators.Lte, wandb.automations._filters.operators.Gte, wandb.automations._filters.operators.Eq, wandb.automations._filters.operators.Ne, wandb.automations._filters.operators.In, wandb.automations._filters.operators.NotIn, wandb.automations._filters.operators.Exists, wandb.automations._filters.operators.Regex, wandb.automations._filters.operators.Contains, wandb.automations._filters.expressions.FilterExpr, Dict[str, Any]], Json, BeforeValidator(func=, json_schema_input_type=PydanticUndefined), PlainSerializer(func=, return_type=PydanticUndefined, when_used='always'), AfterValidator(func=)] = And(()) +``` +## Description -## class `OnLinkArtifact` A new artifact is linked to a collection. -Examples: +## Examples: + Define an event that triggers when an artifact is linked to the collection "my-collection" with the alias "prod": @@ -29,22 +40,156 @@ event = OnLinkArtifact( ) ``` +## Args: -### method `OnLinkArtifact.__init__` +- **event_type**: +- **scope**: +- **filter**: -```python -__init__( - event_type: 'Literal[LINK_ARTIFACT]' = LINK_ARTIFACT, - scope: '_ArtifactSequenceScope | _ArtifactPortfolioScope | ProjectScope', - filter: 'And | Or | Nor | Not | Lt | Gt | Lte | Gte | Eq | Ne | In | NotIn | Exists | Regex | Contains | FilterExpr | dict[str, Any]' = And(()) -) → None + + + +## Methods: + +### construct + + + +### copy + +Returns a copy of the model. + +!!! warning "Deprecated" + This method is now deprecated; use `model_copy` instead. + +If you need `include` or `exclude`, use: + +```python {test="skip" lint="skip"} +data = self.model_dump(include=include, exclude=exclude, round_trip=True) +data = {**data, **(update or {})} +copied = self.model_validate(data) ``` -**Args:** - - - `event_type` (Literal[LINK_ARTIFACT]): - - `scope` (Union[_ArtifactSequenceScope, _ArtifactPortfolioScope, ProjectScope]): The scope of the event. - - `filter` (Union[And, Or, Nor, Not, Lt, Gt, Lte, Gte, Eq, Ne, In, NotIn, Exists, Regex, Contains, FilterExpr, Dict[str, Any]]): Additional conditions(s), if any, that are required for this event to trigger. +### dict + + + +### from_orm + + + +### json + + + +### model_construct + +Creates a new instance of the `Model` class with validated data. + +Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data. +Default values are respected, but no other validation is performed. + +!!! note + `model_construct()` generally respects the `model_config.extra` setting on the provided model. + That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__` + and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored. + Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in + an error if extra values are passed, but they will be ignored. + +### model_copy + +!!! abstract "Usage Documentation" + [`model_copy`](../concepts/serialization.md#model_copy) + +Returns a copy of the model. + +!!! note + The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This + might have unexpected side effects if you store anything in it, on top of the model + fields (e.g. the value of [cached properties][functools.cached_property]). + +### model_dump + +!!! abstract "Usage Documentation" + [`model_dump`](../concepts/serialization.md#modelmodel_dump) + +Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. + +### model_dump_json + +!!! abstract "Usage Documentation" + [`model_dump_json`](../concepts/serialization.md#modelmodel_dump_json) + +Generates a JSON representation of the model using Pydantic's `to_json` method. + +### model_json_schema + +Generates a JSON schema for a model class. + +### model_parametrized_name + +Compute the class name for parametrizations of generic classes. + +This method can be overridden to achieve a custom naming scheme for generic BaseModels. + +### model_post_init + +Override this method to perform additional initialization after `__init__` and `model_construct`. +This is useful if you want to do some validation that requires the entire model to be initialized. + +### model_rebuild + +Try to rebuild the pydantic-core schema for the model. + +This may be necessary when one of the annotations is a ForwardRef which could not be resolved during +the initial attempt to build the schema, and automatic rebuilding fails. + +### model_validate + +Validate a pydantic model instance. + +### model_validate_json + +!!! abstract "Usage Documentation" + [JSON Parsing](../concepts/json.md#json-parsing) + +Validate the given JSON data against the Pydantic model. + +### model_validate_strings + +Validate the given object with string data against the Pydantic model. + +### parse_file + + + +### parse_obj + + + +### parse_raw + + + +### schema + + + +### schema_json + + + +### then + +Define a new Automation in which this event triggers the given action. + +### update_forward_refs + + + +### validate + + + + -**Returns:** - An `OnLinkArtifact` object. diff --git a/models/ref/python/automations/onrunmetric.mdx b/models/ref/python/automations/onrunmetric.mdx index 7f1d168745..1c1bc82828 100644 --- a/models/ref/python/automations/onrunmetric.mdx +++ b/models/ref/python/automations/onrunmetric.mdx @@ -1,18 +1,29 @@ --- title: OnRunMetric -namespace: automations_namespace -python_object_type: class +kind: class +namespace: wandb.automations.events --- + import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - + + + + +```python +*, +event_type: Literal[RUN_METRIC_THRESHOLD, RUN_METRIC_CHANGE, RUN_METRIC_ZSCORE], +scope: wandb.automations.scopes.ProjectScope, +filter: typing.Annotated[wandb.automations.events.RunMetricFilter, Json, BeforeValidator(func=, json_schema_input_type=PydanticUndefined), PlainSerializer(func=, return_type=PydanticUndefined, when_used='always')] +``` +## Description -## class `OnRunMetric` A run metric satisfies a user-defined condition. -Examples: +## Examples: + Define an event that triggers for any run in project "my-project" when the average of the last 5 values of metric "my-metric" exceeds 123.45: @@ -29,22 +40,156 @@ event = OnRunMetric( ) ``` +## Args: -### method `OnRunMetric.__init__` +- **event_type**: +- **scope**: +- **filter**: -```python -__init__( - event_type: 'Literal[RUN_METRIC_THRESHOLD, RUN_METRIC_CHANGE, RUN_METRIC_ZSCORE]', - scope: 'ProjectScope', - filter: 'RunMetricFilter' -) → None + + + +## Methods: + +### construct + + + +### copy + +Returns a copy of the model. + +!!! warning "Deprecated" + This method is now deprecated; use `model_copy` instead. + +If you need `include` or `exclude`, use: + +```python {test="skip" lint="skip"} +data = self.model_dump(include=include, exclude=exclude, round_trip=True) +data = {**data, **(update or {})} +copied = self.model_validate(data) ``` -**Args:** - - - `event_type` (Literal[RUN_METRIC_THRESHOLD, RUN_METRIC_CHANGE, RUN_METRIC_ZSCORE]): - - `scope` (ProjectScope): The scope of the event: must be a project. - - `filter` (RunMetricFilter): Run and/or metric condition(s) that must be satisfied for this event to trigger. +### dict + + + +### from_orm + + + +### json + + + +### model_construct + +Creates a new instance of the `Model` class with validated data. + +Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data. +Default values are respected, but no other validation is performed. + +!!! note + `model_construct()` generally respects the `model_config.extra` setting on the provided model. + That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__` + and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored. + Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in + an error if extra values are passed, but they will be ignored. + +### model_copy + +!!! abstract "Usage Documentation" + [`model_copy`](../concepts/serialization.md#model_copy) + +Returns a copy of the model. + +!!! note + The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This + might have unexpected side effects if you store anything in it, on top of the model + fields (e.g. the value of [cached properties][functools.cached_property]). + +### model_dump + +!!! abstract "Usage Documentation" + [`model_dump`](../concepts/serialization.md#modelmodel_dump) + +Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. + +### model_dump_json + +!!! abstract "Usage Documentation" + [`model_dump_json`](../concepts/serialization.md#modelmodel_dump_json) + +Generates a JSON representation of the model using Pydantic's `to_json` method. + +### model_json_schema + +Generates a JSON schema for a model class. + +### model_parametrized_name + +Compute the class name for parametrizations of generic classes. + +This method can be overridden to achieve a custom naming scheme for generic BaseModels. + +### model_post_init + +Override this method to perform additional initialization after `__init__` and `model_construct`. +This is useful if you want to do some validation that requires the entire model to be initialized. + +### model_rebuild + +Try to rebuild the pydantic-core schema for the model. + +This may be necessary when one of the annotations is a ForwardRef which could not be resolved during +the initial attempt to build the schema, and automatic rebuilding fails. + +### model_validate + +Validate a pydantic model instance. + +### model_validate_json + +!!! abstract "Usage Documentation" + [JSON Parsing](../concepts/json.md#json-parsing) + +Validate the given JSON data against the Pydantic model. + +### model_validate_strings + +Validate the given object with string data against the Pydantic model. + +### parse_file + + + +### parse_obj + + + +### parse_raw + + + +### schema + + + +### schema_json + + + +### then + +Define a new Automation in which this event triggers the given action. + +### update_forward_refs + + + +### validate + + + + -**Returns:** - An `OnRunMetric` object. diff --git a/models/ref/python/automations/onrunstate.mdx b/models/ref/python/automations/onrunstate.mdx index e819d73d91..e4ed37aa26 100644 --- a/models/ref/python/automations/onrunstate.mdx +++ b/models/ref/python/automations/onrunstate.mdx @@ -1,18 +1,29 @@ --- title: OnRunState -namespace: automations_namespace -python_object_type: class +kind: class +namespace: wandb.automations.events --- + import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - + + + + +```python +*, +event_type: Literal[RUN_STATE] = RUN_STATE, +scope: wandb.automations.scopes.ProjectScope, +filter: typing.Annotated[wandb.automations.events.RunStateFilter, Json, BeforeValidator(func=, json_schema_input_type=PydanticUndefined), PlainSerializer(func=, return_type=PydanticUndefined, when_used='always')] +``` +## Description -## class `OnRunState` A run state changes. -Examples: +## Examples: + Define an event that triggers for any run in project "my-project" when its state changes to "finished" (i.e. succeeded) or "failed": @@ -29,22 +40,156 @@ event = OnRunState( ) ``` +## Args: -### method `OnRunState.__init__` +- **event_type**: +- **scope**: +- **filter**: -```python -__init__( - event_type: 'Literal[RUN_STATE]' = RUN_STATE, - scope: 'ProjectScope', - filter: 'RunStateFilter' -) → None + + + +## Methods: + +### construct + + + +### copy + +Returns a copy of the model. + +!!! warning "Deprecated" + This method is now deprecated; use `model_copy` instead. + +If you need `include` or `exclude`, use: + +```python {test="skip" lint="skip"} +data = self.model_dump(include=include, exclude=exclude, round_trip=True) +data = {**data, **(update or {})} +copied = self.model_validate(data) ``` -**Args:** - - - `event_type` (Literal[RUN_STATE]): - - `scope` (ProjectScope): The scope of the event: must be a project. - - `filter` (RunStateFilter): Run state condition(s) that must be satisfied for this event to trigger. +### dict + + + +### from_orm + + + +### json + + + +### model_construct + +Creates a new instance of the `Model` class with validated data. + +Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data. +Default values are respected, but no other validation is performed. + +!!! note + `model_construct()` generally respects the `model_config.extra` setting on the provided model. + That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__` + and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored. + Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in + an error if extra values are passed, but they will be ignored. + +### model_copy + +!!! abstract "Usage Documentation" + [`model_copy`](../concepts/serialization.md#model_copy) + +Returns a copy of the model. + +!!! note + The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This + might have unexpected side effects if you store anything in it, on top of the model + fields (e.g. the value of [cached properties][functools.cached_property]). + +### model_dump + +!!! abstract "Usage Documentation" + [`model_dump`](../concepts/serialization.md#modelmodel_dump) + +Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. + +### model_dump_json + +!!! abstract "Usage Documentation" + [`model_dump_json`](../concepts/serialization.md#modelmodel_dump_json) + +Generates a JSON representation of the model using Pydantic's `to_json` method. + +### model_json_schema + +Generates a JSON schema for a model class. + +### model_parametrized_name + +Compute the class name for parametrizations of generic classes. + +This method can be overridden to achieve a custom naming scheme for generic BaseModels. + +### model_post_init + +Override this method to perform additional initialization after `__init__` and `model_construct`. +This is useful if you want to do some validation that requires the entire model to be initialized. + +### model_rebuild + +Try to rebuild the pydantic-core schema for the model. + +This may be necessary when one of the annotations is a ForwardRef which could not be resolved during +the initial attempt to build the schema, and automatic rebuilding fails. + +### model_validate + +Validate a pydantic model instance. + +### model_validate_json + +!!! abstract "Usage Documentation" + [JSON Parsing](../concepts/json.md#json-parsing) + +Validate the given JSON data against the Pydantic model. + +### model_validate_strings + +Validate the given object with string data against the Pydantic model. + +### parse_file + + + +### parse_obj + + + +### parse_raw + + + +### schema + + + +### schema_json + + + +### then + +Define a new Automation in which this event triggers the given action. + +### update_forward_refs + + + +### validate + + + + -**Returns:** - An `OnRunState` object. diff --git a/models/ref/python/automations/runstatefilter.mdx b/models/ref/python/automations/runstatefilter.mdx index 686bd9b505..842f5280c8 100644 --- a/models/ref/python/automations/runstatefilter.mdx +++ b/models/ref/python/automations/runstatefilter.mdx @@ -1,31 +1,173 @@ --- title: RunStateFilter -namespace: automations_namespace -python_object_type: class +kind: class +namespace: wandb.automations.events --- + import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - + + + + +```python +*, +run_filter: Annotated[Union[wandb.automations._filters.operators.And, wandb.automations._filters.operators.Or, wandb.automations._filters.operators.Nor, wandb.automations._filters.operators.Not, wandb.automations._filters.operators.Lt, wandb.automations._filters.operators.Gt, wandb.automations._filters.operators.Lte, wandb.automations._filters.operators.Gte, wandb.automations._filters.operators.Eq, wandb.automations._filters.operators.Ne, wandb.automations._filters.operators.In, wandb.automations._filters.operators.NotIn, wandb.automations._filters.operators.Exists, wandb.automations._filters.operators.Regex, wandb.automations._filters.operators.Contains, wandb.automations._filters.expressions.FilterExpr, Dict[str, Any]], Json, BeforeValidator(func=, json_schema_input_type=PydanticUndefined), PlainSerializer(func=, return_type=PydanticUndefined, when_used='always'), AfterValidator(func=)] = And(()), +run_state_filter: wandb.automations._filters.run_states.StateFilter +``` +## Description -## class `RunStateFilter` Represents a filter for triggering events based on changes in run states. -### method `RunStateFilter.__init__` -```python -__init__( - run: 'And | Or | Nor | Not | Lt | Gt | Lte | Gte | Eq | Ne | In | NotIn | Exists | Regex | Contains | FilterExpr | dict[str, Any]' = And(()), - state: 'StateFilter' -) → None +## Args: + +- **run_filter**: +- **run_state_filter**: + + + + +## Methods: + +### construct + + + +### copy + +Returns a copy of the model. + +!!! warning "Deprecated" + This method is now deprecated; use `model_copy` instead. + +If you need `include` or `exclude`, use: + +```python {test="skip" lint="skip"} +data = self.model_dump(include=include, exclude=exclude, round_trip=True) +data = {**data, **(update or {})} +copied = self.model_validate(data) ``` -**Args:** - - - `run` (Union[And, Or, Nor, Not, Lt, Gt, Lte, Gte, Eq, Ne, In, NotIn, Exists, Regex, Contains, FilterExpr, Dict[str, Any]]): Filters that must match any runs that will trigger this event. - - `state` (StateFilter): Run state condition(s) that must be satisfied for this event to trigger. +### dict + + + +### from_orm + + + +### json + + + +### model_construct + +Creates a new instance of the `Model` class with validated data. + +Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data. +Default values are respected, but no other validation is performed. + +!!! note + `model_construct()` generally respects the `model_config.extra` setting on the provided model. + That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__` + and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored. + Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in + an error if extra values are passed, but they will be ignored. + +### model_copy + +!!! abstract "Usage Documentation" + [`model_copy`](../concepts/serialization.md#model_copy) + +Returns a copy of the model. + +!!! note + The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This + might have unexpected side effects if you store anything in it, on top of the model + fields (e.g. the value of [cached properties][functools.cached_property]). + +### model_dump + +!!! abstract "Usage Documentation" + [`model_dump`](../concepts/serialization.md#modelmodel_dump) + +Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. + +### model_dump_json + +!!! abstract "Usage Documentation" + [`model_dump_json`](../concepts/serialization.md#modelmodel_dump_json) + +Generates a JSON representation of the model using Pydantic's `to_json` method. + +### model_json_schema + +Generates a JSON schema for a model class. + +### model_parametrized_name + +Compute the class name for parametrizations of generic classes. + +This method can be overridden to achieve a custom naming scheme for generic BaseModels. + +### model_post_init + +Override this method to perform additional initialization after `__init__` and `model_construct`. +This is useful if you want to do some validation that requires the entire model to be initialized. + +### model_rebuild + +Try to rebuild the pydantic-core schema for the model. + +This may be necessary when one of the annotations is a ForwardRef which could not be resolved during +the initial attempt to build the schema, and automatic rebuilding fails. + +### model_validate + +Validate a pydantic model instance. + +### model_validate_json + +!!! abstract "Usage Documentation" + [JSON Parsing](../concepts/json.md#json-parsing) + +Validate the given JSON data against the Pydantic model. + +### model_validate_strings + +Validate the given object with string data against the Pydantic model. + +### parse_file + + + +### parse_obj + + + +### parse_raw + + + +### schema + + + +### schema_json + + + +### update_forward_refs + + + +### validate + + + + -**Returns:** - An `RunStateFilter` object. diff --git a/models/ref/python/automations/sendnotification.mdx b/models/ref/python/automations/sendnotification.mdx index 5613f57f5d..8811cce66e 100644 --- a/models/ref/python/automations/sendnotification.mdx +++ b/models/ref/python/automations/sendnotification.mdx @@ -1,50 +1,183 @@ --- title: SendNotification -namespace: automations_namespace -python_object_type: class +kind: class +namespace: wandb.automations.actions --- + import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - + + + + +```python +*, +integration_id: typing.Annotated[str, Strict(strict=True)], +text: str = '', +level: typing.Annotated[wandb.automations._generated.enums.AlertSeverity, BeforeValidator(func=, json_schema_input_type=PydanticUndefined)] = , +title: str = '', +action_type: Literal[NOTIFICATION] = NOTIFICATION +``` +## Description -## class `SendNotification` Defines an automation action that sends a (Slack) notification. -### method `SendNotification.__init__` -```python -__init__( - integration_id: 'str', - message: 'str' = '', - severity: 'AlertSeverity' = , - title: 'str' = '', - action_type: 'Literal[NOTIFICATION]' = NOTIFICATION -) → None -``` +## Args: -**Args:** - - - `integration_id` (str): The ID of the Slack integration that will be used to send the notification. - - `message` (str): The message body of the sent notification. - - `severity` (AlertSeverity): The severity (`INFO`, `WARN`, `ERROR`) of the sent notification. - - `title` (str): The title of the sent notification. - - `action_type` (Literal[NOTIFICATION]): +- **integration_id**: +- **text**: +- **level**: +- **title**: +- **action_type**: -**Returns:** - An `SendNotification` object. -### classmethod `SendNotification.from_integration` -```python -from_integration( - integration: 'SlackIntegration', - title: 'str' = '', - text: 'str' = '', - level: 'AlertSeverity' = -) → Self + +## Methods: + +### construct + + + +### copy + +Returns a copy of the model. + +!!! warning "Deprecated" + This method is now deprecated; use `model_copy` instead. + +If you need `include` or `exclude`, use: + +```python {test="skip" lint="skip"} +data = self.model_dump(include=include, exclude=exclude, round_trip=True) +data = {**data, **(update or {})} +copied = self.model_validate(data) ``` +### dict + + + +### from_integration + Define a notification action that sends to the given (Slack) integration. + +### from_orm + + + +### json + + + +### model_construct + +Creates a new instance of the `Model` class with validated data. + +Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data. +Default values are respected, but no other validation is performed. + +!!! note + `model_construct()` generally respects the `model_config.extra` setting on the provided model. + That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__` + and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored. + Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in + an error if extra values are passed, but they will be ignored. + +### model_copy + +!!! abstract "Usage Documentation" + [`model_copy`](../concepts/serialization.md#model_copy) + +Returns a copy of the model. + +!!! note + The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This + might have unexpected side effects if you store anything in it, on top of the model + fields (e.g. the value of [cached properties][functools.cached_property]). + +### model_dump + +!!! abstract "Usage Documentation" + [`model_dump`](../concepts/serialization.md#modelmodel_dump) + +Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. + +### model_dump_json + +!!! abstract "Usage Documentation" + [`model_dump_json`](../concepts/serialization.md#modelmodel_dump_json) + +Generates a JSON representation of the model using Pydantic's `to_json` method. + +### model_json_schema + +Generates a JSON schema for a model class. + +### model_parametrized_name + +Compute the class name for parametrizations of generic classes. + +This method can be overridden to achieve a custom naming scheme for generic BaseModels. + +### model_post_init + +Override this method to perform additional initialization after `__init__` and `model_construct`. +This is useful if you want to do some validation that requires the entire model to be initialized. + +### model_rebuild + +Try to rebuild the pydantic-core schema for the model. + +This may be necessary when one of the annotations is a ForwardRef which could not be resolved during +the initial attempt to build the schema, and automatic rebuilding fails. + +### model_validate + +Validate a pydantic model instance. + +### model_validate_json + +!!! abstract "Usage Documentation" + [JSON Parsing](../concepts/json.md#json-parsing) + +Validate the given JSON data against the Pydantic model. + +### model_validate_strings + +Validate the given object with string data against the Pydantic model. + +### parse_file + + + +### parse_obj + + + +### parse_raw + + + +### schema + + + +### schema_json + + + +### update_forward_refs + + + +### validate + + + + + diff --git a/models/ref/python/automations/sendwebhook.mdx b/models/ref/python/automations/sendwebhook.mdx index 5adf2472e6..4a5c7242ea 100644 --- a/models/ref/python/automations/sendwebhook.mdx +++ b/models/ref/python/automations/sendwebhook.mdx @@ -1,44 +1,179 @@ --- title: SendWebhook -namespace: automations_namespace -python_object_type: class +kind: class +namespace: wandb.automations.actions --- + import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - + + + + +```python +*, +integration_id: typing.Annotated[str, Strict(strict=True)], +requestPayload: Optional[Annotated[dict[str, Any], Json, BeforeValidator(func=, json_schema_input_type=PydanticUndefined), PlainSerializer(func=, return_type=PydanticUndefined, when_used='always')]] = None, +action_type: Literal[GENERIC_WEBHOOK] = GENERIC_WEBHOOK +``` +## Description -## class `SendWebhook` Defines an automation action that sends a webhook request. -### method `SendWebhook.__init__` -```python -__init__( - integration_id: 'str', - request_payload: 'Annotated | None' = None, - action_type: 'Literal[GENERIC_WEBHOOK]' = GENERIC_WEBHOOK -) → None -``` +## Args: -**Args:** - - - `integration_id` (str): The ID of the webhook integration that will be used to send the request. - - `request_payload` (Optional[Annotated]): The payload, possibly with template variables, to send in the webhook request. - - `action_type` (Literal[GENERIC_WEBHOOK]): +- **integration_id**: +- **requestPayload**: +- **action_type**: -**Returns:** - An `SendWebhook` object. -### classmethod `SendWebhook.from_integration` -```python -from_integration( - integration: 'WebhookIntegration', - payload: 'Optional[JsonEncoded[dict[str, Any]]]' = None -) → Self + +## Methods: + +### construct + + + +### copy + +Returns a copy of the model. + +!!! warning "Deprecated" + This method is now deprecated; use `model_copy` instead. + +If you need `include` or `exclude`, use: + +```python {test="skip" lint="skip"} +data = self.model_dump(include=include, exclude=exclude, round_trip=True) +data = {**data, **(update or {})} +copied = self.model_validate(data) ``` +### dict + + + +### from_integration + Define a webhook action that sends to the given (webhook) integration. + +### from_orm + + + +### json + + + +### model_construct + +Creates a new instance of the `Model` class with validated data. + +Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data. +Default values are respected, but no other validation is performed. + +!!! note + `model_construct()` generally respects the `model_config.extra` setting on the provided model. + That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__` + and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored. + Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in + an error if extra values are passed, but they will be ignored. + +### model_copy + +!!! abstract "Usage Documentation" + [`model_copy`](../concepts/serialization.md#model_copy) + +Returns a copy of the model. + +!!! note + The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This + might have unexpected side effects if you store anything in it, on top of the model + fields (e.g. the value of [cached properties][functools.cached_property]). + +### model_dump + +!!! abstract "Usage Documentation" + [`model_dump`](../concepts/serialization.md#modelmodel_dump) + +Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. + +### model_dump_json + +!!! abstract "Usage Documentation" + [`model_dump_json`](../concepts/serialization.md#modelmodel_dump_json) + +Generates a JSON representation of the model using Pydantic's `to_json` method. + +### model_json_schema + +Generates a JSON schema for a model class. + +### model_parametrized_name + +Compute the class name for parametrizations of generic classes. + +This method can be overridden to achieve a custom naming scheme for generic BaseModels. + +### model_post_init + +Override this method to perform additional initialization after `__init__` and `model_construct`. +This is useful if you want to do some validation that requires the entire model to be initialized. + +### model_rebuild + +Try to rebuild the pydantic-core schema for the model. + +This may be necessary when one of the annotations is a ForwardRef which could not be resolved during +the initial attempt to build the schema, and automatic rebuilding fails. + +### model_validate + +Validate a pydantic model instance. + +### model_validate_json + +!!! abstract "Usage Documentation" + [JSON Parsing](../concepts/json.md#json-parsing) + +Validate the given JSON data against the Pydantic model. + +### model_validate_strings + +Validate the given object with string data against the Pydantic model. + +### parse_file + + + +### parse_obj + + + +### parse_raw + + + +### schema + + + +### schema_json + + + +### update_forward_refs + + + +### validate + + + + + diff --git a/models/ref/python/custom-charts/bar.mdx b/models/ref/python/custom-charts/bar.mdx index 43ce28b9ad..7820142ddc 100644 --- a/models/ref/python/custom-charts/bar.mdx +++ b/models/ref/python/custom-charts/bar.mdx @@ -1,49 +1,45 @@ --- -title: bar() -namespace: python_sdk_custom_charts -python_object_type: function +title: bar +kind: function +namespace: wandb.plot.bar --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; + -### function `bar` ```python -bar( - table: 'wandb.Table', - label: 'str', - value: 'str', - title: 'str' = '', - split_table: 'bool' = False -) → CustomChart +table: 'wandb.Table', +label: 'str', +value: 'str', +title: 'str' = '', +split_table: 'bool' = False ``` -Constructs a bar chart from a wandb.Table of data. +## Description + +Constructs a bar chart from a wandb.Table of data. +## Args: +- **table**: A table containing the data for the bar chart. +- **label**: The name of the column to use for the labels of each bar. +- **value**: The name of the column to use for the values of each bar. +- **title**: The title of the bar chart. +- **split_table**: Whether the table should be split into a separate section in the W&B UI. If `True`, the table will be displayed in a section named "Custom Chart Tables". Default is `False`. -**Args:** - - - `table`: A table containing the data for the bar chart. - - `label`: The name of the column to use for the labels of each bar. - - `value`: The name of the column to use for the values of each bar. - - `title`: The title of the bar chart. - - `split_table`: Whether the table should be split into a separate section in the W&B UI. If `True`, the table will be displayed in a section named "Custom Chart Tables". Default is `False`. +## Returns: +- **CustomChart**: A custom chart object that can be logged to W&B. To log the chart, pass it to `wandb.log()`. -**Returns:** - - - `CustomChart`: A custom chart object that can be logged to W&B. To log the chart, pass it to `wandb.log()`. -**Example:** - +## Examples: ```python import random @@ -64,12 +60,13 @@ table = wandb.Table(data=data, columns=["class", "accuracy"]) with wandb.init(project="bar_chart") as run: # Create a bar plot from the table bar_plot = wandb.plot.bar( - table=table, - label="class", - value="accuracy", - title="Object Classification Accuracy", + table=table, + label="class", + value="accuracy", + title="Object Classification Accuracy", ) # Log the bar chart to W&B run.log({"bar_plot": bar_plot}) -``` +``` + diff --git a/models/ref/python/custom-charts/confusion_matrix.mdx b/models/ref/python/custom-charts/confusion_matrix.mdx index bfa5103c30..604c4d7b42 100644 --- a/models/ref/python/custom-charts/confusion_matrix.mdx +++ b/models/ref/python/custom-charts/confusion_matrix.mdx @@ -1,58 +1,53 @@ --- -title: confusion_matrix() -namespace: python_sdk_custom_charts -python_object_type: function +title: confusion_matrix +kind: function +namespace: wandb.plot.confusion_matrix --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; + -### function `confusion_matrix` ```python -confusion_matrix( - probs: 'Sequence[Sequence[float]] | None' = None, - y_true: 'Sequence[T] | None' = None, - preds: 'Sequence[T] | None' = None, - class_names: 'Sequence[str] | None' = None, - title: 'str' = 'Confusion Matrix Curve', - split_table: 'bool' = False -) → CustomChart +probs: 'Sequence[Sequence[float]] | None' = None, +y_true: 'Sequence[T] | None' = None, +preds: 'Sequence[T] | None' = None, +class_names: 'Sequence[str] | None' = None, +title: 'str' = 'Confusion Matrix Curve', +split_table: 'bool' = False ``` -Constructs a confusion matrix from a sequence of probabilities or predictions. - +## Description +Constructs a confusion matrix from a sequence of probabilities or predictions. -**Args:** - - - `probs`: A sequence of predicted probabilities for each class. The sequence shape should be (N, K) where N is the number of samples and K is the number of classes. If provided, `preds` should not be provided. - - `y_true`: A sequence of true labels. - - `preds`: A sequence of predicted class labels. If provided, `probs` should not be provided. - - `class_names`: Sequence of class names. If not provided, class names will be defined as "Class_1", "Class_2", etc. - - `title`: Title of the confusion matrix chart. - - `split_table`: Whether the table should be split into a separate section in the W&B UI. If `True`, the table will be displayed in a section named "Custom Chart Tables". Default is `False`. +## Args: +- **probs**: A sequence of predicted probabilities for each class. The sequence shape should be (N, K) where N is the number of samples and K is the number of classes. If provided, `preds` should not be provided. +- **y_true**: A sequence of true labels. +- **preds**: A sequence of predicted class labels. If provided, `probs` should not be provided. +- **class_names**: Sequence of class names. If not provided, class names will be defined as "Class_1", "Class_2", etc. +- **title**: Title of the confusion matrix chart. +- **split_table**: Whether the table should be split into a separate section in the W&B UI. If `True`, the table will be displayed in a section named "Custom Chart Tables". Default is `False`. -**Returns:** - - - `CustomChart`: A custom chart object that can be logged to W&B. To log the chart, pass it to `wandb.log()`. +## Returns: +- **CustomChart**: A custom chart object that can be logged to W&B. To log the chart, pass it to `wandb.log()`. +- **Raises**: +- **ValueError**: If both `probs` and `preds` are provided or if the number of predictions and true labels are not equal. If the number of unique predicted classes exceeds the number of class names or if the number of unique true labels exceeds the number of class names. +- **wandb.Error**: If numpy is not installed. -**Raises:** - - - `ValueError`: If both `probs` and `preds` are provided or if the number of predictions and true labels are not equal. If the number of unique predicted classes exceeds the number of class names or if the number of unique true labels exceeds the number of class names. - - `wandb.Error`: If numpy is not installed. +## Examples: -**Examples:** - Logging a confusion matrix with random probabilities for wildlife classification: +Logging a confusion matrix with random probabilities for wildlife +classification: ```python import numpy as np @@ -75,17 +70,19 @@ wildlife_probs = np.exp(wildlife_probs) / np.sum( # Initialize W&B run and log confusion matrix with wandb.init(project="wildlife_classification") as run: confusion_matrix = wandb.plot.confusion_matrix( - probs=wildlife_probs, - y_true=wildlife_y_true, - class_names=wildlife_class_names, - title="Wildlife Classification Confusion Matrix", + probs=wildlife_probs, + y_true=wildlife_y_true, + class_names=wildlife_class_names, + title="Wildlife Classification Confusion Matrix", ) run.log({"wildlife_confusion_matrix": confusion_matrix}) -``` +``` -In this example, random probabilities are used to generate a confusion matrix. +In this example, random probabilities are used to generate a confusion +matrix. -Logging a confusion matrix with simulated model predictions and 85% accuracy: +Logging a confusion matrix with simulated model predictions and 85% +accuracy: ```python import numpy as np @@ -112,12 +109,14 @@ wildlife_preds = [ # Initialize W&B run and log confusion matrix with wandb.init(project="wildlife_classification") as run: confusion_matrix = wandb.plot.confusion_matrix( - preds=wildlife_preds, - y_true=wildlife_y_true, - class_names=wildlife_class_names, - title="Simulated Wildlife Classification Confusion Matrix", + preds=wildlife_preds, + y_true=wildlife_y_true, + class_names=wildlife_class_names, + title="Simulated Wildlife Classification Confusion Matrix", ) run.log({"wildlife_confusion_matrix": confusion_matrix}) -``` +``` + +In this example, predictions are simulated with 85% accuracy to generate a +confusion matrix. -In this example, predictions are simulated with 85% accuracy to generate a confusion matrix. diff --git a/models/ref/python/custom-charts/histogram.mdx b/models/ref/python/custom-charts/histogram.mdx index fca5a580f1..6b1200c09b 100644 --- a/models/ref/python/custom-charts/histogram.mdx +++ b/models/ref/python/custom-charts/histogram.mdx @@ -1,47 +1,43 @@ --- title: histogram -namespace: python_sdk_custom_charts -python_object_type: function +kind: function +namespace: wandb.plot.histogram --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; + -### function `histogram` ```python -histogram( - table: 'wandb.Table', - value: 'str', - title: 'str' = '', - split_table: 'bool' = False -) → CustomChart +table: 'wandb.Table', +value: 'str', +title: 'str' = '', +split_table: 'bool' = False ``` -Constructs a histogram chart from a W&B Table. +## Description + +Constructs a histogram chart from a W&B Table. +## Args: +- **table**: The W&B Table containing the data for the histogram. +- **value**: The label for the bin axis (x-axis). +- **title**: The title of the histogram plot. +- **split_table**: Whether the table should be split into a separate section in the W&B UI. If `True`, the table will be displayed in a section named "Custom Chart Tables". Default is `False`. -**Args:** - - - `table`: The W&B Table containing the data for the histogram. - - `value`: The label for the bin axis (x-axis). - - `title`: The title of the histogram plot. - - `split_table`: Whether the table should be split into a separate section in the W&B UI. If `True`, the table will be displayed in a section named "Custom Chart Tables". Default is `False`. +## Returns: +- **CustomChart**: A custom chart object that can be logged to W&B. To log the chart, pass it to `wandb.log()`. -**Returns:** - - - `CustomChart`: A custom chart object that can be logged to W&B. To log the chart, pass it to `wandb.log()`. -**Example:** - +## Examples: ```python import math @@ -67,4 +63,5 @@ histogram = wandb.plot.histogram( # Log the histogram plot to W&B with wandb.init(...) as run: run.log({"histogram-plot1": histogram}) -``` +``` + diff --git a/models/ref/python/custom-charts/line.mdx b/models/ref/python/custom-charts/line.mdx index 1338fa49e3..67481e3abe 100644 --- a/models/ref/python/custom-charts/line.mdx +++ b/models/ref/python/custom-charts/line.mdx @@ -1,51 +1,47 @@ --- -title: line() -namespace: python_sdk_custom_charts -python_object_type: function +title: line +kind: function +namespace: wandb.plot.line --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; + -### function `line` ```python -line( - table: 'wandb.Table', - x: 'str', - y: 'str', - stroke: 'str | None' = None, - title: 'str' = '', - split_table: 'bool' = False -) → CustomChart +table: 'wandb.Table', +x: 'str', +y: 'str', +stroke: 'str | None' = None, +title: 'str' = '', +split_table: 'bool' = False ``` -Constructs a customizable line chart. +## Description + +Constructs a customizable line chart. +## Args: +- **table**: The table containing data for the chart. +- **x**: Column name for the x-axis values. +- **y**: Column name for the y-axis values. +- **stroke**: Column name to differentiate line strokes (e.g., for grouping lines). +- **title**: Title of the chart. +- **split_table**: Whether the table should be split into a separate section in the W&B UI. If `True`, the table will be displayed in a section named "Custom Chart Tables". Default is `False`. -**Args:** - - - `table`: The table containing data for the chart. - - `x`: Column name for the x-axis values. - - `y`: Column name for the y-axis values. - - `stroke`: Column name to differentiate line strokes (e.g., for grouping lines). - - `title`: Title of the chart. - - `split_table`: Whether the table should be split into a separate section in the W&B UI. If `True`, the table will be displayed in a section named "Custom Chart Tables". Default is `False`. +## Returns: +- **CustomChart**: A custom chart object that can be logged to W&B. To log the chart, pass it to `wandb.log()`. -**Returns:** - - - `CustomChart`: A custom chart object that can be logged to W&B. To log the chart, pass it to `wandb.log()`. -**Example:** - +## Examples: ```python import math @@ -55,24 +51,25 @@ import wandb # Create multiple series of data with different patterns data = [] for i in range(100): - # Series 1: Sinusoidal pattern with random noise - data.append([i, math.sin(i / 10) + random.uniform(-0.1, 0.1), "series_1"]) - # Series 2: Cosine pattern with random noise - data.append([i, math.cos(i / 10) + random.uniform(-0.1, 0.1), "series_2"]) - # Series 3: Linear increase with random noise - data.append([i, i / 10 + random.uniform(-0.5, 0.5), "series_3"]) + # Series 1: Sinusoidal pattern with random noise + data.append([i, math.sin(i / 10) + random.uniform(-0.1, 0.1), "series_1"]) + # Series 2: Cosine pattern with random noise + data.append([i, math.cos(i / 10) + random.uniform(-0.1, 0.1), "series_2"]) + # Series 3: Linear increase with random noise + data.append([i, i / 10 + random.uniform(-0.5, 0.5), "series_3"]) # Define the columns for the table table = wandb.Table(data=data, columns=["step", "value", "series"]) # Initialize wandb run and log the line chart with wandb.init(project="line_chart_example") as run: - line_chart = wandb.plot.line( - table=table, - x="step", - y="value", - stroke="series", # Group by the "series" column - title="Multi-Series Line Plot", - ) - run.log({"line-chart": line_chart}) -``` + line_chart = wandb.plot.line( + table=table, + x="step", + y="value", + stroke="series", # Group by the "series" column + title="Multi-Series Line Plot", + ) + run.log({"line-chart": line_chart}) +``` + diff --git a/models/ref/python/custom-charts/line_series.mdx b/models/ref/python/custom-charts/line_series.mdx index 68220fd9e1..4e2027671c 100644 --- a/models/ref/python/custom-charts/line_series.mdx +++ b/models/ref/python/custom-charts/line_series.mdx @@ -1,51 +1,49 @@ --- -title: line_series() -namespace: python_sdk_custom_charts -python_object_type: function +title: line_series +kind: function +namespace: wandb.plot.line_series --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; + -### function `line_series` ```python -line_series( - xs: 'Iterable[Iterable[Any]] | Iterable[Any]', - ys: 'Iterable[Iterable[Any]]', - keys: 'Iterable[str] | None' = None, - title: 'str' = '', - xname: 'str' = 'x', - split_table: 'bool' = False -) → CustomChart +xs: 'Iterable[Iterable[Any]] | Iterable[Any]', +ys: 'Iterable[Iterable[Any]]', +keys: 'Iterable[str] | None' = None, +title: 'str' = '', +xname: 'str' = 'x', +split_table: 'bool' = False ``` -Constructs a line series chart. +## Description + +Constructs a line series chart. + +## Args: +- **xs**: Sequence of x values. If a singular array is provided, all y values are plotted against that x array. If an array of arrays is provided, each y value is plotted against the corresponding x array. +- **ys**: Sequence of y values, where each iterable represents a separate line series. +- **keys**: Sequence of keys for labeling each line series. If not provided, keys will be automatically generated as "line_1", "line_2", etc. +- **title**: Title of the chart. +- **xname**: Label for the x-axis. +- **split_table**: Whether the table should be split into a separate section in the W&B UI. If `True`, the table will be displayed in a section named "Custom Chart Tables". Default is `False`. -**Args:** - - - `xs`: Sequence of x values. If a singular array is provided, all y values are plotted against that x array. If an array of arrays is provided, each y value is plotted against the corresponding x array. - - `ys`: Sequence of y values, where each iterable represents a separate line series. - - `keys`: Sequence of keys for labeling each line series. If not provided, keys will be automatically generated as "line_1", "line_2", etc. - - `title`: Title of the chart. - - `xname`: Label for the x-axis. - - `split_table`: Whether the table should be split into a separate section in the W&B UI. If `True`, the table will be displayed in a section named "Custom Chart Tables". Default is `False`. +## Returns: +- **CustomChart**: A custom chart object that can be logged to W&B. To log the chart, pass it to `wandb.log()`. -**Returns:** - - - `CustomChart`: A custom chart object that can be logged to W&B. To log the chart, pass it to `wandb.log()`. +## Examples: -**Examples:** - Logging a single x array where all y series are plotted against the same x values: +Logging a single x array where all y series are plotted against the same x values: ```python import wandb @@ -57,24 +55,26 @@ with wandb.init(project="line_series_example") as run: # Multiple y series to plot ys = [ - [i for i in range(10)], # y = x - [i**2 for i in range(10)], # y = x^2 - [i**3 for i in range(10)], # y = x^3 + [i for i in range(10)], # y = x + [i**2 for i in range(10)], # y = x^2 + [i**3 for i in range(10)], # y = x^3 ] # Generate and log the line series chart line_series_chart = wandb.plot.line_series( - xs, - ys, - title="title", - xname="step", + xs, + ys, + title="title", + xname="step", ) run.log({"line-series-single-x": line_series_chart}) -``` +``` -In this example, a single `xs` series (shared x-values) is used for all `ys` series. This results in each y-series being plotted against the same x-values (0-9). +In this example, a single `xs` series (shared x-values) is used for all +`ys` series. This results in each y-series being plotted against the +same x-values (0-9). -Logging multiple x arrays where each y series is plotted against its corresponding x array: +Logging multiple x arrays where each y series is plotted against its corresponding x array: ```python import wandb @@ -83,28 +83,30 @@ import wandb with wandb.init(project="line_series_example") as run: # Separate x values for each y series xs = [ - [i for i in range(10)], # x for first series - [2 * i for i in range(10)], # x for second series (stretched) - [3 * i for i in range(10)], # x for third series (stretched more) + [i for i in range(10)], # x for first series + [2 * i for i in range(10)], # x for second series (stretched) + [3 * i for i in range(10)], # x for third series (stretched more) ] # Corresponding y series ys = [ - [i for i in range(10)], # y = x - [i**2 for i in range(10)], # y = x^2 - [i**3 for i in range(10)], # y = x^3 + [i for i in range(10)], # y = x + [i**2 for i in range(10)], # y = x^2 + [i**3 for i in range(10)], # y = x^3 ] # Generate and log the line series chart line_series_chart = wandb.plot.line_series( - xs, ys, title="Multiple X Arrays Example", xname="Step" + xs, ys, title="Multiple X Arrays Example", xname="Step" ) run.log({"line-series-multiple-x": line_series_chart}) -``` +``` -In this example, each y series is plotted against its own unique x series. This allows for more flexibility when the x values are not uniform across the data series. +In this example, each y series is plotted against its own unique x series. +This allows for more flexibility when the x values are not uniform across +the data series. -Customizing line labels using `keys`: +Customizing line labels using `keys`: ```python import wandb @@ -113,9 +115,9 @@ import wandb with wandb.init(project="line_series_example") as run: xs = list(range(10)) # Single x array ys = [ - [i for i in range(10)], # y = x - [i**2 for i in range(10)], # y = x^2 - [i**3 for i in range(10)], # y = x^3 + [i for i in range(10)], # y = x + [i**2 for i in range(10)], # y = x^2 + [i**3 for i in range(10)], # y = x^3 ] # Custom labels for each line @@ -123,13 +125,16 @@ with wandb.init(project="line_series_example") as run: # Generate and log the line series chart line_series_chart = wandb.plot.line_series( - xs, - ys, - keys=keys, # Custom keys (line labels) - title="Custom Line Labels Example", - xname="Step", + xs, + ys, + keys=keys, # Custom keys (line labels) + title="Custom Line Labels Example", + xname="Step", ) run.log({"line-series-custom-keys": line_series_chart}) -``` +``` + +This example shows how to provide custom labels for the lines using +the `keys` argument. The keys will appear in the legend as "Linear", +"Quadratic", and "Cubic". -This example shows how to provide custom labels for the lines using the `keys` argument. The keys will appear in the legend as "Linear", "Quadratic", and "Cubic". diff --git a/models/ref/python/custom-charts/plot_table.mdx b/models/ref/python/custom-charts/plot_table.mdx index 41dd583194..a527159e9e 100644 --- a/models/ref/python/custom-charts/plot_table.mdx +++ b/models/ref/python/custom-charts/plot_table.mdx @@ -1,57 +1,54 @@ --- -title: plot_table() -namespace: python_sdk_custom_charts -python_object_type: function +title: plot_table +kind: function +namespace: wandb.plot.custom_chart --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; + -### function `plot_table` ```python -plot_table( - vega_spec_name: 'str', - data_table: 'wandb.Table', - fields: 'dict[str, Any]', - string_fields: 'dict[str, Any] | None' = None, - split_table: 'bool' = False -) → CustomChart +vega_spec_name: 'str', +data_table: 'wandb.Table', +fields: 'dict[str, Any]', +string_fields: 'dict[str, Any] | None' = None, +split_table: 'bool' = False ``` -Creates a custom charts using a Vega-Lite specification and a `wandb.Table`. - -This function creates a custom chart based on a Vega-Lite specification and a data table represented by a `wandb.Table` object. The specification needs to be predefined and stored in the W&B backend. The function returns a custom chart object that can be logged to W&B using `wandb.Run.log()`. +## Description +Creates a custom charts using a Vega-Lite specification and a `wandb.Table`. +This function creates a custom chart based on a Vega-Lite specification and +a data table represented by a `wandb.Table` object. The specification needs +to be predefined and stored in the W&B backend. The function returns a custom +chart object that can be logged to W&B using `wandb.Run.log()`. -**Args:** - - - `vega_spec_name`: The name or identifier of the Vega-Lite spec that defines the visualization structure. - - `data_table`: A `wandb.Table` object containing the data to be visualized. - - `fields`: A mapping between the fields in the Vega-Lite spec and the corresponding columns in the data table to be visualized. - - `string_fields`: A dictionary for providing values for any string constants required by the custom visualization. - - `split_table`: Whether the table should be split into a separate section in the W&B UI. If `True`, the table will be displayed in a section named "Custom Chart Tables". Default is `False`. +## Args: +- **vega_spec_name**: The name or identifier of the Vega-Lite spec that defines the visualization structure. +- **data_table**: A `wandb.Table` object containing the data to be visualized. +- **fields**: A mapping between the fields in the Vega-Lite spec and the corresponding columns in the data table to be visualized. +- **string_fields**: A dictionary for providing values for any string constants required by the custom visualization. +- **split_table**: Whether the table should be split into a separate section in the W&B UI. If `True`, the table will be displayed in a section named "Custom Chart Tables". Default is `False`. -**Returns:** - - - `CustomChart`: A custom chart object that can be logged to W&B. To log the chart, pass the chart object as argument to `wandb.Run.log()`. +## Returns: +- **CustomChart**: A custom chart object that can be logged to W&B. To log the chart, pass the chart object as argument to `wandb.Run.log()`. +- **Raises**: +- **wandb.Error**: If `data_table` is not a `wandb.Table` object. -**Raises:** - - - `wandb.Error`: If `data_table` is not a `wandb.Table` object. +## Examples: -**Example:** - ```python +```python # Create a custom chart using a Vega-Lite spec and the data table. import wandb @@ -64,11 +61,12 @@ with wandb.init() as run: # Create a custom title with `string_fields`. my_custom_chart = wandb.plot_table( - vega_spec_name="wandb/line/v0", - data_table=table, - fields=fields, - string_fields={"title": "Title"}, + vega_spec_name="wandb/line/v0", + data_table=table, + fields=fields, + string_fields={"title": "Title"}, ) run.log({"custom_chart": my_custom_chart}) -``` +``` + diff --git a/models/ref/python/custom-charts/pr_curve.mdx b/models/ref/python/custom-charts/pr_curve.mdx index 1b1b209df8..d96fe7c694 100644 --- a/models/ref/python/custom-charts/pr_curve.mdx +++ b/models/ref/python/custom-charts/pr_curve.mdx @@ -1,63 +1,58 @@ --- -title: pr_curve() -namespace: python_sdk_custom_charts -python_object_type: function +title: pr_curve +kind: function +namespace: wandb.plot.pr_curve --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; + -### function `pr_curve` ```python -pr_curve( - y_true: 'Iterable[T] | None' = None, - y_probas: 'Iterable[numbers.Number] | None' = None, - labels: 'list[str] | None' = None, - classes_to_plot: 'list[T] | None' = None, - interp_size: 'int' = 21, - title: 'str' = 'Precision-Recall Curve', - split_table: 'bool' = False -) → CustomChart +y_true: 'Iterable[T] | None' = None, +y_probas: 'Iterable[numbers.Number] | None' = None, +labels: 'list[str] | None' = None, +classes_to_plot: 'list[T] | None' = None, +interp_size: 'int' = 21, +title: 'str' = 'Precision-Recall Curve', +split_table: 'bool' = False ``` -Constructs a Precision-Recall (PR) curve. - -The Precision-Recall curve is particularly useful for evaluating classifiers on imbalanced datasets. A high area under the PR curve signifies both high precision (a low false positive rate) and high recall (a low false negative rate). The curve provides insights into the balance between false positives and false negatives at various threshold levels, aiding in the assessment of a model's performance. - +## Description +Constructs a Precision-Recall (PR) curve. -**Args:** - - - `y_true`: True binary labels. The shape should be (`num_samples`,). - - `y_probas`: Predicted scores or probabilities for each class. These can be probability estimates, confidence scores, or non-thresholded decision values. The shape should be (`num_samples`, `num_classes`). - - `labels`: Optional list of class names to replace numeric values in `y_true` for easier plot interpretation. For example, `labels = ['dog', 'cat', 'owl']` will replace 0 with 'dog', 1 with 'cat', and 2 with 'owl' in the plot. If not provided, numeric values from `y_true` will be used. - - `classes_to_plot`: Optional list of unique class values from y_true to be included in the plot. If not specified, all unique classes in y_true will be plotted. - - `interp_size`: Number of points to interpolate recall values. The recall values will be fixed to `interp_size` uniformly distributed points in the range [0, 1], and the precision will be interpolated accordingly. - - `title`: Title of the plot. Defaults to "Precision-Recall Curve". - - `split_table`: Whether the table should be split into a separate section in the W&B UI. If `True`, the table will be displayed in a section named "Custom Chart Tables". Default is `False`. +The Precision-Recall curve is particularly useful for evaluating classifiers +on imbalanced datasets. A high area under the PR curve signifies both high +precision (a low false positive rate) and high recall (a low false negative +rate). The curve provides insights into the balance between false positives +and false negatives at various threshold levels, aiding in the assessment of +a model's performance. +## Args: +- **y_true**: True binary labels. The shape should be (`num_samples`,). +- **y_probas**: Predicted scores or probabilities for each class. These can be probability estimates, confidence scores, or non-thresholded decision values. The shape should be (`num_samples`, `num_classes`). +- **labels**: Optional list of class names to replace numeric values in `y_true` for easier plot interpretation. For example, `labels = ['dog', 'cat', 'owl']` will replace 0 with 'dog', 1 with 'cat', and 2 with 'owl' in the plot. If not provided, numeric values from `y_true` will be used. +- **classes_to_plot**: Optional list of unique class values from y_true to be included in the plot. If not specified, all unique classes in y_true will be plotted. +- **interp_size**: Number of points to interpolate recall values. The recall values will be fixed to `interp_size` uniformly distributed points in the range [0, 1], and the precision will be interpolated accordingly. +- **title**: Title of the plot. Defaults to "Precision-Recall Curve". +- **split_table**: Whether the table should be split into a separate section in the W&B UI. If `True`, the table will be displayed in a section named "Custom Chart Tables". Default is `False`. -**Returns:** - - - `CustomChart`: A custom chart object that can be logged to W&B. To log the chart, pass it to `wandb.log()`. +## Returns: +- **CustomChart**: A custom chart object that can be logged to W&B. To log the chart, pass it to `wandb.log()`. +- **Raises**: +- **wandb.Error**: If NumPy, pandas, or scikit-learn is not installed. -**Raises:** - - - `wandb.Error`: If NumPy, pandas, or scikit-learn is not installed. - - -**Example:** - +## Examples: ```python import wandb @@ -76,10 +71,11 @@ labels = ["not spam", "spam"] # Optional class names for readability with wandb.init(project="spam-detection") as run: pr_curve = wandb.plot.pr_curve( - y_true=y_true, - y_probas=y_probas, - labels=labels, - title="Precision-Recall Curve for Spam Detection", + y_true=y_true, + y_probas=y_probas, + labels=labels, + title="Precision-Recall Curve for Spam Detection", ) run.log({"pr-curve": pr_curve}) -``` +``` + diff --git a/models/ref/python/custom-charts/roc_curve.mdx b/models/ref/python/custom-charts/roc_curve.mdx index 8f0d24c81c..b2d15dfdc7 100644 --- a/models/ref/python/custom-charts/roc_curve.mdx +++ b/models/ref/python/custom-charts/roc_curve.mdx @@ -1,57 +1,51 @@ --- -title: roc_curve() -namespace: python_sdk_custom_charts -python_object_type: function +title: roc_curve +kind: function +namespace: wandb.plot.roc_curve --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; + -### function `roc_curve` ```python -roc_curve( - y_true: 'Sequence[numbers.Number]', - y_probas: 'Sequence[Sequence[float]] | None' = None, - labels: 'list[str] | None' = None, - classes_to_plot: 'list[numbers.Number] | None' = None, - title: 'str' = 'ROC Curve', - split_table: 'bool' = False -) → CustomChart +y_true: 'Sequence[numbers.Number]', +y_probas: 'Sequence[Sequence[float]] | None' = None, +labels: 'list[str] | None' = None, +classes_to_plot: 'list[numbers.Number] | None' = None, +title: 'str' = 'ROC Curve', +split_table: 'bool' = False ``` -Constructs Receiver Operating Characteristic (ROC) curve chart. - +## Description +Constructs Receiver Operating Characteristic (ROC) curve chart. -**Args:** - - - `y_true`: The true class labels (ground truth) for the target variable. Shape should be (num_samples,). - - `y_probas`: The predicted probabilities or decision scores for each class. Shape should be (num_samples, num_classes). - - `labels`: Human-readable labels corresponding to the class indices in `y_true`. For example, if `labels=['dog', 'cat']`, class 0 will be displayed as 'dog' and class 1 as 'cat' in the plot. If None, the raw class indices from `y_true` will be used. Default is None. - - `classes_to_plot`: A subset of unique class labels to include in the ROC curve. If None, all classes in `y_true` will be plotted. Default is None. - - `title`: Title of the ROC curve plot. Default is "ROC Curve". - - `split_table`: Whether the table should be split into a separate section in the W&B UI. If `True`, the table will be displayed in a section named "Custom Chart Tables". Default is `False`. +## Args: +- **y_true**: The true class labels (ground truth) for the target variable. Shape should be (num_samples,). +- **y_probas**: The predicted probabilities or decision scores for each class. Shape should be (num_samples, num_classes). +- **labels**: Human-readable labels corresponding to the class indices in `y_true`. For example, if `labels=['dog', 'cat']`, class 0 will be displayed as 'dog' and class 1 as 'cat' in the plot. If None, the raw class indices from `y_true` will be used. Default is None. +- **classes_to_plot**: A subset of unique class labels to include in the ROC curve. If None, all classes in `y_true` will be plotted. Default is None. +- **title**: Title of the ROC curve plot. Default is "ROC Curve". +- **split_table**: Whether the table should be split into a separate section in the W&B UI. If `True`, the table will be displayed in a section named "Custom Chart Tables". Default is `False`. -**Returns:** - - - `CustomChart`: A custom chart object that can be logged to W&B. To log the chart, pass it to `wandb.log()`. +## Returns: +- **CustomChart**: A custom chart object that can be logged to W&B. To log the chart, pass it to `wandb.log()`. +- **Raises**: +- **wandb.Error**: If numpy, pandas, or scikit-learn are not found. -**Raises:** - - - `wandb.Error`: If numpy, pandas, or scikit-learn are not found. +## Examples: -**Example:** - ```python +```python import numpy as np import wandb @@ -75,11 +69,12 @@ classes_to_plot = [0, 1, 2] # Initialize a W&B run and log a ROC curve plot for disease classification with wandb.init(project="medical_diagnosis") as run: roc_plot = wandb.plot.roc_curve( - y_true=y_true, - y_probas=y_probas, - labels=disease_labels, - classes_to_plot=classes_to_plot, - title="ROC Curve for Disease Classification", + y_true=y_true, + y_probas=y_probas, + labels=disease_labels, + classes_to_plot=classes_to_plot, + title="ROC Curve for Disease Classification", ) run.log({"roc-curve": roc_plot}) -``` +``` + diff --git a/models/ref/python/custom-charts/scatter.mdx b/models/ref/python/custom-charts/scatter.mdx index eebcbd41cb..5614b6df29 100644 --- a/models/ref/python/custom-charts/scatter.mdx +++ b/models/ref/python/custom-charts/scatter.mdx @@ -1,47 +1,47 @@ --- -title: scatter() -namespace: python_sdk_custom_charts -python_object_type: function +title: scatter +kind: function +namespace: wandb.plot.scatter --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; + -### function `scatter` ```python -scatter( - table: 'wandb.Table', - x: 'str', - y: 'str', - title: 'str' = '', - split_table: 'bool' = False -) → CustomChart +table: 'wandb.Table', +x: 'str', +y: 'str', +title: 'str' = '', +split_table: 'bool' = False ``` -Constructs a scatter plot from a wandb.Table of data. +## Description + +Constructs a scatter plot from a wandb.Table of data. + +## Args: + +- **table**: The W&B Table containing the data to visualize. +- **x**: The name of the column used for the x-axis. +- **y**: The name of the column used for the y-axis. +- **title**: The title of the scatter chart. +- **split_table**: Whether the table should be split into a separate section in the W&B UI. If `True`, the table will be displayed in a section named "Custom Chart Tables". Default is `False`. +## Returns: -**Args:** - - - `table`: The W&B Table containing the data to visualize. - - `x`: The name of the column used for the x-axis. - - `y`: The name of the column used for the y-axis. - - `title`: The title of the scatter chart. - - `split_table`: Whether the table should be split into a separate section in the W&B UI. If `True`, the table will be displayed in a section named "Custom Chart Tables". Default is `False`. +- **CustomChart**: A custom chart object that can be logged to W&B. To log the chart, pass it to `wandb.log()`. -**Returns:** - - - `CustomChart`: A custom chart object that can be logged to W&B. To log the chart, pass it to `wandb.log()`. -**Example:** - ```python +## Examples: + +```python import math import random import wandb @@ -59,10 +59,11 @@ table = wandb.Table(data=data, columns=["altitude (m)", "temperature (°C)"]) with wandb.init(project="temperature-altitude-scatter") as run: # Create and log the scatter plot scatter_plot = wandb.plot.scatter( - table=table, - x="altitude (m)", - y="temperature (°C)", - title="Altitude vs Temperature", + table=table, + x="altitude (m)", + y="temperature (°C)", + title="Altitude vs Temperature", ) run.log({"altitude-temperature-scatter": scatter_plot}) -``` +``` + diff --git a/models/ref/python/data-types/audio.mdx b/models/ref/python/data-types/audio.mdx index 018146a0ba..54688fce46 100644 --- a/models/ref/python/data-types/audio.mdx +++ b/models/ref/python/data-types/audio.mdx @@ -1,64 +1,81 @@ --- title: Audio -namespace: python_sdk_data_type -python_object_type: class +kind: class +namespace: wandb.sdk.data_types.audio --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - - +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; + -## class `Audio` -W&B class for audio clips. -### method `Audio.__init__` ```python -__init__( - data_or_path: 'str | pathlib.Path | list | np.ndarray', - sample_rate: 'int | None' = None, - caption: 'str | None' = None -) +(data_or_path: 'str | pathlib.Path | list | np.ndarray', +sample_rate: 'int | None' = None, +caption: 'str | None' = None) ``` -Accept a path to an audio file or a numpy array of audio data. +## Description +W&B class for audio clips. -**Args:** - - - `data_or_path`: A path to an audio file or a NumPy array of audio data. - - `sample_rate`: Sample rate, required when passing in raw NumPy array of audio data. - - `caption`: Caption to display with audio. +## Args: +- **data_or_path**: +- **sample_rate**: +- **caption**: ---- +## Methods: -### classmethod `Audio.durations` +### durations -```python -durations(audio_list) -``` +Calculate the duration of the audio files. -Calculate the duration of the audio files. +### file_is_set ---- +### init_from_json -### classmethod `Audio.sample_rates` +Initialize a `WBValue` from a JSON blob based on the class that created it. -```python -sample_rates(audio_list) -``` +Looks through all subclasses and tries to match the json obj with the class +which created it. It will then call that subclass' `from_json` method. +Importantly, this function will set the return object's `source_artifact` +attribute to the passed in source artifact. This is critical for artifact +bookkeeping. If you choose to create a wandb.Value via it's `from_json` method, +make sure to properly set this `artifact_source` to avoid data duplication. + +### is_bound + + + +### path_is_reference + + + +### sample_rates + +Get sample rates of the audio files. + +### to_data_array + +Convert the object to a list of primitives representing the underlying data. + +### type_mapping + +Return a map from `_log_type` to subclass. Used to lookup correct types for deserialization. + +### with_suffix + +Get the name with the appropriate suffix. -Get sample rates of the audio files. ---- diff --git a/models/ref/python/data-types/box3d.mdx b/models/ref/python/data-types/box3d.mdx index 731f65ee43..04e78d789d 100644 --- a/models/ref/python/data-types/box3d.mdx +++ b/models/ref/python/data-types/box3d.mdx @@ -1,104 +1,50 @@ --- -title: box3d() -namespace: python_sdk_data_type -python_object_type: function +title: box3d +kind: function +namespace: wandb.sdk.data_types.object_3d --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; + -### function `box3d` ```python -box3d( - center: 'npt.ArrayLike', - size: 'npt.ArrayLike', - orientation: 'npt.ArrayLike', - color: 'RGBColor', - label: 'str | None' = None, - score: 'numeric | None' = None -) → Box3D +*, +center: 'npt.ArrayLike', +size: 'npt.ArrayLike', +orientation: 'npt.ArrayLike', +color: 'RGBColor', +label: 'str | None' = None, +score: 'numeric | None' = None ``` -A 3D bounding box. The box is specified by its center, size and orientation. +## Description +A 3D bounding box. The box is specified by its center, size and orientation. +## Args: -**Args:** - - - `center`: The center point of the box as a length-3 ndarray. - - `size`: The box's X, Y and Z dimensions as a length-3 ndarray. - - `orientation`: The rotation transforming global XYZ coordinates into the box's local XYZ coordinates, given as a length-4 ndarray [r, x, y, z] corresponding to the non-zero quaternion r + xi + yj + zk. - - `color`: The box's color as an (r, g, b) tuple with `0 <= r,g,b <= 1`. - - `label`: An optional label for the box. - - `score`: An optional score for the box. Typically used to indicate the confidence of a detection. +- **center**: The center point of the box as a length-3 ndarray. +- **size**: The box's X, Y and Z dimensions as a length-3 ndarray. +- **orientation**: The rotation transforming global XYZ coordinates into the box's local XYZ coordinates, given as a length-4 ndarray [r, x, y, z] corresponding to the non-zero quaternion r + xi + yj + zk. +- **color**: The box's color as an (r, g, b) tuple with `0 <= r,g,b <= 1`. +- **label**: An optional label for the box. +- **score**: An optional score for the box. Typically used to indicate the confidence of a detection. +## Returns: + +- ****: A Box3D object. + +{/* - **Example**: The following example creates a point cloud with 60 boxes rotating around the X, Y and Z axes. ```python import wandb import math import numpy as np from scipy.spatial.transform import Rotation +- **with wandb.init**: run.log( { +- **"points"**: wandb.Object3D.from_point_cloud( points=np.random.uniform(-5, 5, size=(100, 3)), boxes=[ wandb.box3d( center=(0.3 * t - 3, 0, 0), size=(0.1, 0.1, 0.1), orientation=Rotation.from_euler( "xyz", [t * math.pi / 10, 0, 0] ).as_quat(), color=(0.5 + t / 40, 0.5, 0.5), label=f"box {t}", score=0.9, ) for t in range(20) ] + [ wandb.box3d( center=(0, 0.3 * t - 3, 0.3), size=(0.1, 0.1, 0.1), orientation=Rotation.from_euler( "xyz", [0, t * math.pi / 10, 0] ).as_quat(), color=(0.5, 0.5 + t / 40, 0.5), label=f"box {t}", score=0.9, ) for t in range(20) ] + [ wandb.box3d( center=(0.3, 0.3, 0.3 * t - 3), size=(0.1, 0.1, 0.1), orientation=Rotation.from_euler( "xyz", [0, 0, t * math.pi / 10] ).as_quat(), color=(0.5, 0.5, 0.5 + t / 40), label=f"box {t}", score=0.9, ) for t in range(20) ], ), } ) ``` */} + -**Returns:** - A Box3D object. -**Example:** - The following example creates a point cloud with 60 boxes rotating around the X, Y and Z axes. -```python -import wandb - -import math -import numpy as np -from scipy.spatial.transform import Rotation - - -with wandb.init() as run: - run.log( - { - "points": wandb.Object3D.from_point_cloud( - points=np.random.uniform(-5, 5, size=(100, 3)), - boxes=[ - wandb.box3d( - center=(0.3 * t - 3, 0, 0), - size=(0.1, 0.1, 0.1), - orientation=Rotation.from_euler( - "xyz", [t * math.pi / 10, 0, 0] - ).as_quat(), - color=(0.5 + t / 40, 0.5, 0.5), - label=f"box {t}", - score=0.9, - ) - for t in range(20) - ] - + [ - wandb.box3d( - center=(0, 0.3 * t - 3, 0.3), - size=(0.1, 0.1, 0.1), - orientation=Rotation.from_euler( - "xyz", [0, t * math.pi / 10, 0] - ).as_quat(), - color=(0.5, 0.5 + t / 40, 0.5), - label=f"box {t}", - score=0.9, - ) - for t in range(20) - ] - + [ - wandb.box3d( - center=(0.3, 0.3, 0.3 * t - 3), - size=(0.1, 0.1, 0.1), - orientation=Rotation.from_euler( - "xyz", [0, 0, t * math.pi / 10] - ).as_quat(), - color=(0.5, 0.5, 0.5 + t / 40), - label=f"box {t}", - score=0.9, - ) - for t in range(20) - ], - ), - } - ) -``` diff --git a/models/ref/python/data-types/histogram.mdx b/models/ref/python/data-types/histogram.mdx index 329eba227e..ccf41d04c0 100644 --- a/models/ref/python/data-types/histogram.mdx +++ b/models/ref/python/data-types/histogram.mdx @@ -1,67 +1,75 @@ --- title: Histogram -namespace: python_sdk_data_type -python_object_type: class +kind: class +namespace: wandb.sdk.data_types.histogram --- + import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - + -## class `Histogram` -W&B class for histograms. +```python +sequence: 'Sequence | None' = None, +np_histogram: 'NumpyHistogram | None' = None, +num_bins: 'int' = 64 +``` -This object works just like numpy's histogram function https://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html +## Description +W&B class for histograms. +This object works just like numpy's histogram function +https://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html -**Attributes:** - - - `bins` ([float]): Edges of bins - - `histogram` ([int]): Number of elements falling in each bin. +Attributes: + bins ([float]): Edges of bins + histogram ([int]): Number of elements falling in each bin. -### method `Histogram.__init__` -```python -__init__( - sequence: 'Sequence | None' = None, - np_histogram: 'NumpyHistogram | None' = None, - num_bins: 'int' = 64 -) → None -``` -Initialize a Histogram object. +## Args: +- **sequence**: +- **np_histogram**: +- **num_bins**: -**Args:** - sequence: Input data for histogram. np_histogram: Alternative input of a precomputed histogram. num_bins: Number of bins for the histogram. The default number of bins is 64. The maximum number of bins is 512. +## Methods: -**Examples:** - Generate histogram from a sequence. +### from_json -```python -import wandb +Deserialize a `json_obj` into it's class representation. -wandb.Histogram([1, 2, 3]) -``` +If additional resources were stored in the `run_or_artifact` artifact during the +`to_json` call, then those resources should be in the `source_artifact`. -Efficiently initialize from np.histogram. +### init_from_json -```python -import numpy as np -import wandb +Initialize a `WBValue` from a JSON blob based on the class that created it. -hist = np.histogram(data) -wandb.Histogram(np_histogram=hist) -``` +Looks through all subclasses and tries to match the json obj with the class +which created it. It will then call that subclass' `from_json` method. +Importantly, this function will set the return object's `source_artifact` +attribute to the passed in source artifact. This is critical for artifact +bookkeeping. If you choose to create a wandb.Value via it's `from_json` method, +make sure to properly set this `artifact_source` to avoid data duplication. +### to_data_array +Convert the object to a list of primitives representing the underlying data. + +### type_mapping + +Return a map from `_log_type` to subclass. Used to lookup correct types for deserialization. + +### with_suffix + +Get the name with the appropriate suffix. ---- diff --git a/models/ref/python/data-types/html.mdx b/models/ref/python/data-types/html.mdx index f28e8a10b5..c3a80914cd 100644 --- a/models/ref/python/data-types/html.mdx +++ b/models/ref/python/data-types/html.mdx @@ -1,58 +1,84 @@ --- title: Html -namespace: python_sdk_data_type -python_object_type: class +kind: class +namespace: wandb.sdk.data_types.html --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - - +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; + -## class `Html` -W&B class for logging HTML content to W&B. -### method `Html.__init__` ```python -__init__( - data: 'str | pathlib.Path | TextIO', - inject: 'bool' = True, - data_is_not_path: 'bool' = False -) → None +data: 'str | pathlib.Path | TextIO', +inject: 'bool' = True, +data_is_not_path: 'bool' = False ``` -Creates a W&B HTML object. +## Description +W&B class for logging HTML content to W&B. -**Args:** - data: A string that is a path to a file with the extension ".html", or a string or IO object containing literal HTML. - - `inject`: Add a stylesheet to the HTML object. If set to False the HTML will pass through unchanged. - - `data_is_not_path`: If set to False, the data will be treated as a path to a file. +## Args: +- **data**: +- **inject**: +- **data_is_not_path**: -**Examples:** - It can be initialized by providing a path to a file: -```python -with wandb.init() as run: - run.log({"html": wandb.Html("./index.html")}) -``` -Alternatively, it can be initialized by providing literal HTML, in either a string or IO object: -```python -with wandb.init() as run: - run.log({"html": wandb.Html("

Hello, world!

")}) -``` +## Methods: +### bind_to_run +Bind this object to a particular Run. +Calling this function is necessary so that we have somewhere specific to put the +file associated with this object, from which other Runs can refer to it. ---- +### captions + + + +### file_is_set + + + +### init_from_json + +Initialize a `WBValue` from a JSON blob based on the class that created it. + +Looks through all subclasses and tries to match the json obj with the class +which created it. It will then call that subclass' `from_json` method. +Importantly, this function will set the return object's `source_artifact` +attribute to the passed in source artifact. This is critical for artifact +bookkeeping. If you choose to create a wandb.Value via it's `from_json` method, +make sure to properly set this `artifact_source` to avoid data duplication. + +### is_bound + + + +### path_is_reference + + + +### to_data_array + +Convert the object to a list of primitives representing the underlying data. + +### type_mapping + +Return a map from `_log_type` to subclass. Used to lookup correct types for deserialization. + +### with_suffix + +Get the name with the appropriate suffix. diff --git a/models/ref/python/data-types/image.mdx b/models/ref/python/data-types/image.mdx index 3729ff30b3..c7a1119767 100644 --- a/models/ref/python/data-types/image.mdx +++ b/models/ref/python/data-types/image.mdx @@ -1,129 +1,91 @@ --- title: Image -namespace: python_sdk_data_type -python_object_type: class +kind: class +namespace: wandb.sdk.data_types.image --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - - +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; + -## class `Image` -A class for logging images to W&B. -### method `Image.__init__` ```python -__init__( - data_or_path: 'ImageDataOrPathType', - mode: 'str | None' = None, - caption: 'str | None' = None, - grouping: 'int | None' = None, - classes: 'Classes | Sequence[dict] | None' = None, - boxes: 'dict[str, BoundingBoxes2D] | dict[str, dict] | None' = None, - masks: 'dict[str, ImageMask] | dict[str, dict] | None' = None, - file_type: 'str | None' = None, - normalize: 'bool' = True -) → None +data_or_path: 'ImageDataOrPathType', +mode: 'str | None' = None, +caption: 'str | None' = None, +grouping: 'int | None' = None, +classes: 'Classes | Sequence[dict] | None' = None, +boxes: 'dict[str, BoundingBoxes2D] | dict[str, dict] | None' = None, +masks: 'dict[str, ImageMask] | dict[str, dict] | None' = None, +file_type: 'str | None' = None, +normalize: 'bool' = True ``` -Initialize a `wandb.Image` object. +## Description -This class handles various image data formats and automatically normalizes pixel values to the range [0, 255] when needed, ensuring compatibility with the W&B backend. +A class for logging images to W&B. -* Data in range [0, 1] is multiplied by 255 and converted to uint8 * Data in range [-1, 1] is rescaled from [-1, 1] to [0, 255] by mapping - -1 to 0 and 1 to 255, then converted to uint8 * Data outside [-1, 1] but not in [0, 255] is clipped to [0, 255] and converted to uint8 (with a warning if values fall outside [0, 255]) * Data already in [0, 255] is converted to uint8 without modification +## Args: -**Args:** - - - `data_or_path`: Accepts NumPy array/pytorch tensor of image data, a PIL image object, or a path to an image file. If a NumPy array or pytorch tensor is provided, the image data will be saved to the given file type. If the values are not in the range [0, 255] or all values are in the range [0, 1], the image pixel values will be normalized to the range [0, 255] unless `normalize` is set to `False`. - - pytorch tensor should be in the format (channel, height, width) - - NumPy array should be in the format (height, width, channel) - - `mode`: The PIL mode for an image. Most common are "L", "RGB", "RGBA". - - `Full Pillow docs for more information https`: //pillow.readthedocs.io/en/stable/handbook/concepts.html#modes - - `caption`: Label for display of image. - - `grouping`: The grouping number for the image. - - `classes`: A list of class information for the image, used for labeling bounding boxes, and image masks. - - `boxes`: A dictionary containing bounding box information for the image. - - `see https`: //docs.wandb.ai/models/ref/python/data-types/boundingboxes2d - - `masks`: A dictionary containing mask information for the image. - - `see https`: //docs.wandb.ai/models/ref/python/data-types/imagemask - - `file_type`: The file type to save the image as. This parameter has no effect if `data_or_path` is a path to an image file. - - `normalize`: If `True`, normalize the image pixel values to fall within the range of [0, 255]. Normalize is only applied if `data_or_path` is a numpy array or pytorch tensor. +- **data_or_path**: +- **mode**: +- **caption**: +- **grouping**: +- **classes**: +- **boxes**: +- **masks**: +- **file_type**: +- **normalize**: +## Properties: -**Examples:** - Create a wandb.Image from a numpy array +### image -```python -import numpy as np -import wandb -with wandb.init() as run: - examples = [] - for i in range(3): - pixels = np.random.randint(low=0, high=256, size=(100, 100, 3)) - image = wandb.Image(pixels, caption=f"random field {i}") - examples.append(image) - run.log({"examples": examples}) -``` -Create a wandb.Image from a PILImage -```python -import numpy as np -from PIL import Image as PILImage -import wandb - -with wandb.init() as run: - examples = [] - for i in range(3): - pixels = np.random.randint( - low=0, high=256, size=(100, 100, 3), dtype=np.uint8 - ) - pil_image = PILImage.fromarray(pixels, mode="RGB") - image = wandb.Image(pil_image, caption=f"random field {i}") - examples.append(image) - run.log({"examples": examples}) -``` - -Log .jpg rather than .png (default) -```python -import numpy as np -import wandb +## Methods: -with wandb.init() as run: - examples = [] - for i in range(3): - pixels = np.random.randint(low=0, high=256, size=(100, 100, 3)) - image = wandb.Image( - pixels, caption=f"random field {i}", file_type="jpg" - ) - examples.append(image) - run.log({"examples": examples}) -``` +### captions ---- -### property Image.image +### file_is_set +### init_from_json +Initialize a `WBValue` from a JSON blob based on the class that created it. +Looks through all subclasses and tries to match the json obj with the class +which created it. It will then call that subclass' `from_json` method. +Importantly, this function will set the return object's `source_artifact` +attribute to the passed in source artifact. This is critical for artifact +bookkeeping. If you choose to create a wandb.Value via it's `from_json` method, +make sure to properly set this `artifact_source` to avoid data duplication. +### is_bound ---- +### path_is_reference + + + +### type_mapping + +Return a map from `_log_type` to subclass. Used to lookup correct types for deserialization. + +### with_suffix +Get the name with the appropriate suffix. diff --git a/models/ref/python/data-types/molecule.mdx b/models/ref/python/data-types/molecule.mdx index 7de6135d08..14d98e5456 100644 --- a/models/ref/python/data-types/molecule.mdx +++ b/models/ref/python/data-types/molecule.mdx @@ -1,42 +1,95 @@ --- title: Molecule -namespace: python_sdk_data_type -python_object_type: class +kind: class +namespace: wandb.sdk.data_types.molecule --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - - +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; + -## class `Molecule` -W&B class for 3D Molecular data. -### method `Molecule.__init__` ```python -__init__( - data_or_path: 'str | pathlib.Path | TextIO', - caption: 'str | None' = None, - **kwargs: 'str' -) → None +data_or_path: 'str | pathlib.Path | TextIO', +caption: 'str | None' = None, **kwargs: 'str' ``` -Initialize a Molecule object. +## Description +W&B class for 3D Molecular data. -**Args:** - - - `data_or_path`: Molecule can be initialized from a file name or an io object. - - `caption`: Caption associated with the molecule for display. +## Args: +- **data_or_path**: +- **caption**: +- **kwargs**: ---- +## Methods: + +### bind_to_run + +Bind this object to a particular Run. + +Calling this function is necessary so that we have somewhere specific to put the +file associated with this object, from which other Runs can refer to it. + +### captions + + + +### file_is_set + + + +### from_json + +Likely will need to override for any more complicated media objects. + +### from_rdkit + +Convert RDKit-supported file/object types to wandb.Molecule. + +### from_smiles + +Convert SMILES string to wandb.Molecule. + +### init_from_json + +Initialize a `WBValue` from a JSON blob based on the class that created it. + +Looks through all subclasses and tries to match the json obj with the class +which created it. It will then call that subclass' `from_json` method. +Importantly, this function will set the return object's `source_artifact` +attribute to the passed in source artifact. This is critical for artifact +bookkeeping. If you choose to create a wandb.Value via it's `from_json` method, +make sure to properly set this `artifact_source` to avoid data duplication. + +### is_bound + + + +### path_is_reference + + + +### to_data_array + +Convert the object to a list of primitives representing the underlying data. + +### type_mapping + +Return a map from `_log_type` to subclass. Used to lookup correct types for deserialization. + +### with_suffix + +Get the name with the appropriate suffix. + diff --git a/models/ref/python/data-types/object3d.mdx b/models/ref/python/data-types/object3d.mdx index 5abbf63aff..1cb48c606d 100644 --- a/models/ref/python/data-types/object3d.mdx +++ b/models/ref/python/data-types/object3d.mdx @@ -1,54 +1,99 @@ --- title: Object3D -namespace: python_sdk_data_type -python_object_type: class +kind: class +namespace: wandb.sdk.data_types.object_3d --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - - +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; + -## class `Object3D` -W&B class for 3D point clouds. -### method `Object3D.__init__` ```python -__init__( - data_or_path: 'np.ndarray | str | pathlib.Path | TextIO | dict', - caption: 'str | None' = None, - **kwargs: 'str | FileFormat3D | None' -) → None +data_or_path: 'np.ndarray | str | pathlib.Path | TextIO | dict', +caption: 'str | None' = None, **kwargs: 'str | FileFormat3D | None' ``` -Creates a W&B Object3D object. +## Description +W&B class for 3D point clouds. -**Args:** - - - `data_or_path`: Object3D can be initialized from a file or a numpy array. - - `caption`: Caption associated with the object for display. +## Args: +- **data_or_path**: +- **caption**: +- **kwargs**: -**Examples:** - The shape of the numpy array must be one of either -```text -[[x y z], ...] nx3 -[[x y z c], ...] nx4 where c is a category with supported range [1, 14] -[[x y z r g b], ...] nx6 where is rgb is color -``` +## Methods: +### bind_to_run ---- +Bind this object to a particular Run. + +Calling this function is necessary so that we have somewhere specific to put the +file associated with this object, from which other Runs can refer to it. + +### captions + + + +### file_is_set + + + +### from_file + +Initializes Object3D from a file or stream. + +### from_json + +Likely will need to override for any more complicated media objects. + +### from_numpy + +Initializes Object3D from a numpy array. + +### from_point_cloud + +Initializes Object3D from a python object. + +### init_from_json + +Initialize a `WBValue` from a JSON blob based on the class that created it. + +Looks through all subclasses and tries to match the json obj with the class +which created it. It will then call that subclass' `from_json` method. +Importantly, this function will set the return object's `source_artifact` +attribute to the passed in source artifact. This is critical for artifact +bookkeeping. If you choose to create a wandb.Value via it's `from_json` method, +make sure to properly set this `artifact_source` to avoid data duplication. + +### is_bound + + + +### path_is_reference + + + +### to_data_array + +Convert the object to a list of primitives representing the underlying data. + +### type_mapping + +Return a map from `_log_type` to subclass. Used to lookup correct types for deserialization. +### with_suffix +Get the name with the appropriate suffix. diff --git a/models/ref/python/data-types/plotly.mdx b/models/ref/python/data-types/plotly.mdx index 21ce43040c..2bae76e84b 100644 --- a/models/ref/python/data-types/plotly.mdx +++ b/models/ref/python/data-types/plotly.mdx @@ -1,35 +1,84 @@ --- title: Plotly -namespace: python_sdk_data_type -python_object_type: class +kind: class +namespace: wandb.sdk.data_types.plotly --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - - +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; + -## class `Plotly` -W&B class for Plotly plots. -### method `Plotly.__init__` ```python -__init__(val: 'plotly.Figure | matplotlib.artist.Artist') +(val: 'plotly.Figure | matplotlib.artist.Artist') ``` -Initialize a Plotly object. +## Description +W&B class for Plotly plots. -**Args:** - - - `val`: Matplotlib or Plotly figure. +## Args: +- **val**: ---- + + +## Methods: + +### bind_to_run + +Bind this object to a particular Run. + +Calling this function is necessary so that we have somewhere specific to put the +file associated with this object, from which other Runs can refer to it. + +### captions + + + +### file_is_set + + + +### from_json + +Likely will need to override for any more complicated media objects. + +### init_from_json + +Initialize a `WBValue` from a JSON blob based on the class that created it. + +Looks through all subclasses and tries to match the json obj with the class +which created it. It will then call that subclass' `from_json` method. +Importantly, this function will set the return object's `source_artifact` +attribute to the passed in source artifact. This is critical for artifact +bookkeeping. If you choose to create a wandb.Value via it's `from_json` method, +make sure to properly set this `artifact_source` to avoid data duplication. + +### is_bound + + + +### path_is_reference + + + +### to_data_array + +Convert the object to a list of primitives representing the underlying data. + +### type_mapping + +Return a map from `_log_type` to subclass. Used to lookup correct types for deserialization. + +### with_suffix + +Get the name with the appropriate suffix. + diff --git a/models/ref/python/data-types/table.mdx b/models/ref/python/data-types/table.mdx index b3bcbfa624..78194b51d7 100644 --- a/models/ref/python/data-types/table.mdx +++ b/models/ref/python/data-types/table.mdx @@ -1,180 +1,130 @@ --- title: Table -namespace: python_sdk_data_type -python_object_type: class +kind: class +namespace: wandb.sdk.data_types.table --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - - - - +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; -## class `Table` -The Table class used to display and analyze tabular data. -Unlike traditional spreadsheets, Tables support numerous types of data: scalar values, strings, numpy arrays, and most subclasses of `wandb.data_types.Media`. This means you can embed `Images`, `Video`, `Audio`, and other sorts of rich, annotated media directly in Tables, alongside other traditional scalar values. + -This class is the primary class used to generate W&B Tables https://docs.wandb.ai/models/tables -### method `Table.__init__` ```python -__init__( - columns=None, - data=None, - rows=None, - dataframe=None, - dtype=None, - optional=True, - allow_mixed_types=False, - log_mode: "Literal['IMMUTABLE', 'MUTABLE', 'INCREMENTAL'] | None" = 'IMMUTABLE' -) +(columns=None, data=None, rows=None, dataframe=None, dtype=None, optional=True, allow_mixed_types=False, +log_mode: "Literal['IMMUTABLE', 'MUTABLE', 'INCREMENTAL'] | None" = 'IMMUTABLE') ``` -Initializes a Table object. +## Description -The rows is available for legacy reasons and should not be used. The Table class uses data to mimic the Pandas API. +The Table class used to display and analyze tabular data. +Unlike traditional spreadsheets, Tables support numerous types of data: +scalar values, strings, numpy arrays, and most subclasses of `wandb.data_types.Media`. +This means you can embed `Images`, `Video`, `Audio`, and other sorts of rich, annotated media +directly in Tables, alongside other traditional scalar values. +This class is the primary class used to generate W&B Tables +https://docs.wandb.ai/models/tables -**Args:** - - - `columns`: (List[str]) Names of the columns in the table. Defaults to ["Input", "Output", "Expected"]. - - `data`: (List[List[any]]) 2D row-oriented array of values. - - `dataframe`: (pandas.DataFrame) DataFrame object used to create the table. When set, `data` and `columns` arguments are ignored. - - `rows`: (List[List[any]]) 2D row-oriented array of values. - - `optional`: (Union[bool,List[bool]]) Determines if `None` values are allowed. Default to True - - If a singular bool value, then the optionality is enforced for all columns specified at construction time - - If a list of bool values, then the optionality is applied to each column - should be the same length as `columns` applies to all columns. A list of bool values applies to each respective column. - - `allow_mixed_types`: (bool) Determines if columns are allowed to have mixed types (disables type validation). Defaults to False - - `log_mode`: Optional[str] Controls how the Table is logged when mutations occur. Options: - - "IMMUTABLE" (default): Table can only be logged once; subsequent logging attempts after the table has been mutated will be no-ops. - - "MUTABLE": Table can be re-logged after mutations, creating a new artifact version each time it's logged. - - "INCREMENTAL": Table data is logged incrementally, with each log creating a new artifact entry containing the new data since the last log. +## Args: +- **columns**: +- **data**: +- **rows**: +- **dataframe**: +- **dtype**: +- **optional**: +- **allow_mixed_types**: +- **log_mode**: ---- -### method `Table.add_column` -```python -add_column(name, data, optional=False) -``` -Adds a column of data to the table. +## Methods: +### add_column +Adds a column of data to the table. -**Args:** - - - `name`: (str) - the unique name of the column - - `data`: (list | np.array) - a column of homogeneous data - - `optional`: (bool) - if null-like values are permitted +### add_computed_columns ---- +Adds one or more computed columns based on existing data. -### method `Table.add_computed_columns` - -```python -add_computed_columns(fn) -``` - -Adds one or more computed columns based on existing data. +### add_data +Adds a new row of data to the table. +The maximum amount ofrows in a table is determined by +`wandb.Table.MAX_ARTIFACT_ROWS`. -**Args:** - - - `fn`: A function which accepts one or two parameters, ndx (int) and row (dict), which is expected to return a dict representing new columns for that row, keyed by the new column names. - - `ndx` is an integer representing the index of the row. Only included if `include_ndx` is set to `True`. - - `row` is a dictionary keyed by existing columns +The length of the data should match the length of the table column. ---- - -### method `Table.add_data` - -```python -add_data(*data) -``` +### add_row -Adds a new row of data to the table. +Deprecated. Use `Table.add_data` method instead. -The maximum amount ofrows in a table is determined by `wandb.Table.MAX_ARTIFACT_ROWS`. +### captions -The length of the data should match the length of the table column. ---- -### method `Table.add_row` +### cast -```python -add_row(*row) -``` +Casts a column to a specific data type. -Deprecated. Use `Table.add_data` method instead. +This can be one of the normal python classes, an internal W&B type, +or an example object, like an instance of wandb.Image or +wandb.Classes. ---- +### file_is_set -### method `Table.cast` -```python -cast(col_name, dtype, optional=False) -``` +### get_column -Casts a column to a specific data type. +Retrieves a column from the table and optionally converts it to a NumPy object. -This can be one of the normal python classes, an internal W&B type, or an example object, like an instance of wandb.Image or wandb.Classes. +### get_dataframe +Returns a `pandas.DataFrame` of the table. +### get_index -**Args:** - - - `col_name` (str): The name of the column to cast. - - `dtype` (class, wandb.wandb_sdk.interface._dtypes.Type, any): The target dtype. - - `optional` (bool): If the column should allow Nones. +Returns an array of row indexes for use in other tables to create links. ---- +### init_from_json +Initialize a `WBValue` from a JSON blob based on the class that created it. -### method `Table.get_column` +Looks through all subclasses and tries to match the json obj with the class +which created it. It will then call that subclass' `from_json` method. +Importantly, this function will set the return object's `source_artifact` +attribute to the passed in source artifact. This is critical for artifact +bookkeeping. If you choose to create a wandb.Value via it's `from_json` method, +make sure to properly set this `artifact_source` to avoid data duplication. -```python -get_column(name, convert_to=None) -``` +### is_bound -Retrieves a column from the table and optionally converts it to a NumPy object. +### path_is_reference -**Args:** - - - `name`: (str) - the name of the column - - `convert_to`: (str, optional) - - "numpy": will convert the underlying data to numpy object ---- -### method `Table.get_dataframe` +### to_data_array -```python -get_dataframe() -``` +Convert the object to a list of primitives representing the underlying data. -Returns a `pandas.DataFrame` of the table. +### type_mapping ---- +Return a map from `_log_type` to subclass. Used to lookup correct types for deserialization. -### method `Table.get_index` +### with_suffix -```python -get_index() -``` +Get the name with the appropriate suffix. -Returns an array of row indexes for use in other tables to create links. ---- diff --git a/models/ref/python/data-types/video.mdx b/models/ref/python/data-types/video.mdx index 7e6ccf5c2f..9d1279b576 100644 --- a/models/ref/python/data-types/video.mdx +++ b/models/ref/python/data-types/video.mdx @@ -1,61 +1,90 @@ --- title: Video -namespace: python_sdk_data_type -python_object_type: class +kind: class +namespace: wandb.sdk.data_types.video --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - - +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; + -## class `Video` -A class for logging videos to W&B. -### method `Video.__init__` ```python -__init__( - data_or_path: 'str | pathlib.Path | np.ndarray | TextIO | BytesIO', - caption: 'str | None' = None, - fps: 'int | None' = None, - format: "Literal['gif', 'mp4', 'webm', 'ogg'] | None" = None -) +(data_or_path: 'str | pathlib.Path | np.ndarray | TextIO | BytesIO', +caption: 'str | None' = None, +fps: 'int | None' = None, +format: "Literal['gif', 'mp4', 'webm', 'ogg'] | None" = None) ``` -Initialize a W&B Video object. +## Description +A class for logging videos to W&B. -**Args:** - - - `data_or_path`: Video can be initialized with a path to a file or an io object. Video can be initialized with a numpy tensor. The numpy tensor must be either 4 dimensional or 5 dimensional. The dimensions should be (number of frames, channel, height, width) or (batch, number of frames, channel, height, width) The format parameter must be specified with the format argument when initializing with a numpy array or io object. - - `caption`: Caption associated with the video for display. - - `fps`: The frame rate to use when encoding raw video frames. Default value is 4. This parameter has no effect when data_or_path is a string, or bytes. - - `format`: Format of video, necessary if initializing with a numpy array or io object. This parameter will be used to determine the format to use when encoding the video data. Accepted values are "gif", "mp4", "webm", or "ogg". If no value is provided, the default format will be "gif". +## Args: +- **data_or_path**: +- **caption**: +- **fps**: +- **format**: -**Examples:** - Log a numpy array as a video -```python -import numpy as np -import wandb -with wandb.init() as run: - # axes are (number of frames, channel, height, width) - frames = np.random.randint( - low=0, high=256, size=(10, 3, 100, 100), dtype=np.uint8 - ) - run.log({"video": wandb.Video(frames, format="mp4", fps=4)}) -``` +## Methods: +### bind_to_run +Bind this object to a particular Run. ---- +Calling this function is necessary so that we have somewhere specific to put the +file associated with this object, from which other Runs can refer to it. + +### captions + + + +### file_is_set + + + +### from_json + +Likely will need to override for any more complicated media objects. + +### init_from_json + +Initialize a `WBValue` from a JSON blob based on the class that created it. + +Looks through all subclasses and tries to match the json obj with the class +which created it. It will then call that subclass' `from_json` method. +Importantly, this function will set the return object's `source_artifact` +attribute to the passed in source artifact. This is critical for artifact +bookkeeping. If you choose to create a wandb.Value via it's `from_json` method, +make sure to properly set this `artifact_source` to avoid data duplication. + +### is_bound + + + +### path_is_reference + + + +### to_data_array + +Convert the object to a list of primitives representing the underlying data. + +### type_mapping + +Return a map from `_log_type` to subclass. Used to lookup correct types for deserialization. + +### with_suffix + +Get the name with the appropriate suffix. diff --git a/models/ref/python/experiments/artifact.mdx b/models/ref/python/experiments/artifact.mdx index 45179e8c43..1d518ec760 100644 --- a/models/ref/python/experiments/artifact.mdx +++ b/models/ref/python/experiments/artifact.mdx @@ -1,1126 +1,411 @@ --- title: Artifact -namespace: python_sdk_actions -python_object_type: class +kind: class +namespace: wandb.sdk.artifacts.artifact --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - - - - - - -## class `Artifact` -Flexible and lightweight building block for dataset and model versioning. - -Construct an empty W&B Artifact. Populate an artifacts contents with methods that begin with `add`. Once the artifact has all the desired files, you can call `run.log_artifact()` to log it. - -### method `Artifact.__init__` - -```python -__init__( - name: 'str', - type: 'str', - description: 'str | None' = None, - metadata: 'dict[str, Any] | None' = None, - incremental: 'bool' = False, - use_as: 'str | None' = None, - storage_region: 'str | None' = None -) → None -``` - -**Args:** - - - `name` (str): A human-readable name for the artifact. Use the name to identify a specific artifact in the W&B App UI or programmatically. You can interactively reference an artifact with the `use_artifact` Public API. A name can contain letters, numbers, underscores, hyphens, and dots. The name must be unique across a project. - - `type` (str): The artifact's type. Use the type of an artifact to both organize and differentiate artifacts. You can use any string that contains letters, numbers, underscores, hyphens, and dots. Common types include `dataset` or `model`. Include `model` within your type string if you want to link the artifact to the W&B Model Registry. Note that some types reserved for internal use and cannot be set by users. Such types include `job` and types that start with `wandb-`. - - `description (str | None) = None`: A description of the artifact. For Model or Dataset Artifacts, add documentation for your standardized team model or dataset card. View an artifact's description programmatically with the `Artifact.description` attribute or programmatically with the W&B App UI. W&B renders the description as markdown in the W&B App. - - `metadata (dict[str, Any] | None) = None`: Additional information about an artifact. Specify metadata as a dictionary of key-value pairs. You can specify no more than 100 total keys. - - `incremental`: Use `Artifact.new_draft()` method instead to modify an existing artifact. - - `use_as`: Deprecated. - - - -**Returns:** - An `Artifact` object. - - - - - - - ---- - -### property Artifact.aliases - -List of one or more semantically-friendly references or - -identifying "nicknames" assigned to an artifact version. - -Aliases are mutable references that you can programmatically reference. Change an artifact's alias with the W&B App UI or programmatically. See [Create new artifact versions](https://docs.wandb.ai/models/artifacts/create-a-new-artifact-version) for more information. - - - -**Returns:** - - `list[str]`: The aliases property value. ---- - -### property Artifact.collection - -The collection this artifact is retrieved from. - -A collection is an ordered group of artifact versions. If this artifact is retrieved from a collection that it is linked to, return that collection. Otherwise, return the collection that the artifact version originates from. - -The collection that an artifact originates from is known as the source sequence. - - - -**Returns:** - - `ArtifactCollection`: The collection property value. ---- - -### property Artifact.commit_hash - -The hash returned when this artifact was committed. - - - -**Returns:** - - `str`: The commit_hash property value. ---- - -### property Artifact.created_at - -Timestamp when the artifact was created. - - - -**Returns:** - - `str`: The created_at property value. ---- - -### property Artifact.description - -A description of the artifact. - - - -**Returns:** - - `str | None`: The description property value. ---- - -### property Artifact.digest - -The logical digest of the artifact. - -The digest is the checksum of the artifact's contents. If an artifact has the same digest as the current `latest` version, then `log_artifact` is a no-op. - - - -**Returns:** - - `str`: The digest property value. ---- - - -### property Artifact.entity - -The name of the entity that the artifact collection belongs to. - -If the artifact is a link, the entity will be the entity of the linked artifact. - - - -**Returns:** - - `str`: The entity property value. ---- - -### property Artifact.file_count - -The number of files (including references). - - - -**Returns:** - - `int`: The file_count property value. ---- - -### property Artifact.history_step - -The nearest step which logged history metrics for this artifact's source run. - - - -**Examples:** - ```python -run = artifact.logged_by() -if run and (artifact.history_step is not None): - history = run.sample_history( - min_step=artifact.history_step, - max_step=artifact.history_step + 1, - keys=["my_metric"], - ) -``` - - - -**Returns:** - - `int | None`: The history_step property value. ---- - -### property Artifact.id - -The artifact's ID. - - - -**Returns:** - - `str | None`: The id property value. ---- - - -### property Artifact.is_link - -Boolean flag indicating if the artifact is a link artifact. - -True: The artifact is a link artifact to a source artifact. False: The artifact is a source artifact. - - - -**Returns:** - - `bool`: The is_link property value. ---- - -### property Artifact.linked_artifacts - -Returns a list of all the linked artifacts of a source artifact. - -If this artifact is a link artifact (`artifact.is_link == True`), it will return an empty list. - -Limited to 500 results. - - - -**Returns:** - - `list[Artifact]`: The linked_artifacts property value. ---- - -### property Artifact.manifest - -The artifact's manifest. - -The manifest lists all of its contents, and can't be changed once the artifact has been logged. - - - -**Returns:** - - `ArtifactManifest`: The manifest property value. ---- - -### property Artifact.metadata - -User-defined artifact metadata. - -Structured data associated with the artifact. - - - -**Returns:** - - `dict`: The metadata property value. ---- - -### property Artifact.name - -The artifact name and version of the artifact. - -A string with the format `{collection}:{alias}`. If fetched before an artifact is logged/saved, the name won't contain the alias. If the artifact is a link, the name will be the name of the linked artifact. - - - -**Returns:** - - `str`: The name property value. ---- - -### property Artifact.project - -The name of the project that the artifact collection belongs to. - -If the artifact is a link, the project will be the project of the linked artifact. - - - -**Returns:** - - `str`: The project property value. ---- - -### property Artifact.qualified_name - -The entity/project/name of the artifact. - -If the artifact is a link, the qualified name will be the qualified name of the linked artifact path. - - - -**Returns:** - - `str`: The qualified_name property value. ---- - -### property Artifact.size - -The total size of the artifact in bytes. - -Includes any references tracked by this artifact. - - - -**Returns:** - - `int`: The size property value. ---- - -### property Artifact.source_artifact - -Returns the source artifact, which is the original logged artifact. - -If this artifact is a source artifact (`artifact.is_link == False`), it will return itself. - - - -**Returns:** - - `Artifact`: The source_artifact property value. ---- - -### property Artifact.source_collection - -The artifact's source collection. - -The source collection is the collection that the artifact was logged from. - - - -**Returns:** - - `ArtifactCollection`: The source_collection property value. ---- - -### property Artifact.source_entity - -The name of the entity of the source artifact. - - - -**Returns:** - - `str`: The source_entity property value. ---- - -### property Artifact.source_name - -The artifact name and version of the source artifact. - -A string with the format `{source_collection}:{alias}`. Before the artifact is saved, contains only the name since the version is not yet known. - - - -**Returns:** - - `str`: The source_name property value. ---- - -### property Artifact.source_project - -The name of the project of the source artifact. - - - -**Returns:** - - `str`: The source_project property value. ---- - -### property Artifact.source_qualified_name - -The source_entity/source_project/source_name of the source artifact. - - - -**Returns:** - - `str`: The source_qualified_name property value. ---- - -### property Artifact.source_version - -The source artifact's version. - -A string with the format `v{number}`. - - - -**Returns:** - - `str`: The source_version property value. ---- - -### property Artifact.state - -The status of the artifact. One of: "PENDING", "COMMITTED", or "DELETED". - - - -**Returns:** - - `str`: The state property value. ---- - -### property Artifact.tags - -List of one or more tags assigned to this artifact version. - - - -**Returns:** - - `list[str]`: The tags property value. ---- - -### property Artifact.ttl - -The time-to-live (TTL) policy of an artifact. - -Artifacts are deleted shortly after a TTL policy's duration passes. If set to `None`, the artifact deactivates TTL policies and will be not scheduled for deletion, even if there is a team default TTL. An artifact inherits a TTL policy from the team default if the team administrator defines a default TTL and there is no custom policy set on an artifact. - - - -**Raises:** - - - `ArtifactNotLoggedError`: Unable to fetch inherited TTL if the artifact has not been logged or saved. - - - -**Returns:** - - `timedelta | None`: The ttl property value. ---- - -### property Artifact.type -The artifact's type. Common types include `dataset` or `model`. - - - -**Returns:** - - `str`: The type property value. ---- - -### property Artifact.updated_at - -The time when the artifact was last updated. - - - -**Returns:** - - `str`: The updated_at property value. ---- - -### property Artifact.url - -Constructs the URL of the artifact. - - - -**Returns:** - - - `str`: The URL of the artifact. - - - -**Returns:** - - `str`: The url property value. ---- - -### property Artifact.use_as - -Deprecated. - - - -**Returns:** - - `str | None`: The use_as property value. ---- - -### property Artifact.version - -The artifact's version. - -A string with the format `v{number}`. If this is a link artifact, the version will be from the linked collection. - - - - - -**Returns:** - - `str`: The version property value. ---- - -### method `Artifact.add` - -```python -add( - obj: 'WBValue', - name: 'StrPath', - overwrite: 'bool' = False -) → ArtifactManifestEntry -``` - -Add wandb.WBValue `obj` to the artifact. - - - -**Args:** - - - `obj`: The object to add. Currently support one of Bokeh, JoinedTable, PartitionedTable, Table, Classes, ImageMask, BoundingBoxes2D, Audio, Image, Video, Html, Object3D - - `name`: The path within the artifact to add the object. - - `overwrite`: If True, overwrite existing objects with the same file path if applicable. - - - -**Returns:** - The added manifest entry - - - -**Raises:** - - - `ArtifactFinalizedError`: You cannot make changes to the current artifact version because it is finalized. Log a new artifact version instead. - ---- - -### method `Artifact.add_dir` - -```python -add_dir( - local_path: 'str', - name: 'str | None' = None, - skip_cache: 'bool | None' = False, - policy: "Literal['mutable', 'immutable'] | None" = 'mutable', - merge: 'bool' = False -) → None -``` - -Add a local directory to the artifact. - - - -**Args:** - - - `local_path`: The path of the local directory. - - `name`: The subdirectory name within an artifact. The name you specify appears in the W&B App UI nested by artifact's `type`. Defaults to the root of the artifact. - - `skip_cache`: If set to `True`, W&B will not copy/move files to the cache while uploading - - `policy`: By default, "mutable". - - mutable: Create a temporary copy of the file to prevent corruption during upload. - - immutable: Disable protection, rely on the user not to delete or change the file. - - `merge`: If `False` (default), throws ValueError if a file was already added in a previous add_dir call and its content has changed. If `True`, overwrites existing files with changed content. Always adds new files and never removes files. To replace an entire directory, pass a name when adding the directory using `add_dir(local_path, name=my_prefix)` and call `remove(my_prefix)` to remove the directory, then add it again. - - - -**Raises:** - - - `ArtifactFinalizedError`: You cannot make changes to the current artifact version because it is finalized. Log a new artifact version instead. - - `ValueError`: Policy must be "mutable" or "immutable" - ---- - -### method `Artifact.add_file` - -```python -add_file( - local_path: 'str', - name: 'str | None' = None, - is_tmp: 'bool | None' = False, - skip_cache: 'bool | None' = False, - policy: "Literal['mutable', 'immutable'] | None" = 'mutable', - overwrite: 'bool' = False -) → ArtifactManifestEntry -``` - -Add a local file to the artifact. - - - -**Args:** - - - `local_path`: The path to the file being added. - - `name`: The path within the artifact to use for the file being added. Defaults to the basename of the file. - - `is_tmp`: If true, then the file is renamed deterministically to avoid collisions. - - `skip_cache`: If `True`, do not copy files to the cache after uploading. - - `policy`: By default, set to "mutable". If set to "mutable", create a temporary copy of the file to prevent corruption during upload. If set to "immutable", disable protection and rely on the user not to delete or change the file. - - `overwrite`: If `True`, overwrite the file if it already exists. - - - -**Returns:** - The added manifest entry. - - - -**Raises:** - - - `ArtifactFinalizedError`: You cannot make changes to the current artifact version because it is finalized. Log a new artifact version instead. - - `ValueError`: Policy must be "mutable" or "immutable" - ---- - -### method `Artifact.add_reference` - -```python -add_reference( - uri: 'ArtifactManifestEntry | str', - name: 'StrPath | None' = None, - checksum: 'bool' = True, - max_objects: 'int | None' = None -) → Sequence[ArtifactManifestEntry] -``` - -Add a reference denoted by a URI to the artifact. - -Unlike files or directories that you add to an artifact, references are not uploaded to W&B. For more information, see [Track external files](https://docs.wandb.ai/models/artifacts/track-external-files). - -By default, the following schemes are supported: - - -- http(s): The size and digest of the file will be inferred by the `Content-Length` and the `ETag` response headers returned by the server. -- s3: The checksum and size are pulled from the object metadata. If bucket versioning is enabled, then the version ID is also tracked. -- gs: The checksum and size are pulled from the object metadata. If bucket versioning is enabled, then the version ID is also tracked. -- https, domain matching `*.blob.core.windows.net` -- Azure: The checksum and size are be pulled from the blob metadata. If storage account versioning is enabled, then the version ID is also tracked. -- file: The checksum and size are pulled from the file system. This scheme is useful if you have an NFS share or other externally mounted volume containing files you wish to track but not necessarily upload. - -For any other scheme, the digest is just a hash of the URI and the size is left blank. - - - -**Args:** - - - `uri`: The URI path of the reference to add. The URI path can be an object returned from `Artifact.get_entry` to store a reference to another artifact's entry. - - `name`: The path within the artifact to place the contents of this reference. - - `checksum`: Whether or not to checksum the resource(s) located at the reference URI. Checksumming is strongly recommended as it enables automatic integrity validation. Disabling checksumming will speed up artifact creation but reference directories will not iterated through so the objects in the directory will not be saved to the artifact. We recommend setting `checksum=False` when adding reference objects, in which case a new version will only be created if the reference URI changes. - - `max_objects`: The maximum number of objects to consider when adding a reference that points to directory or bucket store prefix. By default, the maximum number of objects allowed for Amazon S3, GCS, Azure, and local files is 10,000,000. Other URI schemas do not have a maximum. - - - -**Returns:** - The added manifest entries. - - - -**Raises:** - - - `ArtifactFinalizedError`: You cannot make changes to the current artifact version because it is finalized. Log a new artifact version instead. - ---- - -### method `Artifact.checkout` - -```python -checkout(root: 'str | None' = None) → str -``` - -Replace the specified root directory with the contents of the artifact. - -WARNING: This will delete all files in `root` that are not included in the artifact. - - - -**Args:** - - - `root`: The directory to replace with this artifact's files. - - - -**Returns:** - The path of the checked out contents. +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; + -**Raises:** - - - `ArtifactNotLoggedError`: If the artifact is not logged. ---- - -### method `Artifact.delete` ```python -delete(delete_aliases: 'bool' = False) → None +name: 'str', +type: 'str', +description: 'str | None' = None, +metadata: 'dict[str, Any] | None' = None, +incremental: 'bool' = False, +use_as: 'str | None' = None, +storage_region: 'str | None' = None ``` -Delete an artifact and its files. +## Description -If called on a linked artifact, only the link is deleted, and the source artifact is unaffected. +Flexible and lightweight building block for dataset and model versioning. -Use `Artifact.unlink()` instead of `Artifact.delete()` to remove a link between a source artifact and a collection. +Construct an empty W&B Artifact. Populate an artifacts contents with methods that +begin with `add`. Once the artifact has all the desired files, you can call +`run.log_artifact()` to log it. -**Args:** - - - `delete_aliases`: If set to `True`, delete all aliases associated with the artifact. If `False`, raise an exception if the artifact has existing aliases. This parameter is ignored if the artifact is retrieved from a collection it is linked to. +## Args: +- **name**: A human-readable name for the artifact. Use the name to identify a specific artifact in the W&B App UI or programmatically. You can interactively reference an artifact with the `use_artifact` Public API. A name can contain letters, numbers, underscores, hyphens, and dots. The name must be unique across a project. +- **type**: The artifact's type. Use the type of an artifact to both organize and differentiate artifacts. You can use any string that contains letters, numbers, underscores, hyphens, and dots. Common types include `dataset` or `model`. Include `model` within your type string if you want to link the artifact to the W&B Model Registry. Note that some types reserved for internal use and cannot be set by users. Such types include `job` and types that start with `wandb-`. +- **description**: A description of the artifact. For Model or Dataset Artifacts, add documentation for your standardized team model or dataset card. View an artifact's description programmatically with the `Artifact.description` attribute or programmatically with the W&B App UI. W&B renders the description as markdown in the W&B App. +- **metadata**: Additional information about an artifact. Specify metadata as a dictionary of key-value pairs. You can specify no more than 100 total keys. +- **incremental**: Use `Artifact.new_draft()` method instead to modify an existing artifact. +- **use_as**: Deprecated. +- **storage_region**: -**Raises:** - - - `ArtifactNotLoggedError`: If the artifact is not logged. +## Properties: ---- +### id -### method `Artifact.download` +The artifact's ID. -```python -download( - root: 'StrPath | None' = None, - allow_missing_references: 'bool' = False, - skip_cache: 'bool | None' = None, - path_prefix: 'StrPath | None' = None, - multipart: 'bool | None' = None -) → FilePathStr -``` +### entity -Download the contents of the artifact to the specified root directory. +The name of the entity that the artifact collection belongs to. -Existing files located within `root` are not modified. Explicitly delete `root` before you call `download` if you want the contents of `root` to exactly match the artifact. +If the artifact is a link, the entity will be the entity of the linked artifact. +### project +The name of the project that the artifact collection belongs to. -**Args:** - - - `root`: The directory W&B stores the artifact's files. - - `allow_missing_references`: If set to `True`, any invalid reference paths will be ignored while downloading referenced files. - - `skip_cache`: If set to `True`, the artifact cache will be skipped when downloading and W&B will download each file into the default root or specified download directory. - - `path_prefix`: If specified, only files with a path that starts with the given prefix will be downloaded. Uses unix format (forward slashes). - - `multipart`: If set to `None` (default), the artifact will be downloaded in parallel using multipart download if individual file size is greater than 2GB. If set to `True` or `False`, the artifact will be downloaded in parallel or serially regardless of the file size. +If the artifact is a link, the project will be the project of the linked artifact. +### name +The artifact name and version of the artifact. -**Returns:** - The path to the downloaded contents. +A string with the format `{collection}:{alias}`. If fetched before an artifact is +logged/saved, the name won't contain the alias. +If the artifact is a link, the name will be the name of the linked artifact. +### qualified_name +The entity/project/name of the artifact. -**Raises:** - - - `ArtifactNotLoggedError`: If the artifact is not logged. +If the artifact is a link, the qualified name will be the qualified name of the +linked artifact path. ---- +### version -### method `Artifact.file` +The artifact's version. -```python -file(root: 'str | None' = None) → StrPath -``` +A string with the format `v{number}`. +If this is a link artifact, the version will be from the linked collection. -Download a single file artifact to the directory you specify with `root`. +### collection +The collection this artifact is retrieved from. +A collection is an ordered group of artifact versions. +If this artifact is retrieved from a collection that it is linked to, +return that collection. Otherwise, return the collection +that the artifact version originates from. -**Args:** - - - `root`: The root directory to store the file. Defaults to `./artifacts/self.name/`. +The collection that an artifact originates from is known as +the source sequence. +### source_entity +The name of the entity of the source artifact. -**Returns:** - The full path of the downloaded file. +### source_project +The name of the project of the source artifact. +### source_name -**Raises:** - - - `ArtifactNotLoggedError`: If the artifact is not logged. - - `ValueError`: If the artifact contains more than one file. +The artifact name and version of the source artifact. ---- +A string with the format `{source_collection}:{alias}`. Before the artifact +is saved, contains only the name since the version is not yet known. -### method `Artifact.files` +### source_qualified_name -```python -files( - names: 'list[str] | None' = None, - per_page: 'int' = 50, - start: 'str | None' = None -) → ArtifactFiles -``` +The source_entity/source_project/source_name of the source artifact. -Iterate over all files stored in this artifact. +### source_version +The source artifact's version. +A string with the format `v{number}`. -**Args:** - - - `names`: The filename paths relative to the root of the artifact you wish to list. - - `per_page`: The number of files to return per request. - - `start`: Pagination cursor for resuming a past query, captured from a previous paginator's `.cursor` attribute. +### source_collection +The artifact's source collection. +The source collection is the collection that the artifact was logged from. -**Returns:** - An iterator containing `File` objects. +### is_link +Boolean flag indicating if the artifact is a link artifact. +True: The artifact is a link artifact to a source artifact. +False: The artifact is a source artifact. -**Raises:** - - - `ArtifactNotLoggedError`: If the artifact is not logged. +### linked_artifacts ---- +Returns a list of all the linked artifacts of a source artifact. -### method `Artifact.finalize` +If this artifact is a link artifact (`artifact.is_link == True`), +it will return an empty list. -```python -finalize() → None -``` +Limited to 500 results. -Finalize the artifact version. +### source_artifact -You cannot modify an artifact version once it is finalized because the artifact is logged as a specific artifact version. Create a new artifact version to log more data to an artifact. An artifact is automatically finalized when you log the artifact with `log_artifact`. +Returns the source artifact, which is the original logged artifact. ---- +If this artifact is a source artifact (`artifact.is_link == False`), +it will return itself. -### method `Artifact.get` +### type -```python -get(name: 'str') → WBValue | None -``` +The artifact's type. Common types include `dataset` or `model`. -Get the WBValue object located at the artifact relative `name`. +### url +Constructs the URL of the artifact. +### description -**Args:** - - - `name`: The artifact relative name to retrieve. +A description of the artifact. +### metadata +User-defined artifact metadata. -**Returns:** - W&B object that can be logged with `run.log()` and visualized in the W&B UI. +Structured data associated with the artifact. +### ttl +The time-to-live (TTL) policy of an artifact. -**Raises:** - - - `ArtifactNotLoggedError`: if the artifact isn't logged or the run is offline. +Artifacts are deleted shortly after a TTL policy's duration passes. +If set to `None`, the artifact deactivates TTL policies and will be not +scheduled for deletion, even if there is a team default TTL. +An artifact inherits a TTL policy from +the team default if the team administrator defines a default +TTL and there is no custom policy set on an artifact. ---- +Raises: + ArtifactNotLoggedError: Unable to fetch inherited TTL if the + artifact has not been logged or saved. -### method `Artifact.get_added_local_path_name` +### aliases -```python -get_added_local_path_name(local_path: 'str') → str | None -``` +List of one or more semantically-friendly references or -Get the artifact relative name of a file added by a local filesystem path. +identifying "nicknames" assigned to an artifact version. +Aliases are mutable references that you can programmatically reference. +Change an artifact's alias with the W&B App UI or programmatically. +See [Create new artifact versions](https://docs.wandb.ai/models/artifacts/create-a-new-artifact-version) +for more information. +### tags -**Args:** - - - `local_path`: The local path to resolve into an artifact relative name. +List of one or more tags assigned to this artifact version. +### use_as +Deprecated. -**Returns:** - The artifact relative name. +### state ---- +The status of the artifact. One of: "PENDING", "COMMITTED", or "DELETED". -### method `Artifact.get_entry` +### manifest -```python -get_entry(name: 'StrPath') → ArtifactManifestEntry -``` +The artifact's manifest. -Get the entry with the given name. +The manifest lists all of its contents, and can't be changed once the artifact +has been logged. +### digest +The logical digest of the artifact. -**Args:** - - - `name`: The artifact relative name to get +The digest is the checksum of the artifact's contents. If an artifact has the +same digest as the current `latest` version, then `log_artifact` is a no-op. +### size +The total size of the artifact in bytes. -**Returns:** - A `W&B` object. +Includes any references tracked by this artifact. +### commit_hash +The hash returned when this artifact was committed. -**Raises:** - - - `ArtifactNotLoggedError`: if the artifact isn't logged or the run is offline. - - `KeyError`: if the artifact doesn't contain an entry with the given name. +### file_count ---- +The number of files (including references). -### method `Artifact.get_path` +### created_at -```python -get_path(name: 'StrPath') → ArtifactManifestEntry -``` +Timestamp when the artifact was created. -Deprecated. Use `get_entry(name)`. +### updated_at ---- +The time when the artifact was last updated. -### method `Artifact.is_draft` +### history_step -```python -is_draft() → bool -``` +The nearest step which logged history metrics for this artifact's source run. -Check if artifact is not saved. +## Methods: -**Returns:** - Boolean. `False` if artifact is saved. `True` if artifact is not saved. +### add ---- +Add wandb.WBValue `obj` to the artifact. -### method `Artifact.json_encode` +### add_dir -```python -json_encode() → dict[str, Any] -``` +Add a local directory to the artifact. -Returns the artifact encoded to the JSON format. +### add_file +Add a local file to the artifact. +### add_reference -**Returns:** - A `dict` with `string` keys representing attributes of the artifact. +Add a reference denoted by a URI to the artifact. ---- +Unlike files or directories that you add to an artifact, references are not +uploaded to W&B. For more information, +see [Track external files](https://docs.wandb.ai/models/artifacts/track-external-files). -### method `Artifact.link` +By default, the following schemes are supported: -```python -link(target_path: 'str', aliases: 'Iterable[str] | None' = None) → Artifact -``` +- http(s): The size and digest of the file will be inferred by the + `Content-Length` and the `ETag` response headers returned by the server. +- s3: The checksum and size are pulled from the object metadata. + If bucket versioning is enabled, then the version ID is also tracked. +- gs: The checksum and size are pulled from the object metadata. If bucket + versioning is enabled, then the version ID is also tracked. +- https, domain matching `*.blob.core.windows.net` +- Azure: The checksum and size are be pulled from the blob metadata. + If storage account versioning is enabled, then the version ID is + also tracked. +- file: The checksum and size are pulled from the file system. This scheme + is useful if you have an NFS share or other externally mounted volume + containing files you wish to track but not necessarily upload. -Link this artifact to a collection. +For any other scheme, the digest is just a hash of the URI and the size is left +blank. +### checkout +Replace the specified root directory with the contents of the artifact. -**Args:** - - - `target_path`: The path of the collection. Path consists of the prefix "wandb-registry-" along with the registry name and the collection name `wandb-registry-{REGISTRY_NAME}/{COLLECTION_NAME}`. - - `aliases`: Add one or more aliases to the linked artifact. The "latest" alias is automatically applied to the most recent artifact you link. +WARNING: This will delete all files in `root` that are not included in the +artifact. +### delete +Delete an artifact and its files. -**Raises:** - - - `ArtifactNotLoggedError`: If the artifact is not logged. +If called on a linked artifact, only the link is deleted, and the +source artifact is unaffected. +Use `Artifact.unlink()` instead of `Artifact.delete()` to remove a +link between a source artifact and a collection. +### download -**Returns:** - The linked artifact. +Download the contents of the artifact to the specified root directory. ---- +Existing files located within `root` are not modified. Explicitly delete `root` +before you call `download` if you want the contents of `root` to exactly match +the artifact. -### method `Artifact.logged_by` +### file -```python -logged_by() → Run | None -``` +Download a single file artifact to the directory you specify with `root`. -Get the W&B run that originally logged the artifact. +### files +Iterate over all files stored in this artifact. +### finalize -**Returns:** - The name of the W&B run that originally logged the artifact. +Finalize the artifact version. +You cannot modify an artifact version once it is finalized because the artifact +is logged as a specific artifact version. Create a new artifact version +to log more data to an artifact. An artifact is automatically finalized +when you log the artifact with `log_artifact`. +### get -**Raises:** - - - `ArtifactNotLoggedError`: If the artifact is not logged. +Get the WBValue object located at the artifact relative `name`. ---- +### get_added_local_path_name -### method `Artifact.new_draft` +Get the artifact relative name of a file added by a local filesystem path. -```python -new_draft() → Artifact -``` +### get_entry -Create a new draft artifact with the same content as this committed artifact. +Get the entry with the given name. -Modifying an existing artifact creates a new artifact version known as an "incremental artifact". The artifact returned can be extended or modified and logged as a new version. +### get_path +Deprecated. Use `get_entry(name)`. +### is_draft -**Returns:** - An `Artifact` object. +Check if artifact is not saved. +### json_encode +Returns the artifact encoded to the JSON format. -**Raises:** - - - `ArtifactNotLoggedError`: If the artifact is not logged. - ---- +### link -### method `Artifact.new_file` - -```python -new_file( - name: 'str', - mode: 'str' = 'x', - encoding: 'str | None' = None -) → Iterator[IO] -``` +Link this artifact to a collection. -Open a new temporary file and add it to the artifact. +### logged_by +Get the W&B run that originally logged the artifact. +### new_draft -**Args:** - - - `name`: The name of the new file to add to the artifact. - - `mode`: The file access mode to use to open the new file. - - `encoding`: The encoding used to open the new file. +Create a new draft artifact with the same content as this committed artifact. +Modifying an existing artifact creates a new artifact version known +as an "incremental artifact". The artifact returned can be extended or +modified and logged as a new version. +### new_file -**Returns:** - A new file object that can be written to. Upon closing, the file is automatically added to the artifact. +Open a new temporary file and add it to the artifact. +### remove +Remove an item from the artifact. -**Raises:** - - - `ArtifactFinalizedError`: You cannot make changes to the current artifact version because it is finalized. Log a new artifact version instead. - ---- - -### method `Artifact.remove` - -```python -remove(item: 'StrPath | ArtifactManifestEntry') → None -``` +### save -Remove an item from the artifact. +Persist any changes made to the artifact. +If currently in a run, that run will log this artifact. If not currently in a +run, a run of type "auto" is created to track this artifact. +### unlink -**Args:** - - - `item`: The item to remove. Can be a specific manifest entry or the name of an artifact-relative path. If the item matches a directory all items in that directory will be removed. +Unlink this artifact if it is a linked member of an artifact collection. +Raises: + ArtifactNotLoggedError: If the artifact is not logged. + ValueError: If the artifact is not linked to any collection. +### used_by -**Raises:** - - - `ArtifactFinalizedError`: You cannot make changes to the current artifact version because it is finalized. Log a new artifact version instead. - - `FileNotFoundError`: If the item isn't found in the artifact. - ---- - -### method `Artifact.save` - -```python -save( - project: 'str | None' = None, - settings: 'wandb.Settings | None' = None -) → None -``` - -Persist any changes made to the artifact. - -If currently in a run, that run will log this artifact. If not currently in a run, a run of type "auto" is created to track this artifact. - - - -**Args:** - - - `project`: A project to use for the artifact in the case that a run is not already in context. - - `settings`: A settings object to use when initializing an automatic run. Most commonly used in testing harness. - ---- - -### method `Artifact.unlink` - -```python -unlink() → None -``` - -Unlink this artifact if it is a linked member of an artifact collection. - - - -**Raises:** - - - `ArtifactNotLoggedError`: If the artifact is not logged. - - `ValueError`: If the artifact is not linked to any collection. - ---- - -### method `Artifact.used_by` - -```python -used_by() → list[Run] -``` - -Get a list of the runs that have used this artifact and its linked artifacts. - - - -**Returns:** - A list of `Run` objects. - - - -**Raises:** - - - `ArtifactNotLoggedError`: If the artifact is not logged. - ---- - -### method `Artifact.verify` - -```python -verify(root: 'str | None' = None) → None -``` - -Verify that the contents of an artifact match the manifest. - -All files in the directory are checksummed and the checksums are then cross-referenced against the artifact's manifest. References are not verified. - - - -**Args:** - - - `root`: The directory to verify. If None artifact will be downloaded to './artifacts/self.name/'. - - - -**Raises:** - - - `ArtifactNotLoggedError`: If the artifact is not logged. - - `ValueError`: If the verification fails. - ---- - -### method `Artifact.wait` - -```python -wait(timeout: 'int | None' = None) → Artifact -``` +Get a list of the runs that have used this artifact and its linked artifacts. -If needed, wait for this artifact to finish logging. +### verify +Verify that the contents of an artifact match the manifest. +All files in the directory are checksummed and the checksums are then +cross-referenced against the artifact's manifest. References are not verified. -**Args:** - - - `timeout`: The time, in seconds, to wait. +### wait +If needed, wait for this artifact to finish logging. -**Returns:** - An `Artifact` object. diff --git a/models/ref/python/experiments/run.mdx b/models/ref/python/experiments/run.mdx index 48efc28070..eb8617375e 100644 --- a/models/ref/python/experiments/run.mdx +++ b/models/ref/python/experiments/run.mdx @@ -1,37 +1,56 @@ --- title: Run -namespace: python_sdk_actions -python_object_type: class +kind: class +namespace: wandb.sdk.wandb_run --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; + -## class `Run` -A unit of computation logged by W&B. Typically, this is an ML experiment. -Call [`wandb.init()`](https://docs.wandb.ai/models/ref/python/functions/init) to create a new run. `wandb.init()` starts a new run and returns a `wandb.Run` object. Each run is associated with a unique ID (run ID). W&B recommends using a context (`with` statement) manager to automatically finish the run. +```python +settings: 'Settings', +config: 'dict[str, Any] | None' = None, +sweep_config: 'dict[str, Any] | None' = None, +launch_config: 'dict[str, Any] | None' = None +``` -For distributed training experiments, you can either track each process separately using one run per process or track all processes to a single run. See [Log distributed training experiments](https://docs.wandb.ai/models/track/log/distributed-training) for more information. +## Description -You can log data to a run with `wandb.Run.log()`. Anything you log using `wandb.Run.log()` is sent to that run. See [Create an experiment](https://docs.wandb.ai/models/track/create-an-experiment) or [`wandb.init`](https://docs.wandb.ai/models/ref/python/functions/init) API reference page or more information. +A unit of computation logged by W&B. Typically, this is an ML experiment. -There is a another `Run` object in the [`wandb.apis.public`](https://docs.wandb.ai/models/ref/python/public-api/api) namespace. Use this object is to interact with runs that have already been created. +Call [`wandb.init()`](https://docs.wandb.ai/models/ref/python/functions/init) to create a +new run. `wandb.init()` starts a new run and returns a `wandb.Run` object. +Each run is associated with a unique ID (run ID). W&B recommends using +a context (`with` statement) manager to automatically finish the run. +For distributed training experiments, you can either track each process +separately using one run per process or track all processes to a single run. +See [Log distributed training experiments](https://docs.wandb.ai/models/track/log/distributed-training) +for more information. +You can log data to a run with `wandb.Run.log()`. Anything you log using +`wandb.Run.log()` is sent to that run. See +[Create an experiment](https://docs.wandb.ai/models/track/create-an-experiment) or +[`wandb.init`](https://docs.wandb.ai/models/ref/python/functions/init) API reference page +or more information. -**Attributes:** - - - `summary`: (Summary) A summary of the run, which is a dictionary-like object. For more information, see - - `[Log summary metrics](https`: //docs.wandb.ai/models/track/log/log-summary). +There is a another `Run` object in the +[`wandb.apis.public`](https://docs.wandb.ai/models/ref/python/public-api/api) +namespace. Use this object is to interact with runs that have already been +created. +Attributes: + summary: (Summary) A summary of the run, which is a dictionary-like + object. For more information, see + [Log summary metrics](https://docs.wandb.ai/models/track/log/log-summary). +## Examples: -**Examples:** - Create a run with `wandb.init()`: +Create a run with `wandb.init()`: ```python import wandb @@ -40,1149 +59,380 @@ import wandb # Use context manager (`with` statement) to automatically finish the run with wandb.init(entity="entity", project="project") as run: run.log({"accuracy": acc, "loss": loss}) -``` - - -### property Run.config - -Config object associated with this run. - - - -**Returns:** - - `wandb_config.Config`: The config property value. ---- - -### property Run.config_static - -Static config object associated with this run. - - - -**Returns:** - - `wandb_config.ConfigStatic`: The config_static property value. ---- - -### property Run.dir - -The directory where files associated with the run are saved. - - - -**Returns:** - - `str`: The dir property value. ---- - -### property Run.disabled - -True if the run is disabled, False otherwise. - - - -**Returns:** - - `bool`: The disabled property value. ---- - -### property Run.entity - -The name of the W&B entity associated with the run. - -Entity can be a username or the name of a team or organization. - - - -**Returns:** - - `str`: The entity property value. ---- - -### property Run.group - -Returns the name of the group associated with this run. - -Grouping runs together allows related experiments to be organized and visualized collectively in the W&B UI. This is especially useful for scenarios such as distributed training or cross-validation, where multiple runs should be viewed and managed as a unified experiment. - -In shared mode, where all processes share the same run object, setting a group is usually unnecessary, since there is only one run and no grouping is required. - - - -**Returns:** - - `str`: The group property value. ---- - -### property Run.id - -Identifier for this run. - - - -**Returns:** - - `str`: The id property value. ---- - -### property Run.job_type - -Name of the job type associated with the run. - -View a run's job type in the run's Overview page in the W&B App. - -You can use this to categorize runs by their job type, such as "training", "evaluation", or "inference". This is useful for organizing and filtering runs in the W&B UI, especially when you have multiple runs with different job types in the same project. For more information, see [Organize runs](https://docs.wandb.ai/models/runs#organize-runs). - - - -**Returns:** - - `str`: The job_type property value. ---- - -### property Run.name - -Display name of the run. - -Display names are not guaranteed to be unique and may be descriptive. By default, they are randomly generated. - - - -**Returns:** - - `str | None`: The name property value. ---- - -### property Run.notes - -Notes associated with the run, if there are any. - -Notes can be a multiline string and can also use markdown and latex equations inside `$$`, like `$x + 3$`. - - - -**Returns:** - - `str | None`: The notes property value. ---- - -### property Run.offline - -True if the run is offline, False otherwise. - - - -**Returns:** - - `bool`: The offline property value. ---- - -### property Run.path - -Path to the run. - -Run paths include entity, project, and run ID, in the format `entity/project/run_id`. - - - -**Returns:** - - `str`: The path property value. ---- - -### property Run.project - -Name of the W&B project associated with the run. - - - -**Returns:** - - `str`: The project property value. ---- - -### property Run.project_url - -URL of the W&B project associated with the run, if there is one. - -Offline runs do not have a project URL. - - - -**Returns:** - - `str | None`: The project_url property value. ---- - -### property Run.resumed - -True if the run was resumed, False otherwise. - - - -**Returns:** - - `bool`: The resumed property value. ---- - -### property Run.settings - -A frozen copy of run's Settings object. - - - -**Returns:** - - `Settings`: The settings property value. ---- - -### property Run.start_time - -Unix timestamp (in seconds) of when the run started. - - - -**Returns:** - - `float`: The start_time property value. ---- - - - -### property Run.sweep_id - -Identifier for the sweep associated with the run, if there is one. - - - -**Returns:** - - `str | None`: The sweep_id property value. ---- - -### property Run.sweep_url - -URL of the sweep associated with the run, if there is one. - -Offline runs do not have a sweep URL. - - - -**Returns:** - - `str | None`: The sweep_url property value. ---- - -### property Run.tags - -Tags associated with the run, if there are any. - - - -**Returns:** - - `tuple | None`: The tags property value. ---- - -### property Run.url - -The url for the W&B run, if there is one. - -Offline runs will not have a url. - - - - - -**Returns:** - - `str | None`: The url property value. ---- - -### method `Run.alert` - -```python -alert( - title: 'str', - text: 'str', - level: 'str | AlertLevel | None' = None, - wait_duration: 'int | float | timedelta | None' = None -) → None ``` -Create an alert with the given title and text. +## Args: +- **settings**: +- **config**: +- **sweep_config**: +- **launch_config**: -**Args:** - - - `title`: The title of the alert, must be less than 64 characters long. - - `text`: The text body of the alert. - - `level`: The alert level to use, either: `INFO`, `WARN`, or `ERROR`. - - `wait_duration`: The time to wait (in seconds) before sending another alert with this title. +## Properties: ---- +### settings -### method `Run.define_metric` +A frozen copy of run's Settings object. -```python -define_metric( - name: 'str', - step_metric: 'str | wandb_metric.Metric | None' = None, - step_sync: 'bool | None' = None, - hidden: 'bool | None' = None, - summary: 'str | None' = None, - goal: 'str | None' = None, - overwrite: 'bool | None' = None -) → wandb_metric.Metric -``` +### dir -Customize metrics logged with `wandb.Run.log()`. +The directory where files associated with the run are saved. +### config +Config object associated with this run. -**Args:** - - - `name`: The name of the metric to customize. - - `step_metric`: The name of another metric to serve as the X-axis for this metric in automatically generated charts. - - `step_sync`: Automatically insert the last value of step_metric into `wandb.Run.log()` if it is not provided explicitly. Defaults to True if step_metric is specified. - - `hidden`: Hide this metric from automatic plots. - - `summary`: Specify aggregate metrics added to summary. Supported aggregations include "min", "max", "mean", "last", "first", "best", "copy" and "none". "none" prevents a summary from being generated. "best" is used together with the goal parameter, "best" is deprecated and should not be used, use "min" or "max" instead. "copy" is deprecated and should not be used. - - `goal`: Specify how to interpret the "best" summary type. Supported options are "minimize" and "maximize". "goal" is deprecated and should not be used, use "min" or "max" instead. - - `overwrite`: If false, then this call is merged with previous `define_metric` calls for the same metric by using their values for any unspecified parameters. If true, then unspecified parameters overwrite values specified by previous calls. +### config_static +Static config object associated with this run. +### name -**Returns:** - An object that represents this call but can otherwise be discarded. +Display name of the run. ---- +Display names are not guaranteed to be unique and may be descriptive. +By default, they are randomly generated. -### method `Run.display` +### notes -```python -display(height: 'int' = 420, hidden: 'bool' = False) → bool -``` +Notes associated with the run, if there are any. -Display this run in Jupyter. +Notes can be a multiline string and can also use markdown and latex +equations inside `$$`, like `$x + 3$`. ---- +### tags -### method `Run.finish` +Tags associated with the run, if there are any. -```python -finish(exit_code: 'int | None' = None, quiet: 'bool | None' = None) → None -``` +### id -Finish a run and upload any remaining data. +Identifier for this run. -Marks the completion of a W&B run and ensures all data is synced to the server. The run's final state is determined by its exit conditions and sync status. +### sweep_id -Run States: -- Running: Active run that is logging data and/or sending heartbeats. -- Crashed: Run that stopped sending heartbeats unexpectedly. -- Finished: Run completed successfully (`exit_code=0`) with all data synced. -- Failed: Run completed with errors (`exit_code!=0`). -- Killed: Run was forcibly stopped before it could finish. +Identifier for the sweep associated with the run, if there is one. +### path +Path to the run. -**Args:** - - - `exit_code`: Integer indicating the run's exit status. Use 0 for success, any other value marks the run as failed. - - `quiet`: Deprecated. Configure logging verbosity using `wandb.Settings(quiet=...)`. +Run paths include entity, project, and run ID, in the format +`entity/project/run_id`. ---- +### start_time -### method `Run.finish_artifact` +Unix timestamp (in seconds) of when the run started. -```python -finish_artifact( - artifact_or_path: 'Artifact | str', - name: 'str | None' = None, - type: 'str | None' = None, - aliases: 'list[str] | None' = None, - distributed_id: 'str | None' = None -) → Artifact -``` +### resumed -Finishes a non-finalized artifact as output of a run. +True if the run was resumed, False otherwise. -Subsequent "upserts" with the same distributed ID will result in a new version. +### offline +True if the run is offline, False otherwise. +### disabled -**Args:** - - - `artifact_or_path`: A path to the contents of this artifact, can be in the following forms: - - `/local/directory` - - `/local/directory/file.txt` - - `s3://bucket/path` You can also pass an Artifact object created by calling `wandb.Artifact`. - - `name`: An artifact name. May be prefixed with entity/project. Valid names can be in the following forms: - - name:version - - name:alias - - digest This will default to the basename of the path prepended with the current run id if not specified. - - `type`: The type of artifact to log, examples include `dataset`, `model` - - `aliases`: Aliases to apply to this artifact, defaults to `["latest"]` - - `distributed_id`: Unique string that all distributed jobs share. If None, defaults to the run's group name. +True if the run is disabled, False otherwise. +### group +Returns the name of the group associated with this run. -**Returns:** - An `Artifact` object. +Grouping runs together allows related experiments to be organized and +visualized collectively in the W&B UI. This is especially useful for +scenarios such as distributed training or cross-validation, where +multiple runs should be viewed and managed as a unified experiment. ---- +In shared mode, where all processes share the same run object, +setting a group is usually unnecessary, since there is only one +run and no grouping is required. +### job_type +Name of the job type associated with the run. +View a run's job type in the run's Overview page in the W&B App. -### method `Run.link_artifact` +You can use this to categorize runs by their job type, such as +"training", "evaluation", or "inference". This is useful for organizing +and filtering runs in the W&B UI, especially when you have multiple +runs with different job types in the same project. For more +information, see [Organize runs](https://docs.wandb.ai/models/runs#organize-runs). -```python -link_artifact( - artifact: 'Artifact', - target_path: 'str', - aliases: 'list[str] | None' = None -) → Artifact -``` +### project -Link the artifact to a collection. +Name of the W&B project associated with the run. -The term “link” refers to pointers that connect where W&B stores the artifact and where the artifact is accessible in the registry. W&B does not duplicate artifacts when you link an artifact to a collection. +### project_url -View linked artifacts in the Registry UI for the specified collection. +URL of the W&B project associated with the run, if there is one. +Offline runs do not have a project URL. +### sweep_url -**Args:** - - - `artifact`: The artifact object to link to the collection. - - `target_path`: The path of the collection. Path consists of the prefix "wandb-registry-" along with the registry name and the collection name `wandb-registry-{REGISTRY_NAME}/{COLLECTION_NAME}`. - - `aliases`: Add one or more aliases to the linked artifact. The "latest" alias is automatically applied to the most recent artifact you link. +URL of the sweep associated with the run, if there is one. +Offline runs do not have a sweep URL. +### url -**Returns:** - The linked artifact. +The url for the W&B run, if there is one. ---- +Offline runs will not have a url. -### method `Run.link_model` +### entity -```python -link_model( - path: 'StrPath', - registered_model_name: 'str', - name: 'str | None' = None, - aliases: 'list[str] | None' = None -) → Artifact | None -``` +The name of the W&B entity associated with the run. -Log a model artifact version and link it to a registered model in the model registry. +Entity can be a username or the name of a team or organization. -Linked model versions are visible in the UI for the specified registered model. -This method will: -- Check if 'name' model artifact has been logged. If so, use the artifact version that matches the files located at 'path' or log a new version. Otherwise log files under 'path' as a new model artifact, 'name' of type 'model'. -- Check if registered model with name 'registered_model_name' exists in the 'model-registry' project. If not, create a new registered model with name 'registered_model_name'. -- Link version of model artifact 'name' to registered model, 'registered_model_name'. -- Attach aliases from 'aliases' list to the newly linked model artifact version. +## Methods: +### alert -**Args:** - - - `path`: (str) A path to the contents of this model, can be in the following forms: - - `/local/directory` - - `/local/directory/file.txt` - - `s3://bucket/path` - - `registered_model_name`: The name of the registered model that the model is to be linked to. A registered model is a collection of model versions linked to the model registry, typically representing a team's specific ML Task. The entity that this registered model belongs to will be derived from the run. - - `name`: The name of the model artifact that files in 'path' will be logged to. This will default to the basename of the path prepended with the current run id if not specified. - - `aliases`: Aliases that will only be applied on this linked artifact inside the registered model. The alias "latest" will always be applied to the latest version of an artifact that is linked. +Create an alert with the given title and text. +### define_metric +Customize metrics logged with `wandb.Run.log()`. -**Raises:** - - - `AssertionError`: If registered_model_name is a path or if model artifact 'name' is of a type that does not contain the substring 'model'. - - `ValueError`: If name has invalid special characters. +### display +Display this run in Jupyter. +### finish -**Returns:** - The linked artifact if linking was successful, otherwise `None`. +Finish a run and upload any remaining data. ---- +Marks the completion of a W&B run and ensures all data is synced to the server. +The run's final state is determined by its exit conditions and sync status. -### method `Run.log` +Run States: +- Running: Active run that is logging data and/or sending heartbeats. +- Crashed: Run that stopped sending heartbeats unexpectedly. +- Finished: Run completed successfully (`exit_code=0`) with all data synced. +- Failed: Run completed with errors (`exit_code!=0`). +- Killed: Run was forcibly stopped before it could finish. -```python -log( - data: 'dict[str, Any]', - step: 'int | None' = None, - commit: 'bool | None' = None -) → None -``` +### finish_artifact -Upload run data. +Finishes a non-finalized artifact as output of a run. -Use `log` to log data from runs, such as scalars, images, video, histograms, plots, and tables. See [Log objects and media](https://docs.wandb.ai/models/track/log) for code snippets, best practices, and more. +Subsequent "upserts" with the same distributed ID will result in a new version. -Basic usage: +### link_artifact -```python -import wandb +Link the artifact to a collection. -with wandb.init() as run: - run.log({"train-loss": 0.5, "accuracy": 0.9}) -``` +The term “link” refers to pointers that connect where W&B stores the +artifact and where the artifact is accessible in the registry. W&B +does not duplicate artifacts when you link an artifact to a collection. -The previous code snippet saves the loss and accuracy to the run's history and updates the summary values for these metrics. +View linked artifacts in the Registry UI for the specified collection. -Visualize logged data in a workspace at [wandb.ai](https://wandb.ai), or locally on a [self-hosted instance](https://docs.wandb.ai/platform/hosting) of the W&B app, or export data to visualize and explore locally, such as in a Jupyter notebook, with the [Public API](https://docs.wandb.ai/models/track/public-api-guide). +### link_model -Logged values don't have to be scalars. You can log any [W&B supported Data Type](https://docs.wandb.ai/models/ref/python/data-types) such as images, audio, video, and more. For example, you can use `wandb.Table` to log structured data. See [Log tables, visualize and query data](https://docs.wandb.ai/models/tables/tables-walkthrough) tutorial for more details. +Log a model artifact version and link it to a registered model in the model registry. -W&B organizes metrics with a forward slash (`/`) in their name into sections named using the text before the final slash. For example, the following results in two sections named "train" and "validate": +Linked model versions are visible in the UI for the specified registered model. -```python -with wandb.init() as run: - # Log metrics in the "train" section. - run.log( - { - "train/accuracy": 0.9, - "train/loss": 30, - "validate/accuracy": 0.8, - "validate/loss": 20, - } - ) -``` - -Only one level of nesting is supported; `run.log({"a/b/c": 1})` produces a section named "a". - -`run.log()` is not intended to be called more than a few times per second. For optimal performance, limit your logging to once every N iterations, or collect data over multiple iterations and log it in a single step. - -By default, each call to `log` creates a new "step". The step must always increase, and it is not possible to log to a previous step. You can use any metric as the X axis in charts. See [Custom log axes](https://docs.wandb.ai/models/track/log/customize-logging-axes) for more details. - -In many cases, it is better to treat the W&B step like you'd treat a timestamp rather than a training step. - -```python -with wandb.init() as run: - # Example: log an "epoch" metric for use as an X axis. - run.log({"epoch": 40, "train-loss": 0.5}) -``` - -It is possible to use multiple `wandb.Run.log()` invocations to log to the same step with the `step` and `commit` parameters. The following are all equivalent: - -```python -with wandb.init() as run: - # Normal usage: - run.log({"train-loss": 0.5, "accuracy": 0.8}) - run.log({"train-loss": 0.4, "accuracy": 0.9}) +This method will: +- Check if 'name' model artifact has been logged. If so, use the artifact version that matches the files +located at 'path' or log a new version. Otherwise log files under 'path' as a new model artifact, 'name' +of type 'model'. +- Check if registered model with name 'registered_model_name' exists in the 'model-registry' project. +If not, create a new registered model with name 'registered_model_name'. +- Link version of model artifact 'name' to registered model, 'registered_model_name'. +- Attach aliases from 'aliases' list to the newly linked model artifact version. - # Implicit step without auto-incrementing: - run.log({"train-loss": 0.5}, commit=False) - run.log({"accuracy": 0.8}) - run.log({"train-loss": 0.4}, commit=False) - run.log({"accuracy": 0.9}) +### log - # Explicit step: - run.log({"train-loss": 0.5}, step=current_step) - run.log({"accuracy": 0.8}, step=current_step) - current_step += 1 - run.log({"train-loss": 0.4}, step=current_step) - run.log({"accuracy": 0.9}, step=current_step, commit=True) -``` +Upload run data. +Use `log` to log data from runs, such as scalars, images, video, +histograms, plots, and tables. See [Log objects and media](https://docs.wandb.ai/models/track/log) for +code snippets, best practices, and more. - -**Args:** - - - `data`: A `dict` with `str` keys and values that are serializable - - `Python objects including`: `int`, `float` and `string`; any of the `wandb.data_types`; lists, tuples and NumPy arrays of serializable Python objects; other `dict`s of this structure. - - `step`: The step number to log. If `None`, then an implicit auto-incrementing step is used. See the notes in the description. - - `commit`: If true, finalize and upload the step. If false, then accumulate data for the step. See the notes in the description. If `step` is `None`, then the default is `commit=True`; otherwise, the default is `commit=False`. - - - -**Examples:** - For more and more detailed examples, see [our guides to logging](https://docs.wandb.ai/models/track/log). - -Basic usage - -```python -import wandb - -with wandb.init() as run: - run.log({"train-loss": 0.5, "accuracy": 0.9 -``` - -Incremental logging +Basic usage: ```python import wandb with wandb.init() as run: - run.log({"loss": 0.2}, commit=False) - # Somewhere else when I'm ready to report this step: - run.log({"accuracy": 0.8}) -``` - -Histogram - -```python -import numpy as np -import wandb - -# sample gradients at random from normal distribution -gradients = np.random.randn(100, 100) -with wandb.init() as run: - run.log({"gradients": wandb.Histogram(gradients)}) -``` - -Image from NumPy - -```python -import numpy as np -import wandb - -with wandb.init() as run: - examples = [] - for i in range(3): - pixels = np.random.randint(low=0, high=256, size=(100, 100, 3)) - image = wandb.Image(pixels, caption=f"random field {i}") - examples.append(image) - run.log({"examples": examples}) -``` - -Image from PIL - -```python -import numpy as np -from PIL import Image as PILImage -import wandb - -with wandb.init() as run: - examples = [] - for i in range(3): - pixels = np.random.randint( - low=0, - high=256, - size=(100, 100, 3), - dtype=np.uint8, - ) - pil_image = PILImage.fromarray(pixels, mode="RGB") - image = wandb.Image(pil_image, caption=f"random field {i}") - examples.append(image) - run.log({"examples": examples}) -``` - -Video from NumPy - -```python -import numpy as np -import wandb - -with wandb.init() as run: - # axes are (time, channel, height, width) - frames = np.random.randint( - low=0, - high=256, - size=(10, 3, 100, 100), - dtype=np.uint8, - ) - run.log({"video": wandb.Video(frames, fps=4)}) -``` - -Matplotlib plot + run.log({"train-loss": 0.5, "accuracy": 0.9}) +``` -```python -from matplotlib import pyplot as plt -import numpy as np -import wandb +The previous code snippet saves the loss and accuracy to the run's +history and updates the summary values for these metrics. -with wandb.init() as run: - fig, ax = plt.subplots() - x = np.linspace(0, 10) - y = x * x - ax.plot(x, y) # plot y = x^2 - run.log({"chart": fig}) -``` +Visualize logged data in a workspace at [wandb.ai](https://wandb.ai), +or locally on a [self-hosted instance](https://docs.wandb.ai/platform/hosting) +of the W&B app, or export data to visualize and explore locally, such as in a +Jupyter notebook, with the [Public API](https://docs.wandb.ai/models/track/public-api-guide). -PR Curve +Logged values don't have to be scalars. You can log any +[W&B supported Data Type](https://docs.wandb.ai/models/ref/python/data-types) +such as images, audio, video, and more. For example, you can use +`wandb.Table` to log structured data. See +[Log tables, visualize and query data](https://docs.wandb.ai/models/tables/tables-walkthrough) +tutorial for more details. -```python -import wandb - -with wandb.init() as run: - run.log({"pr": wandb.plot.pr_curve(y_test, y_probas, labels)}) -``` - -3D Object +W&B organizes metrics with a forward slash (`/`) in their name +into sections named using the text before the final slash. For example, +the following results in two sections named "train" and "validate": ```python -import wandb - with wandb.init() as run: + # Log metrics in the "train" section. run.log( - { - "generated_samples": [ - wandb.Object3D(open("sample.obj")), - wandb.Object3D(open("sample.gltf")), - wandb.Object3D(open("sample.glb")), - ] - } + { + "train/accuracy": 0.9, + "train/loss": 30, + "validate/accuracy": 0.8, + "validate/loss": 20, + } ) -``` - - - -**Raises:** - - - `wandb.Error`: If called before `wandb.init()`. - - `ValueError`: If invalid data is passed. - ---- - -### method `Run.log_artifact` - -```python -log_artifact( - artifact_or_path: 'Artifact | StrPath', - name: 'str | None' = None, - type: 'str | None' = None, - aliases: 'list[str] | None' = None, - tags: 'list[str] | None' = None -) → Artifact ``` -Declare an artifact as an output of a run. +Only one level of nesting is supported; `run.log({"a/b/c": 1})` +produces a section named "a". +`run.log()` is not intended to be called more than a few times per second. +For optimal performance, limit your logging to once every N iterations, +or collect data over multiple iterations and log it in a single step. +By default, each call to `log` creates a new "step". +The step must always increase, and it is not possible to log +to a previous step. You can use any metric as the X axis in charts. +See [Custom log axes](https://docs.wandb.ai/models/track/log/customize-logging-axes) +for more details. -**Args:** - - - `artifact_or_path`: (str or Artifact) A path to the contents of this artifact, can be in the following forms: - - `/local/directory` - - `/local/directory/file.txt` - - `s3://bucket/path` You can also pass an Artifact object created by calling `wandb.Artifact`. - - `name`: (str, optional) An artifact name. Valid names can be in the following forms: - - name:version - - name:alias - - digest This will default to the basename of the path prepended with the current run id if not specified. - - `type`: (str) The type of artifact to log, examples include `dataset`, `model` - - `aliases`: (list, optional) Aliases to apply to this artifact, defaults to `["latest"]` - - `tags`: (list, optional) Tags to apply to this artifact, if any. - - - -**Returns:** - An `Artifact` object. - ---- - -### method `Run.log_code` +In many cases, it is better to treat the W&B step like +you'd treat a timestamp rather than a training step. ```python -log_code( - root: 'str | None' = '.', - name: 'str | None' = None, - include_fn: 'Callable[[str, str], bool] | Callable[[str], bool]' = , - exclude_fn: 'Callable[[str, str], bool] | Callable[[str], bool]' = -) → Artifact | None -``` - -Save the current state of your code to a W&B Artifact. - -By default, it walks the current directory and logs all files that end with `.py`. - - - -**Args:** - - - `root`: The relative (to `os.getcwd()`) or absolute path to recursively find code from. - - `name`: (str, optional) The name of our code artifact. By default, we'll name the artifact `source-$PROJECT_ID-$ENTRYPOINT_RELPATH`. There may be scenarios where you want many runs to share the same artifact. Specifying name allows you to achieve that. - - `include_fn`: A callable that accepts a file path and (optionally) root path and returns True when it should be included and False otherwise. This - - `defaults to `lambda path, root`: path.endswith(".py")`. - - `exclude_fn`: A callable that accepts a file path and (optionally) root path and returns `True` when it should be excluded and `False` otherwise. This defaults to a function that excludes all files within `/.wandb/` and `/wandb/` directories. - - - -**Examples:** - Basic usage - -```python -import wandb - with wandb.init() as run: - run.log_code() -``` - -Advanced usage - -```python -import wandb - -with wandb.init() as run: - run.log_code( - root="../", - include_fn=lambda path: path.endswith(".py") or path.endswith(".ipynb"), - exclude_fn=lambda path, root: os.path.relpath(path, root).startswith( - "cache/" - ), - ) -``` - - - -**Returns:** - An `Artifact` object if code was logged - ---- - -### method `Run.log_model` - -```python -log_model( - path: 'StrPath', - name: 'str | None' = None, - aliases: 'list[str] | None' = None -) → None -``` - -Logs a model artifact containing the contents inside the 'path' to a run and marks it as an output to this run. - -The name of model artifact can only contain alphanumeric characters, underscores, and hyphens. - - - -**Args:** - - - `path`: (str) A path to the contents of this model, can be in the following forms: - - `/local/directory` - - `/local/directory/file.txt` - - `s3://bucket/path` - - `name`: A name to assign to the model artifact that the file contents will be added to. This will default to the basename of the path prepended with the current run id if not specified. - - `aliases`: Aliases to apply to the created model artifact, defaults to `["latest"]` - - - -**Raises:** - - - `ValueError`: If name has invalid special characters. - - - -**Returns:** - None - ---- - -### method `Run.mark_preempting` - -```python -mark_preempting() → None + # Example: log an "epoch" metric for use as an X axis. + run.log({"epoch": 40, "train-loss": 0.5}) ``` -Mark this run as preempting. - -Also tells the internal process to immediately report this to server. - ---- - -### method `Run.pin_config_keys` +It is possible to use multiple `wandb.Run.log()` invocations to log to +the same step with the `step` and `commit` parameters. +The following are all equivalent: ```python -pin_config_keys(keys: 'Sequence[str]' = ()) → None -``` - -Pin config keys to display in the References section on Run Overview. - -Pinned keys appear prominently above Notes on the Run Overview page. String values are rendered as markdown; non-strings are rendered as plain text. Calling this again replaces the previously pinned list. - - - -**Args:** - - - `keys`: Config key names to pin, matching keys set via ``run.config``. These are exact key strings (dots and slashes are treated literally, not as path separators). Order is preserved and determines display order. - ---- - - -### method `Run.restore` - -```python -restore( - name: 'str', - run_path: 'str | None' = None, - replace: 'bool' = False, - root: 'str | None' = None -) → None | TextIO -``` - -Download the specified file from cloud storage. - -File is placed into the current directory or run directory. By default, will only download the file if it doesn't already exist. - - - -**Args:** - - - `name`: The name of the file. - - `run_path`: Optional path to a run to pull files from, i.e. `username/project_name/run_id` if wandb.init has not been called, this is required. - - `replace`: Whether to download the file even if it already exists locally - - `root`: The directory to download the file to. Defaults to the current directory or the run directory if wandb.init was called. - - - -**Returns:** - None if it can't find the file, otherwise a file object open for reading. - - - -**Raises:** - - - `CommError`: If W&B can't connect to the W&B backend. - - `ValueError`: If the file is not found or can't find run_path. - ---- - -### method `Run.save` - -```python -save( - glob_str: 'str | os.PathLike', - base_path: 'str | os.PathLike | None' = None, - policy: 'PolicyName' = 'live' -) → bool | list[str] -``` - -Sync one or more files to W&B. - -Relative paths are relative to the current working directory. - -A Unix glob, such as "myfiles/*", is expanded at the time `save` is called regardless of the `policy`. In particular, new files are not picked up automatically. - -A `base_path` may be provided to control the directory structure of uploaded files. It should be a prefix of `glob_str`, and the directory structure beneath it is preserved. - -When given an absolute path or glob and no `base_path`, one directory level is preserved as in the example above. - -Files are automatically deduplicated: calling `save()` multiple times on the same file without modifications will not re-upload it. - - - -**Args:** - - - `glob_str`: A relative or absolute path or Unix glob. - - `base_path`: A path to use to infer a directory structure; see examples. - - `policy`: One of `live`, `now`, or `end`. - - live: upload the file as it changes, overwriting the previous version - - now: upload the file once now - - end: upload file when the run ends - - - -**Returns:** - Paths to the symlinks created for the matched files. - -For historical reasons, this may return a boolean in legacy code. - -```python -import wandb - -run = wandb.init() - -run.save("these/are/myfiles/*") -# => Saves files in a "these/are/myfiles/" folder in the run. - -run.save("these/are/myfiles/*", base_path="these") -# => Saves files in an "are/myfiles/" folder in the run. - -run.save("/Users/username/Documents/run123/*.txt") -# => Saves files in a "run123/" folder in the run. See note below. - -run.save("/Users/username/Documents/run123/*.txt", base_path="/Users") -# => Saves files in a "username/Documents/run123/" folder in the run. - -run.save("files/*/saveme.txt") -# => Saves each "saveme.txt" file in an appropriate subdirectory -# of "files/". - -# Explicitly finish the run since a context manager is not used. -run.finish() -``` - ---- - -### method `Run.status` - -```python -status() → RunStatus -``` - -Get sync info from the internal backend, about the current run's sync status. - ---- - - -### method `Run.unwatch` - -```python -unwatch( - models: 'torch.nn.Module | Sequence[torch.nn.Module] | None' = None -) → None -``` - -Remove pytorch model topology, gradient and parameter hooks. - - - -**Args:** - - - `models`: Optional list of pytorch models that have had watch called on them. - ---- - -### method `Run.upsert_artifact` - -```python -upsert_artifact( - artifact_or_path: 'Artifact | str', - name: 'str | None' = None, - type: 'str | None' = None, - aliases: 'list[str] | None' = None, - distributed_id: 'str | None' = None -) → Artifact -``` - -Declare (or append to) a non-finalized artifact as output of a run. - -Note that you must call run.finish_artifact() to finalize the artifact. This is useful when distributed jobs need to all contribute to the same artifact. - - - -**Args:** - - - `artifact_or_path`: A path to the contents of this artifact, can be in the following forms: - - `/local/directory` - - `/local/directory/file.txt` - - `s3://bucket/path` - - `name`: An artifact name. May be prefixed with "entity/project". Defaults to the basename of the path prepended with the current run ID if not specified. Valid names can be in the following forms: - - name:version - - name:alias - - digest - - `type`: The type of artifact to log. Common examples include `dataset`, `model`. - - `aliases`: Aliases to apply to this artifact, defaults to `["latest"]`. - - `distributed_id`: Unique string that all distributed jobs share. If None, defaults to the run's group name. - - - -**Returns:** - An `Artifact` object. - ---- - -### method `Run.use_artifact` +with wandb.init() as run: + # Normal usage: + run.log({"train-loss": 0.5, "accuracy": 0.8}) + run.log({"train-loss": 0.4, "accuracy": 0.9}) -```python -use_artifact( - artifact_or_name: 'str | Artifact', - type: 'str | None' = None, - aliases: 'list[str] | None' = None, - use_as: 'str | None' = None -) → Artifact + # Implicit step without auto-incrementing: + run.log({"train-loss": 0.5}, commit=False) + run.log({"accuracy": 0.8}) + run.log({"train-loss": 0.4}, commit=False) + run.log({"accuracy": 0.9}) + + # Explicit step: + run.log({"train-loss": 0.5}, step=current_step) + run.log({"accuracy": 0.8}, step=current_step) + current_step += 1 + run.log({"train-loss": 0.4}, step=current_step) + run.log({"accuracy": 0.9}, step=current_step, commit=True) ``` -Declare an artifact as an input to a run. +### log_artifact -Call `download` or `file` on the returned object to get the contents locally. +Declare an artifact as an output of a run. +### log_code +Save the current state of your code to a W&B Artifact. -**Args:** - - - `artifact_or_name`: The name of the artifact to use. May be prefixed with the name of the project the artifact was logged to ("entity" or "entity/project"). If no entity is specified in the name, the Run or API setting's entity is used. Valid names can be in the following forms - - name:version - - name:alias - - `type`: The type of artifact to use. - - `aliases`: Aliases to apply to this artifact - - `use_as`: This argument is deprecated and does nothing. +By default, it walks the current directory and logs all files that end with `.py`. +### log_model +Logs a model artifact containing the contents inside the 'path' to a run and marks it as an output to this run. -**Returns:** - An `Artifact` object. +The name of model artifact can only contain alphanumeric characters, +underscores, and hyphens. +### mark_preempting +Mark this run as preempting. -**Examples:** - ```python -import wandb +Also tells the internal process to immediately report this to server. -run = wandb.init(project="") +### pin_config_keys -# Use an artifact by name and alias -artifact_a = run.use_artifact(artifact_or_name=":") +Pin config keys to display in the References section on Run Overview. -# Use an artifact by name and version -artifact_b = run.use_artifact(artifact_or_name=":v") +Pinned keys appear prominently above Notes on the Run Overview page. +String values are rendered as markdown; non-strings are rendered as +plain text. Calling this again replaces the previously pinned list. -# Use an artifact by entity/project/name:alias -artifact_c = run.use_artifact( - artifact_or_name="//:" -) +### restore -# Use an artifact by entity/project/name:version -artifact_d = run.use_artifact( - artifact_or_name="//:v" -) +Download the specified file from cloud storage. -# Explicitly finish the run since a context manager is not used. -run.finish() -``` +File is placed into the current directory or run directory. +By default, will only download the file if it doesn't already exist. ---- +### save -### method `Run.use_model` +Sync one or more files to W&B. -```python -use_model(name: 'str') → FilePathStr -``` +Relative paths are relative to the current working directory. -Download the files logged in a model artifact 'name'. +A Unix glob, such as "myfiles/*", is expanded at the time `save` is +called regardless of the `policy`. In particular, new files are not +picked up automatically. +A `base_path` may be provided to control the directory structure of +uploaded files. It should be a prefix of `glob_str`, and the directory +structure beneath it is preserved. +When given an absolute path or glob and no `base_path`, one +directory level is preserved as in the example above. -**Args:** - - - `name`: A model artifact name. 'name' must match the name of an existing logged model artifact. May be prefixed with `entity/project/`. Valid names can be in the following forms - - model_artifact_name:version - - model_artifact_name:alias +Files are automatically deduplicated: calling `save()` multiple times +on the same file without modifications will not re-upload it. +### status +Get sync info from the internal backend, about the current run's sync status. -**Returns:** - - - `path` (str): Path to downloaded model artifact file(s). +### unwatch +Remove pytorch model topology, gradient and parameter hooks. +### upsert_artifact -**Raises:** - - - `AssertionError`: If model artifact 'name' is of a type that does not contain the substring 'model'. +Declare (or append to) a non-finalized artifact as output of a run. ---- +Note that you must call run.finish_artifact() to finalize the artifact. +This is useful when distributed jobs need to all contribute to the same artifact. -### method `Run.watch` +### use_artifact -```python -watch( - models: 'torch.nn.Module | Sequence[torch.nn.Module]', - criterion: 'torch.F | None' = None, - log: "Literal['gradients', 'parameters', 'all'] | None" = 'gradients', - log_freq: 'int' = 1000, - idx: 'int | None' = None, - log_graph: 'bool' = False -) → None -``` +Declare an artifact as an input to a run. -Hook into given PyTorch model to monitor gradients and the model's computational graph. +Call `download` or `file` on the returned object to get the contents locally. -This function can track parameters, gradients, or both during training. +### use_model +Download the files logged in a model artifact 'name'. +### watch -**Args:** - - - `models`: A single model or a sequence of models to be monitored. - - `criterion`: The loss function being optimized (optional). - - `log`: Specifies whether to log "gradients", "parameters", or "all". Set to None to disable logging. (default="gradients"). - - `log_freq`: Frequency (in batches) to log gradients and parameters. (default=1000) - - `idx`: Index used when tracking multiple models with `wandb.watch`. (default=None) - - `log_graph`: Whether to log the model's computational graph. (default=False) +Hook into given PyTorch model to monitor gradients and the model's computational graph. +This function can track parameters, gradients, or both during training. -**Raises:** - ValueError: If `wandb.init()` has not been called or if any of the models are not instances of `torch.nn.Module`. diff --git a/models/ref/python/experiments/settings.mdx b/models/ref/python/experiments/settings.mdx index d0beb1636a..365c572a4c 100644 --- a/models/ref/python/experiments/settings.mdx +++ b/models/ref/python/experiments/settings.mdx @@ -1,15 +1,174 @@ --- title: Settings -namespace: python_sdk_actions -python_object_type: class +kind: class +namespace: wandb.sdk.wandb_settings --- + import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - + + + +```python +*, +allow_media_symlink: bool = False, +allow_offline_artifacts: bool = True, +allow_val_change: bool = False, +anonymous: object = , +api_key: Optional[str] = None, +azure_account_url_to_access_key: Optional[Dict[str, str]] = None, +app_url_override: Optional[str] = None, +base_url: str = 'https://api.wandb.ai', +code_dir: Optional[str] = None, +config_paths: Optional[collections.abc.Sequence[str]] = None, +console: Literal['auto', 'off', 'wrap', 'redirect', 'wrap_raw', 'wrap_emu'] = 'auto', +console_multipart: bool = False, +console_chunk_max_bytes: int = 0, +console_chunk_max_seconds: int = 0, +credentials_file: str = , +disable_code: bool = False, +disable_git: bool = False, +disable_git_fork_point: bool = True, +disable_job_creation: bool = True, +docker: Optional[str] = None, +email: Optional[str] = None, +entity: Optional[str] = None, +organization: Optional[str] = None, +force: bool = False, +fork_from: Optional[wandb.sdk.lib.run_moment.RunMoment] = None, +git_commit: Optional[str] = None, +git_remote: str = 'origin', +git_remote_url: Optional[str] = None, +git_root: Optional[str] = None, +heartbeat_seconds: int = 30, +host: Optional[str] = None, +http_proxy: Optional[str] = None, +https_proxy: Optional[str] = None, +identity_token_file: Optional[str] = None, +ignore_globs: collections.abc.Sequence[str] = (), +init_timeout: float = 90.0, +finish_timeout: float = 0.0, +finish_timeout_raises: bool = False, +insecure_disable_ssl: bool = False, +job_name: Optional[str] = None, +job_source: Optional[Literal['repo', 'artifact', 'image']] = None, +label_disable: bool = False, +launch: bool = False, +launch_config_path: Optional[str] = None, +login_timeout: Optional[float] = None, +mode: Literal['online', 'offline', 'shared', 'disabled', 'dryrun', 'run'] = 'online', +notebook_name: Optional[str] = None, +program: Optional[str] = None, +program_abspath: Optional[str] = None, +program_relpath: Optional[str] = None, +project: Optional[str] = None, +quiet: bool = False, +reinit: Union[Literal['default', 'return_previous', 'finish_previous', 'create_new'], bool] = 'default', +relogin: bool = False, +resume: Optional[Literal['allow', 'must', 'never', 'auto']] = None, +resume_from: Optional[wandb.sdk.lib.run_moment.RunMoment] = None, +resumed: bool = False, +root_dir: str = , +run_group: Optional[str] = None, +run_id: Optional[str] = None, +run_job_type: Optional[str] = None, +run_name: Optional[str] = None, +run_notes: Optional[str] = None, +run_tags: Optional[Tuple[str, ...]] = None, +sagemaker_disable: bool = False, +save_code: Optional[bool] = None, +settings_system: Optional[str] = None, +stop_fn: Optional[Callable[[], NoneType]] = None, +max_end_of_run_history_metrics: int = 10, +max_end_of_run_summary_metrics: int = 10, +show_colors: Optional[bool] = None, +show_emoji: Optional[bool] = None, +show_errors: bool = True, +show_info: bool = True, +show_warnings: bool = True, +silent: bool = False, +start_method: Optional[str] = None, +stop_on_fatal_error: bool = False, +strict: Optional[bool] = None, +summary_timeout: int = 60, +summary_warnings: int = 5, +sweep_id: Optional[str] = None, +sweep_param_path: Optional[str] = None, +symlink: bool = , +sync_tensorboard: Optional[bool] = None, +table_raise_on_max_row_limit_exceeded: bool = False, +use_dot_wandb: Optional[bool] = None, +username: Optional[str] = None, +x_cli_only_mode: bool = False, +x_disable_meta: bool = False, +x_disable_stats: bool = False, +x_disable_viewer: bool = False, +x_disable_machine_info: bool = False, +x_executable: Optional[str] = None, +x_extra_http_headers: Optional[Dict[str, str]] = None, +x_file_stream_max_bytes: Optional[int] = None, +x_file_stream_max_line_bytes: Optional[int] = None, +x_file_stream_transmit_interval: Optional[float] = None, +x_file_stream_retry_max: Optional[int] = None, +x_file_stream_retry_wait_min_seconds: Optional[float] = None, +x_file_stream_retry_wait_max_seconds: Optional[float] = None, +x_file_stream_timeout_seconds: Optional[float] = None, +x_file_transfer_retry_max: Optional[int] = None, +x_file_transfer_retry_wait_min_seconds: Optional[float] = None, +x_file_transfer_retry_wait_max_seconds: Optional[float] = None, +x_file_transfer_timeout_seconds: Optional[float] = None, +x_files_dir: Optional[str] = None, +x_flow_control_custom: Optional[bool] = None, +x_flow_control_disabled: Optional[bool] = None, +x_graphql_retry_max: Optional[int] = None, +x_graphql_retry_wait_min_seconds: Optional[float] = None, +x_graphql_retry_wait_max_seconds: Optional[float] = None, +x_graphql_timeout_seconds: Optional[float] = None, +x_internal_check_process: float = 8.0, +x_jupyter_name: Optional[str] = None, +x_jupyter_path: Optional[str] = None, +x_jupyter_root: Optional[str] = None, +x_label: Optional[str] = None, +x_live_policy_rate_limit: Optional[int] = None, +x_live_policy_wait_time: Optional[int] = None, +x_log_level: int = 20, +x_network_buffer: Optional[int] = None, +x_primary: bool = True, +x_proxies: Optional[Dict[str, str]] = None, +x_runqueue_item_id: Optional[str] = None, +x_save_requirements: bool = True, +x_server_side_derived_summary: bool = False, +x_server_side_expand_glob_metrics: bool = True, +x_service_transport: Optional[str] = None, +x_service_wait: float = 30.0, +x_skip_transaction_log: bool = False, +x_start_time: Optional[float] = None, +x_stats_pid: int = 54642, +x_stats_sampling_interval: float = 15.0, +x_stats_neuron_monitor_config_path: Optional[str] = None, +x_stats_dcgm_exporter: Optional[str] = None, +x_stats_open_metrics_endpoints: Optional[Dict[str, str]] = None, +x_stats_open_metrics_filters: Union[Dict[str, Dict[str, str]], collections.abc.Sequence[str], NoneType] = None, +x_stats_open_metrics_http_headers: Optional[Dict[str, str]] = None, +x_stats_disk_paths: Optional[collections.abc.Sequence[str]] = ('/',), +x_stats_cpu_count: Optional[int] = None, +x_stats_cpu_logical_count: Optional[int] = None, +x_stats_gpu_count: Optional[int] = None, +x_stats_gpu_type: Optional[str] = None, +x_stats_gpu_device_ids: Optional[collections.abc.Sequence[int]] = None, +x_stats_buffer_size: int = 0, +x_stats_coreweave_metadata_base_url: str = 'http://169.254.169.254', +x_stats_coreweave_metadata_endpoint: str = '/api/v2/cloud-init/meta-data', +x_stats_track_process_tree: bool = False, +x_sync: bool = False, +x_sync_dir_suffix: str = '', +x_update_finish_state: bool = True +``` + +## Description -## class `Settings` Settings for the W&B SDK. This class manages configuration settings for the W&B SDK, @@ -28,610 +187,401 @@ The settings are organized into three categories: the environment. -### method `Settings.__init__` - -```python -__init__( - allow_media_symlink: 'bool' = False, - allow_offline_artifacts: 'bool' = True, - allow_val_change: 'bool' = False, - anonymous: 'object' = , - api_key: 'str | None' = None, - azure_account_url_to_access_key: 'dict[str, str] | None' = None, - app_url_override: 'str | None' = None, - base_url: 'str' = 'https://api.wandb.ai', - code_dir: 'str | None' = None, - config_paths: 'Sequence | None' = None, - console: 'Literal['auto', 'off', 'wrap', 'redirect', 'wrap_raw', 'wrap_emu']' = 'auto', - console_multipart: 'bool' = False, - console_chunk_max_bytes: 'int' = 0, - console_chunk_max_seconds: 'int' = 0, - credentials_file: 'str' = None, - disable_code: 'bool' = False, - disable_git: 'bool' = False, - disable_git_fork_point: 'bool' = True, - disable_job_creation: 'bool' = True, - docker: 'str | None' = None, - email: 'str | None' = None, - entity: 'str | None' = None, - organization: 'str | None' = None, - force: 'bool' = False, - fork_from: 'RunMoment | None' = None, - git_commit: 'str | None' = None, - git_remote: 'str' = 'origin', - git_remote_url: 'str | None' = None, - git_root: 'str | None' = None, - heartbeat_seconds: 'int' = 30, - host: 'str | None' = None, - http_proxy: 'str | None' = None, - https_proxy: 'str | None' = None, - identity_token_file: 'str | None' = None, - ignore_globs: 'Sequence' = (), - init_timeout: 'float' = 90.0, - insecure_disable_ssl: 'bool' = False, - job_name: 'str | None' = None, - job_source: 'Literal['repo', 'artifact', 'image'] | None' = None, - label_disable: 'bool' = False, - launch: 'bool' = False, - launch_config_path: 'str | None' = None, - login_timeout: 'float | None' = None, - mode: 'Literal['online', 'offline', 'shared', 'disabled', 'dryrun', 'run']' = 'online', - notebook_name: 'str | None' = None, - program: 'str | None' = None, - program_abspath: 'str | None' = None, - program_relpath: 'str | None' = None, - project: 'str | None' = None, - quiet: 'bool' = False, - reinit: 'Literal['default', 'return_previous', 'finish_previous', 'create_new'] | bool' = 'default', - relogin: 'bool' = False, - resume: 'Literal['allow', 'must', 'never', 'auto'] | None' = None, - resume_from: 'RunMoment | None' = None, - resumed: 'bool' = False, - root_dir: 'str' = None, - run_group: 'str | None' = None, - run_id: 'str | None' = None, - run_job_type: 'str | None' = None, - run_name: 'str | None' = None, - run_notes: 'str | None' = None, - run_tags: 'tuple[str, Ellipsis] | None' = None, - sagemaker_disable: 'bool' = False, - save_code: 'bool | None' = None, - settings_system: 'str | None' = None, - stop_fn: 'Callable | None' = None, - max_end_of_run_history_metrics: 'int' = 10, - max_end_of_run_summary_metrics: 'int' = 10, - show_colors: 'bool | None' = None, - show_emoji: 'bool | None' = None, - show_errors: 'bool' = True, - show_info: 'bool' = True, - show_warnings: 'bool' = True, - silent: 'bool' = False, - start_method: 'str | None' = None, - strict: 'bool | None' = None, - summary_timeout: 'int' = 60, - summary_warnings: 'int' = 5, - sweep_id: 'str | None' = None, - sweep_param_path: 'str | None' = None, - symlink: 'bool' = None, - sync_tensorboard: 'bool | None' = None, - table_raise_on_max_row_limit_exceeded: 'bool' = False, - use_dot_wandb: 'bool | None' = None, - username: 'str | None' = None, - x_cli_only_mode: 'bool' = False, - x_disable_meta: 'bool' = False, - x_disable_stats: 'bool' = False, - x_disable_viewer: 'bool' = False, - x_disable_machine_info: 'bool' = False, - x_executable: 'str | None' = None, - x_extra_http_headers: 'dict[str, str] | None' = None, - x_file_stream_max_bytes: 'int | None' = None, - x_file_stream_max_line_bytes: 'int | None' = None, - x_file_stream_transmit_interval: 'float | None' = None, - x_file_stream_retry_max: 'int | None' = None, - x_file_stream_retry_wait_min_seconds: 'float | None' = None, - x_file_stream_retry_wait_max_seconds: 'float | None' = None, - x_file_stream_timeout_seconds: 'float | None' = None, - x_file_transfer_retry_max: 'int | None' = None, - x_file_transfer_retry_wait_min_seconds: 'float | None' = None, - x_file_transfer_retry_wait_max_seconds: 'float | None' = None, - x_file_transfer_timeout_seconds: 'float | None' = None, - x_files_dir: 'str | None' = None, - x_flow_control_custom: 'bool | None' = None, - x_flow_control_disabled: 'bool | None' = None, - x_graphql_retry_max: 'int | None' = None, - x_graphql_retry_wait_min_seconds: 'float | None' = None, - x_graphql_retry_wait_max_seconds: 'float | None' = None, - x_graphql_timeout_seconds: 'float | None' = None, - x_internal_check_process: 'float' = 8.0, - x_jupyter_name: 'str | None' = None, - x_jupyter_path: 'str | None' = None, - x_jupyter_root: 'str | None' = None, - x_label: 'str | None' = None, - x_live_policy_rate_limit: 'int | None' = None, - x_live_policy_wait_time: 'int | None' = None, - x_log_level: 'int' = 20, - x_network_buffer: 'int | None' = None, - x_primary: 'bool' = True, - x_proxies: 'dict[str, str] | None' = None, - x_runqueue_item_id: 'str | None' = None, - x_save_requirements: 'bool' = True, - x_server_side_derived_summary: 'bool' = False, - x_server_side_expand_glob_metrics: 'bool' = True, - x_service_transport: 'str | None' = None, - x_service_wait: 'float' = 30.0, - x_skip_transaction_log: 'bool' = False, - x_start_time: 'float | None' = None, - x_stats_pid: 'int' = 72322, - x_stats_sampling_interval: 'float' = 15.0, - x_stats_neuron_monitor_config_path: 'str | None' = None, - x_stats_dcgm_exporter: 'str | None' = None, - x_stats_open_metrics_endpoints: 'dict[str, str] | None' = None, - x_stats_open_metrics_filters: 'dict[str, dict[str, str]] | Sequence | None' = None, - x_stats_open_metrics_http_headers: 'dict[str, str] | None' = None, - x_stats_disk_paths: 'Sequence | None' = ('/',), - x_stats_cpu_count: 'int | None' = None, - x_stats_cpu_logical_count: 'int | None' = None, - x_stats_gpu_count: 'int | None' = None, - x_stats_gpu_type: 'str | None' = None, - x_stats_gpu_device_ids: 'Sequence | None' = None, - x_stats_buffer_size: 'int' = 0, - x_stats_coreweave_metadata_base_url: 'str' = 'http://169.254.169.254', - x_stats_coreweave_metadata_endpoint: 'str' = '/api/v2/cloud-init/meta-data', - x_stats_track_process_tree: 'bool' = False, - x_sync: 'bool' = False, - x_sync_dir_suffix: 'str' = '', - x_update_finish_state: 'bool' = True -) → None -``` - -**Args:** - - - `allow_media_symlink` (bool): Whether to symlink media files to the run directory. - If true, media files will be symlinked or hardlinked to the - run directory instead of copied. This may result in faster - logging and reduced disk usage. However, deleting or modifying - the original files before upload to the W&B server will be - reflected in the uploaded data. - - `allow_offline_artifacts` (bool): Flag to allow table artifacts to be synced in offline mode. - To revert to the old behavior, set this to False. - - `allow_val_change` (bool): Flag to allow modification of `Config` values after they've been set. - - `anonymous` (object): Deprecated and will be removed. - - `api_key` (Optional[str]): The W&B API key. - - `azure_account_url_to_access_key` (Optional[Dict[str, str]]): Mapping of Azure account URLs to their corresponding access keys for Azure integration. - - `app_url_override` (Optional[str]): Override for the 'app' URL for the W&B UI. - The `app_url` is normally computed based on `base_url`, but this can be - used to set it explicitly. - WANDB_APP_URL is the corresponding environment variable. - - `base_url` (str): The URL of the W&B backend for data synchronization. - - `code_dir` (Optional[str]): Directory containing the code to be tracked by W&B. - - `config_paths` (Optional[Sequence]): Paths to files to load configuration from into the `Config` object. - - `console` (Literal['auto', 'off', 'wrap', 'redirect', 'wrap_raw', 'wrap_emu']): The type of console capture to be applied. - Possible values are: - - "auto" - Automatically selects the console capture method based on the - system environment and settings. - - "off" - Disables console capture. - - "redirect" - Redirects low-level file descriptors for capturing output. - - "wrap" - Overrides the write methods of sys.stdout/sys.stderr. Will be - mapped to either "wrap_raw" or "wrap_emu" based on the state of the system. - - "wrap_raw" - Same as "wrap" but captures raw output directly instead of - through an emulator. Derived from the `wrap` setting and should not be set manually. - - "wrap_emu" - Same as "wrap" but captures output through an emulator. - Derived from the `wrap` setting and should not be set manually. - - `console_multipart` (bool): Enable multipart console logging. - When True, the SDK writes console output to timestamped files - under the `logs/` directory instead of a single `output.log`. - Each part is uploaded as soon as it is closed, giving users live - access to logs while the run is active. Rollover cadence is - controlled by `console_chunk_max_bytes` and/or `console_chunk_max_seconds`. - If both limits are `0`, all logs are uploaded once at run finish. - Note: Uploaded chunks are immutable; terminal control sequences - that modify previous lines (e.g., progress bars using carriage returns) - only affect the current chunk. - - `console_chunk_max_bytes` (int): Size-based rollover threshold for multipart console logs, in bytes. - Starts a new console log file when the current part reaches this - size. Has an effect only when `console_multipart` is `True`. - Can be combined with `console_chunk_max_seconds`; whichever limit is - hit first triggers the rollover. A value of `0` disables the - size-based limit. - - `console_chunk_max_seconds` (int): Time-based rollover threshold for multipart console logs, in seconds. - Starts a new console log file after this many seconds have elapsed - since the current part began. Requires `console_multipart` to be - `True`. May be used with `console_chunk_max_bytes`; the first limit - reached closes the part. A value of `0` disables the time-based - limit. - - `credentials_file` (str): Path to file for writing temporary access tokens. - - `disable_code` (bool): Whether to disable capturing the code. - - `disable_git` (bool): Whether to disable capturing the git state. - - `disable_git_fork_point` (bool): Whether to disable inferring fork point from remote branches - When set to True, the SDK will use the latest commit from the upstream - branch, if one is set. Otherwise skip generating the diff patch. - When set to False, the SDK will try to use the latest commit from the upstream branch, - if one is set. - Otherwise, it will find the closest commit from all remote branches. - This may impact performance for repos with many upstream branches. - - `disable_job_creation` (bool): Whether to disable the creation of a job artifact for W&B Launch. - - `docker` (Optional[str]): The Docker image used to execute the script. - - `email` (Optional[str]): The email address of the user. - - `entity` (Optional[str]): The W&B entity, such as a user or a team. - - `organization` (Optional[str]): The W&B organization. - - `force` (bool): Whether to pass the `force` flag to `wandb.login()`. - - `fork_from` (Optional[RunMoment]): Specifies a point in a previous execution of a run to fork from. - The point is defined by the run ID, a metric, and its value. - Currently, only the metric '_step' is supported. - - `git_commit` (Optional[str]): The git commit hash to associate with the run. - - `git_remote` (str): The git remote to associate with the run. - - `git_remote_url` (Optional[str]): The URL of the git remote repository. - - `git_root` (Optional[str]): Root directory of the git repository. - - - `host` (Optional[str]): Hostname of the machine running the script. - - `http_proxy` (Optional[str]): Custom proxy servers for http requests to W&B. - - `https_proxy` (Optional[str]): Custom proxy servers for https requests to W&B. - - `identity_token_file` (Optional[str]): Path to file containing an identity token (JWT) for authentication. - - `ignore_globs` (Sequence): Unix glob patterns relative to `files_dir` specifying files to exclude from upload. - - `init_timeout` (float): Time in seconds to wait for the `wandb.init` call to complete before timing out. - - `insecure_disable_ssl` (bool): Whether to insecurely disable SSL verification. - - `job_name` (Optional[str]): Name of the Launch job running the script. - - `job_source` (Optional[Literal['repo', 'artifact', 'image']]): Source type for Launch. - - `label_disable` (bool): Whether to disable automatic labeling features. - - - `launch_config_path` (Optional[str]): Path to the launch configuration file. - - `login_timeout` (Optional[float]): Time in seconds to wait for login operations before timing out. - - `mode` (Literal['online', 'offline', 'shared', 'disabled', 'dryrun', 'run']): The operating mode for W&B logging and synchronization. - - `notebook_name` (Optional[str]): Name of the notebook if running in a Jupyter-like environment. - - `program` (Optional[str]): Path to the script that created the run, if available. - - `program_abspath` (Optional[str]): The absolute path from the root repository directory to the script that - created the run. - Root repository directory is defined as the directory containing the - .git directory, if it exists. Otherwise, it's the current working directory. - - `program_relpath` (Optional[str]): The relative path to the script that created the run. - - `project` (Optional[str]): The W&B project ID. - - `quiet` (bool): Flag to suppress non-essential output. - - `reinit` (Union[Literal['default', 'return_previous', 'finish_previous', 'create_new'], bool]): What to do when `wandb.init()` is called while a run is active. - Options: - - "default": Use "finish_previous" in notebooks and "return_previous" - otherwise. - - "return_previous": Return the most recently created run - that is not yet finished. This does not update `wandb.run`; see - the "create_new" option. - - "finish_previous": Finish all active runs, then return a new run. - - "create_new": Create a new run without modifying other active runs. - Does not update `wandb.run` and top-level functions like `wandb.log`. - Because of this, some older integrations that rely on the global run - will not work. - Can also be a boolean, but this is deprecated. False is the same as - "return_previous", and True is the same as "finish_previous". - - `relogin` (bool): Flag to force a new login attempt. - - `resume` (Optional[Literal['allow', 'must', 'never', 'auto']]): Specifies the resume behavior for the run. - Options: - - "must": Resumes from an existing run with the same ID. If no such run exists, - it will result in failure. - - "allow": Attempts to resume from an existing run with the same ID. If none is - found, a new run will be created. - - "never": Always starts a new run. If a run with the same ID already exists, - it will result in failure. - - "auto": Automatically resumes from the most recent failed run on the same - machine. - - `resume_from` (Optional[RunMoment]): Specifies a point in a previous execution of a run to resume from. - The point is defined by the run ID, a metric, and its value. - Currently, only the metric '_step' is supported. - - - `root_dir` (str): The root directory to use as the base for all run-related paths. - In particular, this is used to derive the wandb directory and the run directory. - - `run_group` (Optional[str]): Group identifier for related runs. - Used for grouping runs in the UI. - - `run_id` (Optional[str]): The ID of the run. - - `run_job_type` (Optional[str]): Type of job being run (e.g., training, evaluation). - - `run_name` (Optional[str]): Human-readable name for the run. - - `run_notes` (Optional[str]): Additional notes or description for the run. - - `run_tags` (Optional[Tuple[str, Ellipsis]]): Tags to associate with the run for organization and filtering. - - `sagemaker_disable` (bool): Flag to disable SageMaker-specific functionality. - - `save_code` (Optional[bool]): Whether to save the code associated with the run. - - `settings_system` (Optional[str]): Path to the system-wide settings file. - - `stop_fn` (Optional[Callable]): A callback to execute to stop the run. - A run can be stopped through the web UI, or after a fatal error - (if configured via a setting). - By default, to stop a run, W&B sends a SIGINT to the main thread. - Set this callback to override this behavior, like to use a different - signal or to take some other action before interrupting. - The callback runs in a separate thread. It runs soon after a stop is - requested, but not immediately. - - `max_end_of_run_history_metrics` (int): Maximum number of history sparklines to display at the end of a run. - - `max_end_of_run_summary_metrics` (int): Maximum number of summary metrics to display at the end of a run. - - - - `show_errors` (bool): Whether to display error messages. - - `show_info` (bool): Whether to display informational messages. - - `show_warnings` (bool): Whether to display warning messages. - - `silent` (bool): Flag to suppress all output. - - - `strict` (Optional[bool]): Whether to enable strict mode for validation and error checking. - - `summary_timeout` (int): Time in seconds to wait for summary operations before timing out. - - - `sweep_id` (Optional[str]): Identifier of the sweep this run belongs to. - - `sweep_param_path` (Optional[str]): Path to the sweep parameters configuration. - - `symlink` (bool): Whether to use symlinks (True by default except on Windows). - - `sync_tensorboard` (Optional[bool]): Whether to synchronize TensorBoard logs with W&B. - - `table_raise_on_max_row_limit_exceeded` (bool): Whether to raise an exception when table row limits are exceeded. - - `use_dot_wandb` (Optional[bool]): Whether to use a hidden `.wandb` or visible `wandb` directory for run data. - If True, the SDK uses `.wandb`. If False, `wandb`. - If not set, defaults to `.wandb` if it already exists, otherwise `wandb`. - - `username` (Optional[str]): Username. - - - `x_disable_meta` (bool): Flag to disable the collection of system metadata. - - `x_disable_stats` (bool): Flag to disable the collection of system metrics. - - - - - `x_extra_http_headers` (Optional[Dict[str, str]]): Additional headers to add to all outgoing HTTP requests. - - - - - - - - - - - +## Args: + +- **allow_media_symlink**: +- **allow_offline_artifacts**: +- **allow_val_change**: +- **anonymous**: +- **api_key**: +- **azure_account_url_to_access_key**: +- **app_url_override**: +- **base_url**: +- **code_dir**: +- **config_paths**: +- **console**: +- **console_multipart**: +- **console_chunk_max_bytes**: +- **console_chunk_max_seconds**: +- **credentials_file**: +- **disable_code**: +- **disable_git**: +- **disable_git_fork_point**: +- **disable_job_creation**: +- **docker**: +- **email**: +- **entity**: +- **organization**: +- **force**: +- **fork_from**: +- **git_commit**: +- **git_remote**: +- **git_remote_url**: +- **git_root**: +- **heartbeat_seconds**: +- **host**: +- **http_proxy**: +- **https_proxy**: +- **identity_token_file**: +- **ignore_globs**: +- **init_timeout**: +- **finish_timeout**: +- **finish_timeout_raises**: +- **insecure_disable_ssl**: +- **job_name**: +- **job_source**: +- **label_disable**: +- **launch**: +- **launch_config_path**: +- **login_timeout**: +- **mode**: +- **notebook_name**: +- **program**: +- **program_abspath**: +- **program_relpath**: +- **project**: +- **quiet**: +- **reinit**: +- **relogin**: +- **resume**: +- **resume_from**: +- **resumed**: +- **root_dir**: +- **run_group**: +- **run_id**: +- **run_job_type**: +- **run_name**: +- **run_notes**: +- **run_tags**: +- **sagemaker_disable**: +- **save_code**: +- **settings_system**: +- **stop_fn**: +- **max_end_of_run_history_metrics**: +- **max_end_of_run_summary_metrics**: +- **show_colors**: +- **show_emoji**: +- **show_errors**: +- **show_info**: +- **show_warnings**: +- **silent**: +- **start_method**: +- **stop_on_fatal_error**: +- **strict**: +- **summary_timeout**: +- **summary_warnings**: +- **sweep_id**: +- **sweep_param_path**: +- **symlink**: +- **sync_tensorboard**: +- **table_raise_on_max_row_limit_exceeded**: +- **use_dot_wandb**: +- **username**: +- **x_cli_only_mode**: +- **x_disable_meta**: +- **x_disable_stats**: +- **x_disable_viewer**: +- **x_disable_machine_info**: +- **x_executable**: +- **x_extra_http_headers**: +- **x_file_stream_max_bytes**: +- **x_file_stream_max_line_bytes**: +- **x_file_stream_transmit_interval**: +- **x_file_stream_retry_max**: +- **x_file_stream_retry_wait_min_seconds**: +- **x_file_stream_retry_wait_max_seconds**: +- **x_file_stream_timeout_seconds**: +- **x_file_transfer_retry_max**: +- **x_file_transfer_retry_wait_min_seconds**: +- **x_file_transfer_retry_wait_max_seconds**: +- **x_file_transfer_timeout_seconds**: +- **x_files_dir**: +- **x_flow_control_custom**: +- **x_flow_control_disabled**: +- **x_graphql_retry_max**: +- **x_graphql_retry_wait_min_seconds**: +- **x_graphql_retry_wait_max_seconds**: +- **x_graphql_timeout_seconds**: +- **x_internal_check_process**: +- **x_jupyter_name**: +- **x_jupyter_path**: +- **x_jupyter_root**: +- **x_label**: +- **x_live_policy_rate_limit**: +- **x_live_policy_wait_time**: +- **x_log_level**: +- **x_network_buffer**: +- **x_primary**: +- **x_proxies**: +- **x_runqueue_item_id**: +- **x_save_requirements**: +- **x_server_side_derived_summary**: +- **x_server_side_expand_glob_metrics**: +- **x_service_transport**: +- **x_service_wait**: +- **x_skip_transaction_log**: +- **x_start_time**: +- **x_stats_pid**: +- **x_stats_sampling_interval**: +- **x_stats_neuron_monitor_config_path**: +- **x_stats_dcgm_exporter**: +- **x_stats_open_metrics_endpoints**: +- **x_stats_open_metrics_filters**: +- **x_stats_open_metrics_http_headers**: +- **x_stats_disk_paths**: +- **x_stats_cpu_count**: +- **x_stats_cpu_logical_count**: +- **x_stats_gpu_count**: +- **x_stats_gpu_type**: +- **x_stats_gpu_device_ids**: +- **x_stats_buffer_size**: +- **x_stats_coreweave_metadata_base_url**: +- **x_stats_coreweave_metadata_endpoint**: +- **x_stats_track_process_tree**: +- **x_sync**: +- **x_sync_dir_suffix**: +- **x_update_finish_state**: + + +## Properties: + +### app_url +The URL for the W&B UI, usually https://wandb.ai. +This is different from `base_url` (like https://api.wandb.ai) which +is used to access W&B APIs programmatically. +### colab_url +The URL to the Colab notebook, if running in Colab. +### deployment +### files_dir +Absolute path to the local directory where the run's files are stored. - - `x_label` (Optional[str]): Label to assign to system metrics and console logs collected for the run. - This is used to group data by on the frontend and can be used to distinguish data - from different processes in a distributed training job. +### is_local +### log_dir - - `x_primary` (bool): Determines whether to save internal wandb files and metadata. - In a distributed setting, this is useful for avoiding file overwrites - from secondary processes when only system metrics and logs are needed, - as the primary process handles the main logging. +The directory for storing log files. +### log_internal - - `x_save_requirements` (bool): Flag to save the requirements file. - - `x_server_side_derived_summary` (bool): Flag to delegate automatic computation of summary from history to the server. - This does not disable user-provided summary updates. +The path to the file to use for internal logs. +### log_symlink_internal - - `x_service_wait` (float): Time in seconds to wait for the wandb-core internal service to start. - - `x_skip_transaction_log` (bool): Whether to skip saving the run events to the transaction log. - This is only relevant for online runs. Can be used to reduce the amount of - data written to disk. - Should be used with caution, as it removes the gurantees about - recoverability. +The path to the symlink to the internal log file of the most recent run. +### log_symlink_user - - `x_stats_sampling_interval` (float): Sampling interval for the system monitor in seconds. +The path to the symlink to the user-process log file of the most recent run. - - `x_stats_dcgm_exporter` (Optional[str]): Endpoint to extract Nvidia DCGM metrics from. - Options: - - Extract DCGM-related metrics from a query to the Prometheus `/api/v1/query` endpoint. - It is a common practice to aggregate metrics reported by the instances of the DCGM Exporter - running on different nodes in a cluster using Prometheus. - - TODO: Parse metrics directly from the `/metrics` endpoint of the DCGM Exporter. - Examples: - - `http://localhost:9400/api/v1/query?query=DCGM_FI_DEV_GPU_TEMP{node="l1337", cluster="globular"}`. +### log_user - - `x_stats_open_metrics_endpoints` (Optional[Dict[str, str]]): OpenMetrics `/metrics` endpoints to monitor for system metrics. - - `x_stats_open_metrics_filters` (Union[Dict[str, Dict[str, str]], Sequence, None]): Filter to apply to metrics collected from OpenMetrics `/metrics` endpoints. - Supports two formats: - - `{"metric regex pattern, including endpoint name as prefix": {"label": "label value regex pattern"}}` - - `("metric regex pattern 1", "metric regex pattern 2", ...)` - - `x_stats_open_metrics_http_headers` (Optional[Dict[str, str]]): HTTP headers to add to OpenMetrics requests. - - `x_stats_disk_paths` (Optional[Sequence]): System paths to monitor for disk usage. - - `x_stats_cpu_count` (Optional[int]): System CPU count. - If set, overrides the auto-detected value in the run metadata. - - `x_stats_cpu_logical_count` (Optional[int]): Logical CPU count. - If set, overrides the auto-detected value in the run metadata. - - `x_stats_gpu_count` (Optional[int]): GPU device count. - If set, overrides the auto-detected value in the run metadata. - - `x_stats_gpu_type` (Optional[str]): GPU device type. - If set, overrides the auto-detected value in the run metadata. - - `x_stats_gpu_device_ids` (Optional[Sequence]): GPU device indices to monitor. - If not set, the system monitor captures metrics for all GPUs. - Assumes 0-based indexing matching CUDA/ROCm device enumeration. +The path to the file to use for user-process logs. +### project_url +The W&B URL where the project can be viewed. - - `x_stats_track_process_tree` (bool): Monitor the entire process tree for resource usage, starting from `x_stats_pid`. - When `True`, the system monitor aggregates the RSS, CPU%, and thread count - from the process with PID `x_stats_pid` and all of its descendants. - This can have a performance overhead and is disabled by default. +### resume_fname - - `x_sync_dir_suffix` (str): Suffix to add to the run's directory name (sync_dir). - This is set in wandb.init() to avoid naming conflicts. - If set, it is joined to the default name with a dash. - - `x_update_finish_state` (bool): Flag to indicate whether this process can update the run's final state on the server. - Set to False in distributed training when only the main process should determine the final state. +The path to the resume file. -**Returns:** - An `Settings` object. +### run_mode +The mode of the run. Can be either "run" or "offline-run". +### run_url +The W&B URL where the run can be viewed. +### settings_workspace +The path to the workspace settings file. +### sweep_url +The W&B URL where the sweep can be viewed. +### sync_dir +The directory for storing the run's files. +### sync_file +Path to the append-only binary transaction log file. +### sync_symlink_latest +Path to the symlink to the most recent run's transaction log file. +### timespec +The time specification for the run. +### wandb_dir +Full path to the wandb directory. +## Methods: +### construct +### copy +Returns a copy of the model. +!!! warning "Deprecated" + This method is now deprecated; use `model_copy` instead. +If you need `include` or `exclude`, use: +```python {test="skip" lint="skip"} +data = self.model_dump(include=include, exclude=exclude, round_trip=True) +data = {**data, **(update or {})} +copied = self.model_validate(data) +``` +### dict +### from_orm -### property `Settings.app_url` +### json -The URL for the W&B UI, usually https://wandb.ai. -This is different from `base_url` (like https://api.wandb.ai) which -is used to access W&B APIs programmatically. -**Returns:** - - `str`: The app_url property value. +### model_construct -### property `Settings.colab_url` +Creates a new instance of the `Model` class with validated data. -The URL to the Colab notebook, if running in Colab. +Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data. +Default values are respected, but no other validation is performed. -**Returns:** - - `Optional[str]`: The colab_url property value. +!!! note + `model_construct()` generally respects the `model_config.extra` setting on the provided model. + That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__` + and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored. + Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in + an error if extra values are passed, but they will be ignored. -### property `Settings.deployment` +### model_copy -### property `Settings.files_dir` +!!! abstract "Usage Documentation" + [`model_copy`](../concepts/serialization.md#model_copy) -Absolute path to the local directory where the run's files are stored. +Returns a copy of the model. -**Returns:** - - `str`: The files_dir property value. +!!! note + The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This + might have unexpected side effects if you store anything in it, on top of the model + fields (e.g. the value of [cached properties][functools.cached_property]). -### property `Settings.is_local` +### model_dump -### property `Settings.log_dir` +!!! abstract "Usage Documentation" + [`model_dump`](../concepts/serialization.md#modelmodel_dump) -The directory for storing log files. +Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. -**Returns:** - - `str`: The log_dir property value. +### model_dump_json -### property `Settings.log_internal` +!!! abstract "Usage Documentation" + [`model_dump_json`](../concepts/serialization.md#modelmodel_dump_json) -The path to the file to use for internal logs. +Generates a JSON representation of the model using Pydantic's `to_json` method. -**Returns:** - - `str`: The log_internal property value. +### model_json_schema -### property `Settings.log_symlink_internal` +Generates a JSON schema for a model class. -The path to the symlink to the internal log file of the most recent run. +### model_parametrized_name -**Returns:** - - `str`: The log_symlink_internal property value. +Compute the class name for parametrizations of generic classes. -### property `Settings.log_symlink_user` +This method can be overridden to achieve a custom naming scheme for generic BaseModels. -The path to the symlink to the user-process log file of the most recent run. +### model_post_init -**Returns:** - - `str`: The log_symlink_user property value. +Override this method to perform additional initialization after `__init__` and `model_construct`. +This is useful if you want to do some validation that requires the entire model to be initialized. -### property `Settings.log_user` +### model_rebuild -The path to the file to use for user-process logs. +Try to rebuild the pydantic-core schema for the model. -**Returns:** - - `str`: The log_user property value. +This may be necessary when one of the annotations is a ForwardRef which could not be resolved during +the initial attempt to build the schema, and automatic rebuilding fails. -### property `Settings.project_url` +### model_validate -The W&B URL where the project can be viewed. +Validate a pydantic model instance. -**Returns:** - - `str`: The project_url property value. +### model_validate_json -### property `Settings.resume_fname` +!!! abstract "Usage Documentation" + [JSON Parsing](../concepts/json.md#json-parsing) -The path to the resume file. +Validate the given JSON data against the Pydantic model. -**Returns:** - - `str`: The resume_fname property value. +### model_validate_strings -### property `Settings.run_mode` +Validate the given object with string data against the Pydantic model. -The mode of the run. Can be either "run" or "offline-run". +### parse_file -**Returns:** - - `Literal['run', 'offline-run']`: The run_mode property value. -### property `Settings.run_url` -The W&B URL where the run can be viewed. +### parse_obj -**Returns:** - - `str`: The run_url property value. -### property `Settings.settings_workspace` -The path to the workspace settings file. +### parse_raw -**Returns:** - - `str`: The settings_workspace property value. -### property `Settings.sweep_url` -The W&B URL where the sweep can be viewed. +### schema -**Returns:** - - `str`: The sweep_url property value. -### property `Settings.sync_dir` -The directory for storing the run's files. +### schema_json -**Returns:** - - `str`: The sync_dir property value. -### property `Settings.sync_file` -Path to the append-only binary transaction log file. +### update_forward_refs -**Returns:** - - `str`: The sync_file property value. -### property `Settings.sync_symlink_latest` -Path to the symlink to the most recent run's transaction log file. +### validate -**Returns:** - - `str`: The sync_symlink_latest property value. -### property `Settings.timespec` -The time specification for the run. +### validate_anonymous -**Returns:** - - `str`: The timespec property value. -### property `Settings.wandb_dir` -Full path to the wandb directory. +### validate_x_extra_http_headers -**Returns:** - - `str`: The wandb_dir property value. +### validate_x_stats_coreweave_metadata_base_url diff --git a/models/ref/python/functions/controller.mdx b/models/ref/python/functions/controller.mdx index a8b13dad5b..59c36a3a6f 100644 --- a/models/ref/python/functions/controller.mdx +++ b/models/ref/python/functions/controller.mdx @@ -1,31 +1,43 @@ --- -title: controller() -namespace: python_sdk_actions -python_object_type: function +title: controller +kind: function +namespace: wandb.sdk.wandb_sweep --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; + -### function `controller` ```python -controller( - sweep_id_or_config: 'str | dict | None' = None, - entity: 'str | None' = None, - project: 'str | None' = None -) → _WandbController +sweep_id_or_config: 'str | dict | None' = None, +entity: 'str | None' = None, +project: 'str | None' = None ``` -Public sweep controller constructor. +## Description + +Public sweep controller constructor. + +## Args: + +- **sweep_id_or_config**: +- **entity**: +- **project**: + + +## Returns: +- **return**: _WandbController -**Examples:** - ```python + + +## Examples: + +```python import wandb tuner = wandb.controller(...) @@ -33,4 +45,5 @@ print(tuner.sweep_config) print(tuner.sweep_id) tuner.configure_search(...) tuner.configure_stopping(...) -``` +``` + diff --git a/models/ref/python/functions/finish.mdx b/models/ref/python/functions/finish.mdx index e1170e77f4..e4781c5d14 100644 --- a/models/ref/python/functions/finish.mdx +++ b/models/ref/python/functions/finish.mdx @@ -1,34 +1,46 @@ --- -title: finish() -namespace: python_sdk_actions -python_object_type: function +title: finish +kind: function +namespace: wandb.sdk.wandb_run --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; + -### function `finish` ```python -finish(exit_code: 'int | None' = None, quiet: 'bool | None' = None) → None +exit_code: 'int | None' = None, +quiet: 'bool | None' = None ``` -Finish a run and upload any remaining data. +## Description + +Finish a run and upload any remaining data. + +Marks the completion of a W&B run and ensures all data is synced to the server. +The run's final state is determined by its exit conditions and sync status. + +Run States: +- Running: Active run that is logging data and/or sending heartbeats. +- Crashed: Run that stopped sending heartbeats unexpectedly. +- Finished: Run completed successfully (`exit_code=0`) with all data synced. +- Failed: Run completed with errors (`exit_code!=0`). + +## Args: + +- **exit_code**: Integer indicating the run's exit status. Use 0 for success, any other value marks the run as failed. +- **quiet**: Deprecated. Configure logging verbosity using `wandb.Settings(quiet=...)`. + + +## Returns: + +- **return**: None + -Marks the completion of a W&B run and ensures all data is synced to the server. The run's final state is determined by its exit conditions and sync status. -Run States: -- Running: Active run that is logging data and/or sending heartbeats. -- Crashed: Run that stopped sending heartbeats unexpectedly. -- Finished: Run completed successfully (`exit_code=0`) with all data synced. -- Failed: Run completed with errors (`exit_code!=0`). -**Args:** - - - `exit_code`: Integer indicating the run's exit status. Use 0 for success, any other value marks the run as failed. - - `quiet`: Deprecated. Configure logging verbosity using `wandb.Settings(quiet=...)`. diff --git a/models/ref/python/functions/init.mdx b/models/ref/python/functions/init.mdx index b9e52b495f..9f3ceb2df2 100644 --- a/models/ref/python/functions/init.mdx +++ b/models/ref/python/functions/init.mdx @@ -1,113 +1,110 @@ --- -title: init() -namespace: python_sdk_actions -python_object_type: function +title: init +kind: function +namespace: wandb.sdk.wandb_init --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; + -### function `init` ```python -init( - entity: 'str | None' = None, - project: 'str | None' = None, - dir: 'StrPath | None' = None, - id: 'str | None' = None, - name: 'str | None' = None, - notes: 'str | None' = None, - tags: 'Sequence[str] | None' = None, - config: 'dict[str, Any] | str | None' = None, - config_exclude_keys: 'list[str] | None' = None, - config_include_keys: 'list[str] | None' = None, - allow_val_change: 'bool | None' = None, - group: 'str | None' = None, - job_type: 'str | None' = None, - mode: "Literal['online', 'offline', 'disabled', 'shared'] | None" = None, - force: 'bool | None' = None, - reinit: "bool | Literal[None, 'default', 'return_previous', 'finish_previous', 'create_new']" = None, - resume: "bool | Literal['allow', 'never', 'must', 'auto'] | None" = None, - resume_from: 'str | None' = None, - fork_from: 'str | None' = None, - save_code: 'bool | None' = None, - tensorboard: 'bool | None' = None, - sync_tensorboard: 'bool | None' = None, - monitor_gym: 'bool | None' = None, - settings: 'Settings | dict[str, Any] | None' = None, - anonymous: 'DoNotSet' = -) → Run +entity: 'str | None' = None, +project: 'str | None' = None, +dir: 'StrPath | None' = None, +id: 'str | None' = None, +name: 'str | None' = None, +notes: 'str | None' = None, +tags: 'Sequence[str] | None' = None, +config: 'dict[str, Any] | str | None' = None, +config_exclude_keys: 'list[str] | None' = None, +config_include_keys: 'list[str] | None' = None, +allow_val_change: 'bool | None' = None, +group: 'str | None' = None, +job_type: 'str | None' = None, +mode: "Literal['online', 'offline', 'disabled', 'shared'] | None" = None, +force: 'bool | None' = None, +reinit: "bool | Literal[None, 'default', 'return_previous', 'finish_previous', 'create_new']" = None, +resume: "bool | Literal['allow', 'never', 'must', 'auto'] | None" = None, +resume_from: 'str | None' = None, +fork_from: 'str | None' = None, +save_code: 'bool | None' = None, +tensorboard: 'bool | None' = None, +sync_tensorboard: 'bool | None' = None, +monitor_gym: 'bool | None' = None, +settings: 'Settings | dict[str, Any] | None' = None, +anonymous: 'DoNotSet' = ``` -Start a new run to track and log to W&B. +## Description + +Start a new run to track and log to W&B. -In an ML training pipeline, you could add `wandb.init()` to the beginning of your training script as well as your evaluation script, and each piece would be tracked as a run in W&B. +In an ML training pipeline, you could add `wandb.init()` to the beginning of +your training script as well as your evaluation script, and each piece would +be tracked as a run in W&B. -`wandb.init()` spawns a new background process to log data to a run, and it also syncs data to https://wandb.ai by default, so you can see your results in real-time. When you're done logging data, call `wandb.Run.finish()` to end the run. If you don't call `run.finish()`, the run will end when your script exits. +`wandb.init()` spawns a new background process to log data to a run, and it +also syncs data to https://wandb.ai by default, so you can see your results +in real-time. When you're done logging data, call `run.finish()` to +end the run, or use the run as a context manager to call it automatically: -Run IDs must not contain any of the following special characters `/ \ # ? % :` + with wandb.init() as run: + ... # run.finish() executes at the end of the block +If you don't call `run.finish()`, the run will end when your script exits. +Run IDs must not contain any of the following special characters `/ \ # ? % :` -**Args:** - - - `entity`: The username or team name the runs are logged to. The entity must already exist, so ensure you create your account or team in the UI before starting to log runs. If not specified, the run will default your default entity. To change the default entity, go to your settings and update the "Default location to create new projects" under "Default team". - - `project`: The name of the project under which this run will be logged. If not specified, we use a heuristic to infer the project name based on the system, such as checking the git root or the current program file. If we can't infer the project name, the project will default to `"uncategorized"`. - - `dir`: The absolute path to the directory where experiment logs and metadata files are stored. If not specified, this defaults to the `./wandb` directory. Note that this does not affect the location where artifacts are stored when calling `download()`. - - `id`: A unique identifier for this run, used for resuming. It must be unique within the project and cannot be reused once a run is deleted. For a short descriptive name, use the `name` field, or for saving hyperparameters to compare across runs, use `config`. - - `name`: A short display name for this run, which appears in the UI to help you identify it. By default, we generate a random two-word name allowing easy cross-reference runs from table to charts. Keeping these run names brief enhances readability in chart legends and tables. For saving hyperparameters, we recommend using the `config` field. - - `notes`: A detailed description of the run, similar to a commit message in Git. Use this argument to capture any context or details that may help you recall the purpose or setup of this run in the future. - - `tags`: A list of tags to label this run in the UI. Tags are helpful for organizing runs or adding temporary identifiers like "baseline" or "production." You can easily add, remove tags, or filter by tags in the UI. If resuming a run, the tags provided here will replace any existing tags. To add tags to a resumed run without overwriting the current tags, use `run.tags += ("new_tag",)` after calling `run = wandb.init()`. - - `config`: Sets `wandb.config`, a dictionary-like object for storing input parameters to your run, such as model hyperparameters or data preprocessing settings. The config appears in the UI in an overview page, allowing you to group, filter, and sort runs based on these parameters. Keys should not contain periods (`.`), and values should be smaller than 10 MB. If a dictionary, `argparse.Namespace`, or `absl.flags.FLAGS` is provided, the key-value pairs will be loaded directly into `wandb.config`. If a string is provided, it is interpreted as a path to a YAML file, from which configuration values will be loaded into `wandb.config`. - - `config_exclude_keys`: A list of specific keys to exclude from `wandb.config`. - - `config_include_keys`: A list of specific keys to include in `wandb.config`. - - `allow_val_change`: Controls whether config values can be modified after their initial set. By default, an exception is raised if a config value is overwritten. For tracking variables that change during training, such as a learning rate, consider using `wandb.log()` instead. By default, this is `False` in scripts and `True` in Notebook environments. - - `group`: Specify a group name to organize individual runs as part of a larger experiment. This is useful for cases like cross-validation or running multiple jobs that train and evaluate a model on different test sets. Grouping allows you to manage related runs collectively in the UI, making it easy to toggle and review results as a unified experiment. - - `job_type`: Specify the type of run, especially helpful when organizing runs within a group as part of a larger experiment. For example, in a group, you might label runs with job types such as "train" and "eval". Defining job types enables you to easily filter and group similar runs in the UI, facilitating direct comparisons. - - `mode`: Specifies how run data is managed, with the following options: - - `"online"` (default): Enables live syncing with W&B when a network connection is available, with real-time updates to visualizations. - - `"offline"`: Suitable for air-gapped or offline environments; data is saved locally and can be synced later. Ensure the run folder is preserved to enable future syncing. - - `"disabled"`: Disables all W&B functionality, making the run’s methods no-ops. Typically used in testing to bypass W&B operations. - - `"shared"`: (This is an experimental feature). Allows multiple processes, possibly on different machines, to simultaneously log to the same run. In this approach you use a primary node and one or more worker nodes to log data to the same run. Within the primary node you initialize a run. For each worker node, initialize a run using the run ID used by the primary node. - - `force`: Determines if a W&B login is required to run the script. If `True`, the user must be logged in to W&B; otherwise, the script will not proceed. If `False` (default), the script can proceed without a login, switching to offline mode if the user is not logged in. - - `reinit`: Shorthand for the "reinit" setting. Determines the behavior of `wandb.init()` when a run is active. - - `resume`: Controls the behavior when resuming a run with the specified `id`. Available options are: - - `"allow"`: If a run with the specified `id` exists, it will resume from the last step; otherwise, a new run will be created. - - `"never"`: If a run with the specified `id` exists, an error will be raised. If no such run is found, a new run will be created. - - `"must"`: If a run with the specified `id` exists, it will resume from the last step. If no run is found, an error will be raised. - - `"auto"`: Automatically resumes the previous run if it crashed on this machine; otherwise, starts a new run. - - `True`: Deprecated. Use `"auto"` instead. - - `False`: Deprecated. Use the default behavior (leaving `resume` unset) to always start a new run. If `resume` is set, `fork_from` and `resume_from` cannot be used. When `resume` is unset, the system will always start a new run. - - `resume_from`: Specifies a moment in a previous run to resume a run from, using the format `{run_id}?_step={step}`. This allows users to truncate the history logged to a run at an intermediate step and resume logging from that step. The target run must be in the same project. If an `id` argument is also provided, the `resume_from` argument will take precedence. `resume`, `resume_from` and `fork_from` cannot be used together, only one of them can be used at a time. Note that this feature is in beta and may change in the future. - - `fork_from`: Specifies a point in a previous run from which to fork a new run, using the format `{id}?_step={step}`. This creates a new run that resumes logging from the specified step in the target run’s history. The target run must be part of the current project. If an `id` argument is also provided, it must be different from the `fork_from` argument, an error will be raised if they are the same. `resume`, `resume_from` and `fork_from` cannot be used together, only one of them can be used at a time. Note that this feature is in beta and may change in the future. - - `save_code`: Enables saving the main script or notebook to W&B, aiding in experiment reproducibility and allowing code comparisons across runs in the UI. By default, this is disabled, but you can change the default to enable on your settings page. - - `tensorboard`: Deprecated. Use `sync_tensorboard` instead. - - `sync_tensorboard`: Enables automatic syncing of W&B logs from TensorBoard or TensorBoardX, saving relevant event files for viewing in the W&B UI. - - `monitor_gym`: Enables automatic logging of videos of the environment when using OpenAI Gym. - - `settings`: Specifies a dictionary or `wandb.Settings` object with advanced settings for the run. +## Args: +- **entity**: The username or team name the runs are logged to. The entity must already exist, so ensure you create your account or team in the UI before starting to log runs. If not specified, the run will default your default entity. To change the default entity, go to your settings and update the "Default location to create new projects" under "Default team". +- **project**: The name of the project under which this run will be logged. If not specified, we use a heuristic to infer the project name based on the system, such as checking the git root or the current program file. If we can't infer the project name, the project will default to `"uncategorized"`. +- **dir**: The absolute path to the directory where experiment logs and metadata files are stored. If not specified, this defaults to the `./wandb` directory. Note that this does not affect the location where artifacts are stored when calling `download()`. +- **id**: A unique identifier for this run, used for resuming. It must be unique within the project and cannot be reused once a run is deleted. For a short descriptive name, use the `name` field, or for saving hyperparameters to compare across runs, use `config`. +- **name**: A short display name for this run, which appears in the UI to help you identify it. By default, we generate a random two-word name allowing easy cross-reference runs from table to charts. Keeping these run names brief enhances readability in chart legends and tables. For saving hyperparameters, we recommend using the `config` field. +- **notes**: A detailed description of the run, similar to a commit message in Git. Use this argument to capture any context or details that may help you recall the purpose or setup of this run in the future. +- **tags**: A list of tags to label this run in the UI. Tags are helpful for organizing runs or adding temporary identifiers like "baseline" or "production." You can easily add, remove tags, or filter by tags in the UI. If resuming a run, the tags provided here will replace any existing tags. To add tags to a resumed run without overwriting the current tags, use `run.tags += ("new_tag",)` after calling `run = wandb.init()`. +- **config**: Sets `wandb.config`, a dictionary-like object for storing input parameters to your run, such as model hyperparameters or data preprocessing settings. The config appears in the UI in an overview page, allowing you to group, filter, and sort runs based on these parameters. Keys should not contain periods (`.`), and values should be smaller than 10 MB. If a dictionary, `argparse.Namespace`, or `absl.flags.FLAGS` is provided, the key-value pairs will be loaded directly into `wandb.config`. If a string is provided, it is interpreted as a path to a YAML file, from which configuration values will be loaded into `wandb.config`. +- **config_exclude_keys**: A list of specific keys to exclude from `wandb.config`. +- **config_include_keys**: A list of specific keys to include in `wandb.config`. +- **allow_val_change**: Controls whether config values can be modified after their initial set. By default, an exception is raised if a config value is overwritten. For tracking variables that change during training, such as a learning rate, consider using `wandb.log()` instead. By default, this is `False` in scripts and `True` in Notebook environments. +- **group**: Specify a group name to organize individual runs as part of a larger experiment. This is useful for cases like cross-validation or running multiple jobs that train and evaluate a model on different test sets. Grouping allows you to manage related runs collectively in the UI, making it easy to toggle and review results as a unified experiment. +- **job_type**: Specify the type of run, especially helpful when organizing runs within a group as part of a larger experiment. For example, in a group, you might label runs with job types such as "train" and "eval". Defining job types enables you to easily filter and group similar runs in the UI, facilitating direct comparisons. +- **mode**: Specifies how run data is managed, with the following options: +- **force**: Determines if a W&B login is required to run the script. If `True`, the user must be logged in to W&B; otherwise, the script will not proceed. If `False` (default), the script can proceed without a login, switching to offline mode if the user is not logged in. +- **reinit**: Shorthand for the "reinit" setting. Determines the behavior of `wandb.init()` when a run is active. +- **resume**: Controls the behavior when resuming a run with the specified `id`. +- **resume_from**: Specifies a moment in a previous run to resume a run from, using the format `{run_id}?_step={step}`. This allows users to truncate the history logged to a run at an intermediate step and resume logging from that step. The target run must be in the same project. If an `id` argument is also provided, the `resume_from` argument will take precedence. `resume`, `resume_from` and `fork_from` cannot be used together, only one of them can be used at a time. Note that this feature is in beta and may change in the future. +- **fork_from**: Specifies a point in a previous run from which to fork a new run, using the format `{id}?_step={step}`. This creates a new run that resumes logging from the specified step in the target run’s history. The target run must be part of the current project. If an `id` argument is also provided, it must be different from the `fork_from` argument, an error will be raised if they are the same. `resume`, `resume_from` and `fork_from` cannot be used together, only one of them can be used at a time. Note that this feature is in beta and may change in the future. +- **save_code**: Enables saving the main script or notebook to W&B, aiding in experiment reproducibility and allowing code comparisons across runs in the UI. By default, this is disabled, but you can change the default to enable on your settings page. +- **tensorboard**: Deprecated. Use `sync_tensorboard` instead. +- **sync_tensorboard**: Enables automatic syncing of W&B logs from TensorBoard or TensorBoardX, saving relevant event files for viewing in the W&B UI. +- **monitor_gym**: Enables automatic logging of videos of the environment when using OpenAI Gym. +- **settings**: Specifies a dictionary or `wandb.Settings` object with advanced settings for the run. +- **anonymous**: -**Returns:** - A `Run` object. +## Returns: +- ****: A `Run` object. +- **Raises**: +- **Error**: If some unknown or internal error happened during the run initialization. +- **AuthenticationError**: If the user failed to provide valid credentials. +- **CommError**: If there was a problem communicating with the WandB server. +- **UsageError**: If the user provided invalid arguments. +- **KeyboardInterrupt**: If user interrupts the run. -**Raises:** - - - `Error`: If some unknown or internal error happened during the run initialization. - - `AuthenticationError`: If the user failed to provide valid credentials. - - `CommError`: If there was a problem communicating with the WandB server. - - `UsageError`: If the user provided invalid arguments. - - `KeyboardInterrupt`: If user interrupts the run. +## Examples: -**Examples:** - `wandb.init()` returns a `Run` object. Use the run object to log data, save artifacts, and manage the run lifecycle. +`wandb.init()` returns a `Run` object. Use the run object to log data, +save artifacts, and manage the run lifecycle. ```python import wandb @@ -118,4 +115,5 @@ with wandb.init(config=config) as run: acc = 0.95 # Example accuracy loss = 0.05 # Example loss run.log({"accuracy": acc, "loss": loss}) -``` +``` + diff --git a/models/ref/python/functions/login.mdx b/models/ref/python/functions/login.mdx index 6913fca583..39cc25a9ef 100644 --- a/models/ref/python/functions/login.mdx +++ b/models/ref/python/functions/login.mdx @@ -1,69 +1,75 @@ --- -title: login() -namespace: python_sdk_actions -python_object_type: function +title: login +kind: function +namespace: wandb.sdk.wandb_login --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; + -### function `login` ```python -login( - key: 'str | None' = None, - relogin: 'bool | None' = None, - host: 'str | None' = None, - force: 'bool | None' = None, - timeout: 'int | None' = None, - verify: 'bool' = False, - referrer: 'str | None' = None, - anonymous: 'DoNotSet' = -) → bool +key: 'str | None' = None, +relogin: 'bool | None' = None, +host: 'str | None' = None, +force: 'bool | None' = None, +timeout: 'int | None' = None, +verify: 'bool' = False, +referrer: 'str | None' = None, +anonymous: 'DoNotSet' = ``` -Log into W&B. +## Description + +Log into W&B. + +You generally don't have to use this because most W&B methods that need +authentication can log in implicitly. This is the programmatic counterpart +to the `wandb login` CLI. -You generally don't have to use this because most W&B methods that need authentication can log in implicitly. This is the programmatic counterpart to the `wandb login` CLI. +This updates global credentials for the session (affecting all wandb usage +in the current Python process after this call) and possibly the .netrc file. -This updates global credentials for the session (affecting all wandb usage in the current Python process after this call) and possibly the .netrc file. +If the identity_token_file setting is set, like through the +WANDB_IDENTITY_TOKEN_FILE environment variable, then this is a no-op. -If the identity_token_file setting is set, like through the WANDB_IDENTITY_TOKEN_FILE environment variable, then this is a no-op. +Otherwise, if an explicit API key is provided, it is used and written to +the system .netrc file. If no key is provided, but the session is already +authenticated, then the session key is used for verification (if verify +is True) and the .netrc file is not updated. -Otherwise, if an explicit API key is provided, it is used and written to the system .netrc file. If no key is provided, but the session is already authenticated, then the session key is used for verification (if verify is True) and the .netrc file is not updated. +If none of the above is true, then this gets the API key from the first of: -If none of the above is true, then this gets the API key from the first of: +- The WANDB_API_KEY environment variable +- The api_key setting in a system or workspace settings file +- The .netrc file (either ~/.netrc, ~/_netrc or the path specified by the + NETRC environment variable) +- An interactive prompt (if available) +## Args: -- The WANDB_API_KEY environment variable -- The api_key setting in a system or workspace settings file -- The .netrc file (either ~/.netrc, ~/_netrc or the path specified by the NETRC environment variable) -- An interactive prompt (if available) +- **key**: The API key to use. +- **relogin**: If true, get the API key from an interactive prompt, skipping reading .netrc, environment variables, etc. +- **host**: The W&B server URL to connect to. +- **force**: If true, disallows selecting offline mode in the interactive prompt. +- **timeout**: Number of seconds to wait for user input in the interactive prompt. This can be used as a failsafe if an interactive prompt is incorrectly shown in a non-interactive environment. +- **verify**: Verify the credentials with the W&B server and raise an AuthenticationError on failure. +- **referrer**: The referrer to use in the URL login request for analytics. +- **anonymous**: +## Returns: -**Args:** - - - `key`: The API key to use. - - `relogin`: If true, get the API key from an interactive prompt, skipping reading .netrc, environment variables, etc. - - `host`: The W&B server URL to connect to. - - `force`: If true, disallows selecting offline mode in the interactive prompt. - - `timeout`: Number of seconds to wait for user input in the interactive prompt. This can be used as a failsafe if an interactive prompt is incorrectly shown in a non-interactive environment. - - `verify`: Verify the credentials with the W&B server and raise an AuthenticationError on failure. - - `referrer`: The referrer to use in the URL login request for analytics. +- **bool**: If `key` is configured. +- **Raises**: +- **AuthenticationError**: If `api_key` fails verification with the server. +- **UsageError**: If `api_key` cannot be configured and no tty. -**Returns:** - - - `bool`: If `key` is configured. -**Raises:** - - - `AuthenticationError`: If `api_key` fails verification with the server. - - `UsageError`: If `api_key` cannot be configured and no tty. diff --git a/models/ref/python/functions/restore.mdx b/models/ref/python/functions/restore.mdx index cd99d0d333..d76f8ed11f 100644 --- a/models/ref/python/functions/restore.mdx +++ b/models/ref/python/functions/restore.mdx @@ -1,47 +1,47 @@ --- -title: restore() -namespace: python_sdk_actions -python_object_type: function +title: restore +kind: function +namespace: wandb.sdk.wandb_run --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; + -### function `restore` ```python -restore( - name: 'str', - run_path: 'str | None' = None, - replace: 'bool' = False, - root: 'str | None' = None -) → None | TextIO +name: 'str', +run_path: 'str | None' = None, +replace: 'bool' = False, +root: 'str | None' = None ``` -Download the specified file from cloud storage. +## Description + +Download the specified file from cloud storage. + +File is placed into the current directory or run directory. +By default, will only download the file if it doesn't already exist. + +## Args: -File is placed into the current directory or run directory. By default, will only download the file if it doesn't already exist. +- **name**: The name of the file. +- **run_path**: Optional path to a run to pull files from, i.e. `username/project_name/run_id` if wandb.init has not been called, this is required. +- **replace**: Whether to download the file even if it already exists locally +- **root**: The directory to download the file to. Defaults to the current directory or the run directory if wandb.init was called. +## Returns: -**Args:** - - - `name`: The name of the file. - - `run_path`: Optional path to a run to pull files from, i.e. `username/project_name/run_id` if wandb.init has not been called, this is required. - - `replace`: Whether to download the file even if it already exists locally - - `root`: The directory to download the file to. Defaults to the current directory or the run directory if wandb.init was called. +- ****: None if it can't find the file, otherwise a file object open for reading. +- **Raises**: +- **CommError**: If W&B can't connect to the W&B backend. +- **ValueError**: If the file is not found or can't find run_path. -**Returns:** - None if it can't find the file, otherwise a file object open for reading. -**Raises:** - - - `CommError`: If W&B can't connect to the W&B backend. - - `ValueError`: If the file is not found or can't find run_path. diff --git a/models/ref/python/functions/setup.mdx b/models/ref/python/functions/setup.mdx index dd0008441f..f168e2296a 100644 --- a/models/ref/python/functions/setup.mdx +++ b/models/ref/python/functions/setup.mdx @@ -1,41 +1,50 @@ --- -title: setup() -namespace: python_sdk_actions -python_object_type: function +title: setup +kind: function +namespace: wandb.sdk.wandb_setup --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; + -### function `setup` ```python -setup(settings: 'Settings | None' = None) → _WandbSetup +settings: 'Settings | None' = None ``` -Prepares W&B for use in the current process and its children. +## Description + +Prepares W&B for use in the current process and its children. + +You can usually ignore this as it is implicitly called by `wandb.init()`. + +When using wandb in multiple processes, calling `wandb.setup()` +in the parent process before starting child processes may improve +performance and resource utilization. -You can usually ignore this as it is implicitly called by `wandb.init()`. +Note that `wandb.setup()` modifies `os.environ`, and it is important +that child processes inherit the modified environment variables. -When using wandb in multiple processes, calling `wandb.setup()` in the parent process before starting child processes may improve performance and resource utilization. +See also `wandb.teardown()`. -Note that `wandb.setup()` modifies `os.environ`, and it is important that child processes inherit the modified environment variables. +## Args: -See also `wandb.teardown()`. +- **settings**: Configuration settings to apply globally. These can be overridden by subsequent `wandb.init()` calls. +## Returns: -**Args:** - - - `settings`: Configuration settings to apply globally. These can be overridden by subsequent `wandb.init()` calls. +- **return**: _WandbSetup -**Example:** - ```python + +## Examples: + +```python import multiprocessing import wandb @@ -43,8 +52,8 @@ import wandb def run_experiment(params): with wandb.init(config=params): - # Run experiment - pass + # Run experiment + pass if __name__ == "__main__": @@ -53,21 +62,22 @@ if __name__ == "__main__": # Define experiment parameters experiment_params = [ - {"learning_rate": 0.01, "epochs": 10}, - {"learning_rate": 0.001, "epochs": 20}, + {"learning_rate": 0.01, "epochs": 10}, + {"learning_rate": 0.001, "epochs": 20}, ] # Start multiple processes, each running a separate experiment processes = [] for params in experiment_params: - p = multiprocessing.Process(target=run_experiment, args=(params,)) - p.start() - processes.append(p) + p = multiprocessing.Process(target=run_experiment, args=(params,)) + p.start() + processes.append(p) # Wait for all processes to complete for p in processes: - p.join() + p.join() # Optional: Explicitly shut down the backend wandb.teardown() -``` +``` + diff --git a/models/ref/python/functions/sweep.mdx b/models/ref/python/functions/sweep.mdx index fb9341891b..113926838d 100644 --- a/models/ref/python/functions/sweep.mdx +++ b/models/ref/python/functions/sweep.mdx @@ -1,45 +1,50 @@ --- -title: sweep() -namespace: python_sdk_actions -python_object_type: function +title: sweep +kind: function +namespace: wandb.sdk.wandb_sweep --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; + -### function `sweep` ```python -sweep( - sweep: 'dict | Callable', - entity: 'str | None' = None, - project: 'str | None' = None, - prior_runs: 'list[str] | None' = None -) → str +sweep: 'dict | Callable', +entity: 'str | None' = None, +project: 'str | None' = None, +prior_runs: 'list[str] | None' = None ``` -Initialize a hyperparameter sweep. +## Description + +Initialize a hyperparameter sweep. + +Search for hyperparameters that optimizes a cost function +of a machine learning model by testing various combinations. + +Make note the unique identifier, `sweep_id`, that is returned. +At a later step provide the `sweep_id` to a sweep agent. + +See [Sweep configuration structure](https://docs.wandb.ai/models/sweeps/define-sweep-configuration) +for information on how to define your sweep. + +## Args: + +- **sweep**: The configuration of a hyperparameter search. (or configuration generator). If you provide a callable, ensure that the callable does not take arguments and that it returns a dictionary that conforms to the W&B sweep config spec. +- **entity**: The username or team name where you want to send W&B runs created by the sweep to. Ensure that the entity you specify already exists. If you don't specify an entity, the run will be sent to your default entity, which is usually your username. +- **project**: The name of the project where W&B runs created from the sweep are sent to. If the project is not specified, the run is sent to a project labeled 'Uncategorized'. +- **prior_runs**: The run IDs of existing runs to add to this sweep. -Search for hyperparameters that optimizes a cost function of a machine learning model by testing various combinations. -Make note the unique identifier, `sweep_id`, that is returned. At a later step provide the `sweep_id` to a sweep agent. +## Returns: -See [Sweep configuration structure](https://docs.wandb.ai/models/sweeps/define-sweep-configuration) for information on how to define your sweep. +- **str**: A unique identifier for the sweep. -**Args:** - - - `sweep`: The configuration of a hyperparameter search. (or configuration generator). If you provide a callable, ensure that the callable does not take arguments and that it returns a dictionary that conforms to the W&B sweep config spec. - - `entity`: The username or team name where you want to send W&B runs created by the sweep to. Ensure that the entity you specify already exists. If you don't specify an entity, the run will be sent to your default entity, which is usually your username. - - `project`: The name of the project where W&B runs created from the sweep are sent to. If the project is not specified, the run is sent to a project labeled 'Uncategorized'. - - `prior_runs`: The run IDs of existing runs to add to this sweep. -**Returns:** - - - `str`: A unique identifier for the sweep. diff --git a/models/ref/python/functions/teardown.mdx b/models/ref/python/functions/teardown.mdx index e996be6fe7..4adac079c9 100644 --- a/models/ref/python/functions/teardown.mdx +++ b/models/ref/python/functions/teardown.mdx @@ -1,23 +1,43 @@ --- -title: teardown() -namespace: python_sdk_actions -python_object_type: function +title: teardown +kind: function +namespace: wandb.sdk.wandb_setup --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; + -### function `teardown` ```python -teardown(exit_code: 'int | None' = None) → None +exit_code: 'int | None' = None ``` -Waits for W&B to finish and frees resources. +## Description + +Waits for W&B to finish and frees resources. + +Completes any runs that were not explicitly finished +using `run.finish()` and waits for all data to be uploaded. + +It is recommended to call this at the end of a session +that used `wandb.setup()`. It is invoked automatically +in an `atexit` hook, but this is not reliable in certain setups +such as when using Python's `multiprocessing` module. + +## Args: + +- **exit_code**: + + +## Returns: + +- **return**: None + + + + -Completes any runs that were not explicitly finished using `run.finish()` and waits for all data to be uploaded. -It is recommended to call this at the end of a session that used `wandb.setup()`. It is invoked automatically in an `atexit` hook, but this is not reliable in certain setups such as when using Python's `multiprocessing` module. diff --git a/models/ref/python/public-api/api.mdx b/models/ref/python/public-api/api.mdx index a6054f5e4c..1e82228637 100644 --- a/models/ref/python/public-api/api.mdx +++ b/models/ref/python/public-api/api.mdx @@ -1,1633 +1,296 @@ --- title: Api -namespace: public_apis_namespace -python_object_type: class +kind: class +namespace: wandb.apis.public.api --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - - - - - - -## class `Api` -Used for querying the W&B server. - - - -**Examples:** - ```python -import wandb - -wandb.Api() -``` - -### method `Api.__init__` - -```python -__init__( - overrides: 'dict[str, Any] | None' = None, - timeout: 'int | None' = None, - api_key: 'str | None' = None -) → None -``` - -Initialize the API. - - - -**Args:** - - - `overrides`: You can set `base_url` if you are - - `using a W&B server other than `https`: //api.wandb.ai`. You can also set defaults for `entity`, `project`, and `run`. - - `timeout`: HTTP timeout in seconds for API requests. If not specified, the default timeout will be used. - - `api_key`: API key to use for authentication. If not provided, the API key from the current environment or configuration will be used. Prompts for an API key if none is provided or configured in the environment. - - ---- - -### property Api.client - -Returns the client object. - - - -**Returns:** - - `RetryingClient`: The client property value. ---- - -### property Api.default_entity - -Returns the default W&B entity. - - - -**Returns:** - - `str | None`: The default_entity property value. ---- - -### property Api.user_agent - -Returns W&B public user agent. - - - -**Returns:** - - `str`: The user_agent property value. ---- - -### property Api.viewer - -Returns the viewer object. - - - -**Raises:** - - - `ValueError`: If viewer data is not able to be fetched from W&B. - - `requests.RequestException`: If an error occurs while making the graphql request. - - - - - -**Returns:** - - `User`: The viewer property value. ---- - -### method `Api.artifact` - -```python -artifact(name: 'str', type: 'str | None' = None) -``` - -Returns a single artifact. - - - -**Args:** - - - `name`: The artifact's name. The name of an artifact resembles a filepath that consists, at a minimum, the name of the project the artifact was logged to, the name of the artifact, and the artifact's version or alias. Optionally append the entity that logged the artifact as a prefix followed by a forward slash. If no entity is specified in the name, the Run or API setting's entity is used. - - `type`: The type of artifact to fetch. - - - -**Returns:** - An `Artifact` object. - - - -**Raises:** - - - `ValueError`: If the artifact name is not specified. - - `ValueError`: If the artifact type is specified but does not match the type of the fetched artifact. - - - -**Examples:** - In the following code snippets "entity", "project", "artifact", "version", and "alias" are placeholders for your W&B entity, name of the project the artifact is in, the name of the artifact, and artifact's version, respectively. - -```python -import wandb - -# Specify the project, artifact's name, and the artifact's alias -wandb.Api().artifact(name="project/artifact:alias") - -# Specify the project, artifact's name, and a specific artifact version -wandb.Api().artifact(name="project/artifact:version") - -# Specify the entity, project, artifact's name, and the artifact's alias -wandb.Api().artifact(name="entity/project/artifact:alias") - -# Specify the entity, project, artifact's name, and a specific artifact version -wandb.Api().artifact(name="entity/project/artifact:version") -``` - - - -**Note:** - -> This method is intended for external use only. Do not call `api.artifact()` within the wandb repository code. - ---- - -### method `Api.artifact_collection` - -```python -artifact_collection(type_name: 'str', name: 'str') → ArtifactCollection -``` - -Returns a single artifact collection by type. - -You can use the returned `ArtifactCollection` object to retrieve information about specific artifacts in that collection, and more. - - - -**Args:** - - - `type_name`: The type of artifact collection to fetch. - - `name`: An artifact collection name. Optionally append the entity that logged the artifact as a prefix followed by a forward slash. - - - -**Returns:** - An `ArtifactCollection` object. - - - -**Examples:** - In the following code snippet "type", "entity", "project", and "artifact_name" are placeholders for the collection type, your W&B entity, name of the project the artifact is in, and the name of the artifact, respectively. - -```python -import wandb - -collections = wandb.Api().artifact_collection( - type_name="type", name="entity/project/artifact_name" -) - -# Get the first artifact in the collection -artifact_example = collections.artifacts()[0] - -# Download the contents of the artifact to the specified root directory. -artifact_example.download() -``` - ---- - -### method `Api.artifact_collection_exists` - -```python -artifact_collection_exists(name: 'str', type: 'str') → bool -``` - -Whether an artifact collection exists within a specified project and entity. - - - -**Args:** - - - `name`: An artifact collection name. Optionally append the entity that logged the artifact as a prefix followed by a forward slash. If entity or project is not specified, infer the collection from the override params if they exist. Otherwise, entity is pulled from the user settings and project will default to "uncategorized". - - `type`: The type of artifact collection. - - - -**Returns:** - True if the artifact collection exists, False otherwise. - - - -**Examples:** - In the following code snippet "type", and "collection_name" refer to the type of the artifact collection and the name of the collection, respectively. - -```python -import wandb - -wandb.Api.artifact_collection_exists(type="type", name="collection_name") -``` - ---- - -### method `Api.artifact_collections` - -```python -artifact_collections( - project_name: 'str', - type_name: 'str', - per_page: 'int' = 50, - start: 'str | None' = None -) → ArtifactCollections -``` - -Returns a collection of matching artifact collections. - - - -**Args:** - - - `project_name`: The name of the project to filter on. - - `type_name`: The name of the artifact type to filter on. - - `per_page`: Sets the page size for query pagination. Usually there is no reason to change this. - - `start`: Pagination cursor for resuming a past query, captured from a previous paginator's `.cursor` attribute. - - - -**Returns:** - An iterable `ArtifactCollections` object. - ---- - -### method `Api.artifact_exists` - -```python -artifact_exists(name: 'str', type: 'str | None' = None) → bool -``` - -Whether an artifact version exists within the specified project and entity. - - - -**Args:** - - - `name`: The name of artifact. Add the artifact's entity and project as a prefix. Append the version or the alias of the artifact with a colon. If the entity or project is not specified, W&B uses override parameters if populated. Otherwise, the entity is pulled from the user settings and the project is set to "Uncategorized". - - `type`: The type of artifact. - - - -**Returns:** - True if the artifact version exists, False otherwise. - - - -**Examples:** - In the following code snippets "entity", "project", "artifact", "version", and "alias" are placeholders for your W&B entity, name of the project the artifact is in, the name of the artifact, and artifact's version, respectively. - -```python -import wandb - -wandb.Api().artifact_exists("entity/project/artifact:version") -wandb.Api().artifact_exists("entity/project/artifact:alias") -``` - ---- - -### method `Api.artifact_type` - -```python -artifact_type(type_name: 'str', project: 'str | None' = None) → ArtifactType -``` - -Returns the matching `ArtifactType`. - - - -**Args:** - - - `type_name`: The name of the artifact type to retrieve. - - `project`: If given, a project name or path to filter on. - - - -**Returns:** - An `ArtifactType` object. - ---- - -### method `Api.artifact_types` - -```python -artifact_types( - project: 'str | None' = None, - start: 'str | None' = None -) → ArtifactTypes -``` - -Returns a collection of matching artifact types. - - - -**Args:** - - - `project`: The project name or path to filter on. - - `start`: Pagination cursor for resuming a past query, captured from a previous paginator's `.cursor` attribute. - - - -**Returns:** - An iterable `ArtifactTypes` object. - ---- - -### method `Api.artifact_versions` - -```python -artifact_versions(type_name, name, per_page=50) -``` - -Deprecated. Use `Api.artifacts(type_name, name)` method instead. - ---- - -### method `Api.artifacts` - -```python -artifacts( - type_name: 'str', - name: 'str', - per_page: 'int' = 50, - tags: 'list[str] | None' = None, - start: 'str | None' = None -) → Artifacts -``` - -Return an `Artifacts` collection. - - - -**Args:** - - - `type_name`: The type of artifacts to fetch. - - `name`: The artifact's collection name. Optionally append the entity that logged the artifact as a prefix followed by a forward slash. - - `per_page`: Sets the page size for query pagination. Usually there is no reason to change this. - - `tags`: Only return artifacts with all of these tags. - - `start`: Pagination cursor for resuming a past query, captured from a previous paginator's `.cursor` attribute. - - - -**Returns:** - An iterable `Artifacts` object. - - - -**Examples:** - In the following code snippet, "type", "entity", "project", and "artifact_name" are placeholders for the artifact type, W&B entity, name of the project the artifact was logged to, and the name of the artifact, respectively. - -```python -import wandb - -wandb.Api().artifacts(type_name="type", name="entity/project/artifact_name") -``` - -Pause iteration and resume later from the same position by saving the paginator's `.cursor` and passing it as `start=`: - -```python -from itertools import islice - -import wandb - -api = wandb.Api() - -# Consume the first page of results, then save the cursor. -page_size = 10 -artifacts = api.artifacts( - type_name="type", - name="entity/project/artifact_name", - per_page=page_size, -) -first_page = list(islice(artifacts, page_size)) - -saved_cursor = artifacts.cursor - -# Later (e.g. in a new process), resume iteration from the saved cursor. -remaining_artifacts = api.artifacts( - type_name="type", - name="entity/project/artifact_name", - per_page=page_size, - start=saved_cursor, -) -``` - ---- - -### method `Api.automation` - -```python -automation(name: 'str', entity: 'str | None' = None) → Automation -``` - -Returns the only Automation matching the parameters. - - - -**Args:** - - - `name`: The name of the automation to fetch. - - `entity`: The entity to fetch the automation for. - - - -**Raises:** - - - `ValueError`: If zero or multiple Automations match the search criteria. - - - -**Examples:** - Get an existing automation named "my-automation": - -```python -import wandb - -api = wandb.Api() -automation = api.automation(name="my-automation") -``` - -Get an existing automation named "other-automation", from the entity "my-team": - -```python -automation = api.automation(name="other-automation", entity="my-team") -``` - ---- - -### method `Api.automations` - -```python -automations( - entity: 'str | None' = None, - name: 'str | None' = None, - per_page: 'int' = 50, - start: 'str | None' = None -) → Iterator[Automation] -``` - -Returns an iterator over all Automations that match the given parameters. - -If no parameters are provided, the returned iterator will contain all Automations that the user has access to. - - - -**Args:** - - - `entity`: The entity to fetch the automations for. - - `name`: The name of the automation to fetch. - - `per_page`: The number of automations to fetch per page. Defaults to 50. Usually there is no reason to change this. - - `start`: Pagination cursor for resuming a past query, captured from a previous paginator's `.cursor` attribute. - - - -**Returns:** - A list of automations. - - - -**Examples:** - Fetch all existing automations for the entity "my-team": - -```python -import wandb - -api = wandb.Api() -automations = api.automations(entity="my-team") -``` - ---- - -### method `Api.create_automation` - -```python -create_automation( - obj: 'NewAutomation', - fetch_existing: 'bool' = False, - **kwargs: 'Unpack[WriteAutomationsKwargs]' -) → Automation -``` - -Create a new Automation. - - - -**Args:** - obj: The automation to create. fetch_existing: If True, and a conflicting automation already exists, attempt to fetch the existing automation instead of raising an error. **kwargs: Any additional values to assign to the automation before creating it. If given, these will override any values that may already be set on the automation: - - `name`: The name of the automation. - - `description`: The description of the automation. - - `enabled`: Whether the automation is enabled. - - `scope`: The scope of the automation. - - `event`: The event that triggers the automation. - - `action`: The action that is triggered by the automation. - - - -**Returns:** - The saved Automation. - - - -**Examples:** - Create a new automation named "my-automation" that sends a Slack notification when a run within a specific project logs a metric exceeding a custom threshold: - -```python -import wandb -from wandb.automations import OnRunMetric, RunEvent, SendNotification - -api = wandb.Api() - -project = api.project("my-project", entity="my-team") - -# Use the first Slack integration for the team -slack_hook = next(api.slack_integrations(entity="my-team")) - -event = OnRunMetric( - scope=project, - filter=RunEvent.metric("custom-metric") > 10, -) -action = SendNotification.from_integration(slack_hook) - -automation = api.create_automation( - event >> action, - name="my-automation", - description="Send a Slack message whenever 'custom-metric' exceeds 10.", -) -``` - ---- - -### method `Api.create_custom_chart` - -```python -create_custom_chart( - entity: 'str', - name: 'str', - display_name: 'str', - spec_type: "Literal['vega2']", - access: "Literal['private', 'public']", - spec: 'str | dict' -) → str -``` - -Create a custom chart preset and return its id. - - - -**Args:** - - - `entity`: The entity (user or team) that owns the chart - - `name`: Unique identifier for the chart preset - - `display_name`: Human-readable name shown in the UI - - `spec_type`: Type of specification. Must be "vega2" for Vega-Lite v2 specifications. - - `access`: Access level for the chart: - - "private": Chart is only accessible to the entity that created it - - "public": Chart is publicly accessible - - `spec`: The Vega/Vega-Lite specification as a dictionary or JSON string - - - -**Returns:** - The ID of the created chart preset in the format "entity/name" - - - -**Raises:** - - - `wandb.Error`: If chart creation fails - - `UnsupportedError`: If the server doesn't support custom charts - - - -**Example:** - ```python - import wandb - - api = wandb.Api() - - # Define a simple bar chart specification - vega_spec = { - "$schema": "https://vega.github.io/schema/vega-lite/v6.json", - "mark": "bar", - "data": {"name": "wandb"}, - "encoding": { - "x": {"field": "${field:x}", "type": "ordinal"}, - "y": {"field": "${field:y}", "type": "quantitative"}, - }, - } - - # Create the custom chart - chart_id = api.create_custom_chart( - entity="my-team", - name="my-bar-chart", - display_name="My Custom Bar Chart", - spec_type="vega2", - access="private", - spec=vega_spec, - ) - - # Use with wandb.plot_table() - chart = wandb.plot_table( - vega_spec_name=chart_id, - data_table=my_table, - fields={"x": "category", "y": "value"}, - ) - ``` - ---- - -### method `Api.create_project` - -```python -create_project(name: 'str', entity: 'str') → None -``` - -Create a new project. - - - -**Args:** - - - `name`: The name of the new project. - - `entity`: The entity of the new project. - ---- - -### method `Api.create_registry` - -```python -create_registry( - name: 'str', - visibility: "Literal['organization', 'restricted']", - organization: 'str | None' = None, - description: 'str | None' = None, - artifact_types: 'list[str] | None' = None -) → Registry -``` - -Create a new registry. - - - -**Args:** - - - `name`: The name of the registry. Name must be unique within the organization. - - `visibility`: The visibility of the registry. - - `organization`: Anyone in the organization can view this registry. You can edit their roles later from the settings in the UI. - - `restricted`: Only invited members via the UI can access this registry. Public sharing is disabled. - - `organization`: The organization of the registry. If no organization is set in the settings, the organization will be fetched from the entity if the entity only belongs to one organization. - - `description`: The description of the registry. - - `artifact_types`: The accepted artifact types of the registry. A type is no - - `more than 128 characters and do not include characters `/` or ``: `. If not specified, all types are accepted. Allowed types added to the registry cannot be removed later. - - - -**Returns:** - A registry object. - - - -**Examples:** - ```python -import wandb - -api = wandb.Api() -registry = api.create_registry( - name="my-registry", - visibility="restricted", - organization="my-org", - description="This is a test registry", - artifact_types=["model"], -) -``` - ---- - -### method `Api.create_run` - -```python -create_run( - run_id: 'str | None' = None, - project: 'str | None' = None, - entity: 'str | None' = None -) → public.Run -``` - -Create a new run. - - - -**Args:** - - - `run_id`: The ID to assign to the run. If not specified, W&B creates a random ID. - - `project`: The project where to log the run to. If no project is specified, log the run to a project called "Uncategorized". - - `entity`: The entity that owns the project. If no entity is specified, log the run to the default entity. - - - -**Returns:** - The newly created `Run`. - ---- - -### method `Api.create_run_queue` - -```python -create_run_queue( - name: 'str', - type: 'public.RunQueueResourceType', - entity: 'str | None' = None, - prioritization_mode: 'public.RunQueuePrioritizationMode | None' = None, - config: 'dict | None' = None, - template_variables: 'dict | None' = None -) → public.RunQueue -``` - -Create a new run queue in W&B Launch. - - - -**Args:** - - - `name`: Name of the queue to create - - `type`: Type of resource to be used for the queue. One of "local-container", "local-process", "kubernetes","sagemaker", or "gcp-vertex". - - `entity`: Name of the entity to create the queue. If `None`, use the configured or default entity. - - `prioritization_mode`: Version of prioritization to use. Either "V0" or `None`. - - `config`: Default resource configuration to be used for the queue. Use handlebars (eg. `{{var}}`) to specify template variables. - - `template_variables`: A dictionary of template variable schemas to use with the config. - - - -**Returns:** - The newly created `RunQueue`. - - - -**Raises:** - `ValueError` if any of the parameters are invalid `wandb.Error` on wandb API errors - ---- - -### method `Api.create_team` - -```python -create_team(team: 'str', admin_username: 'str | None' = None) → Team -``` - -Create a new team. - - - -**Args:** - - - `team`: The name of the team - - `admin_username`: Username of the admin user of the team. Defaults to the current user. - - - -**Returns:** - A `Team` object. - ---- - -### method `Api.create_user` - -```python -create_user(email: 'str', admin: 'bool | None' = False) → User -``` - -Create a new user. - - - -**Args:** - - - `email`: The email address of the user. - - `admin`: Set user as a global instance administrator. - - - -**Returns:** - A `User` object. - ---- - -### method `Api.delete_automation` - -```python -delete_automation(obj: 'Automation | str') → Literal[True] -``` - -Delete an automation. - - - -**Args:** - - - `obj`: The automation to delete, or its ID. - - - -**Returns:** - True if the automation was deleted successfully. - ---- - -### method `Api.flush` -```python -flush() -``` - -Flush the local cache. - -The api object keeps a local cache of runs, so if the state of the run may change while executing your script you must clear the local cache with `api.flush()` to get the latest values associated with the run. - ---- - -### method `Api.from_path` - -```python -from_path(path: 'str') -``` - -Return a run, sweep, project or report from a path. - - - -**Args:** - - - `path`: The path to the project, run, sweep or report - - - -**Returns:** - A `Project`, `Run`, `Sweep`, or `BetaReport` instance. - - - -**Raises:** - `wandb.Error` if path is invalid or the object doesn't exist. - - - -**Examples:** - In the following code snippets "project", "team", "run_id", "sweep_id", and "report_name" are placeholders for the project, team, run ID, sweep ID, and the name of a specific report, respectively. - -```python -import wandb - -api = wandb.Api() - -project = api.from_path("project") -team_project = api.from_path("team/project") -run = api.from_path("team/project/runs/run_id") -sweep = api.from_path("team/project/sweeps/sweep_id") -report = api.from_path("team/project/reports/report_name") -``` - ---- - -### method `Api.integrations` - -```python -integrations( - entity: 'str | None' = None, - per_page: 'int' = 50, - start: 'str | None' = None -) → Iterator[Integration] -``` - -Return an iterator of all integrations for an entity. - - - -**Args:** - - - `entity`: The entity (e.g. team name) for which to fetch integrations. If not provided, the user's default entity will be used. - - `per_page`: Number of integrations to fetch per page. Defaults to 50. Usually there is no reason to change this. - - - -**Yields:** - - - `Iterator[SlackIntegration | WebhookIntegration]`: An iterator of any supported integrations. - ---- - -### method `Api.job` - -```python -job(name: 'str | None', path: 'str | None' = None) → public.Job -``` - -Return a `Job` object. - - - -**Args:** - - - `name`: The name of the job. - - `path`: The root path to download the job artifact. - - - -**Returns:** - A `Job` object. - ---- - -### method `Api.list_jobs` - -```python -list_jobs(entity: 'str', project: 'str') → list[dict[str, Any]] -``` - -Return a list of jobs, if any, for the given entity and project. - - - -**Args:** - - - `entity`: The entity for the listed jobs. - - `project`: The project for the listed jobs. - - - -**Returns:** - A list of matching jobs. - ---- - -### method `Api.project` - -```python -project(name: 'str', entity: 'str | None' = None) → public.Project -``` - -Return the `Project` with the given name (and entity, if given). - - - -**Args:** - - - `name`: The project name. - - `entity`: Name of the entity requested. If None, will fall back to the default entity passed to `Api`. If no default entity, will raise a `ValueError`. - - - -**Returns:** - A `Project` object. - ---- - -### method `Api.projects` - -```python -projects(entity: 'str | None' = None, per_page: 'int' = 200) → public.Projects -``` - -Get projects for a given entity. - - - -**Args:** - - - `entity`: Name of the entity requested. If None, will fall back to the default entity passed to `Api`. If no default entity, will raise a `ValueError`. - - `per_page`: Sets the page size for query pagination. Usually there is no reason to change this. - - - -**Returns:** - A `Projects` object which is an iterable collection of `Project`objects. - ---- - -### method `Api.queued_run` - -```python -queued_run( - entity: 'str', - project: 'str', - queue_name: 'str', - run_queue_item_id: 'str', - project_queue=None, - priority=None -) -``` - -Return a single queued run based on the path. - -Parses paths of the form `entity/project/queue_id/run_queue_item_id`. - ---- - -### method `Api.registries` - -```python -registries( - organization: 'str | None' = None, - filter: 'dict[str, Any] | None' = None, - per_page: 'int' = 100, - start: 'str | None' = None -) → Registries -``` - -Returns a lazy iterator of `Registry` objects. - -Use the iterator to search and filter registries, collections, or artifact versions across your organization's registry. - - - -**Args:** - - - `organization`: (str, optional) The organization of the registry to fetch. If not specified, use the organization specified in the user's settings. - - `filter`: (dict, optional) MongoDB-style filter to apply to each object in the lazy registry iterator. Fields available to filter for registries are `name`, `description`, `created_at`, `updated_at`. Fields available to filter for collections are `name`, `tag`, `description`, `created_at`, `updated_at` Fields available to filter for versions are `tag`, `alias`, `created_at`, `updated_at`, `metadata` - - `per_page`: Sets the page size for query pagination. - - `start`: Pagination cursor for resuming a past query, captured from a previous paginator's `.cursor` attribute. - - - -**Returns:** - A lazy iterator of `Registry` objects. - - - -**Examples:** - Find all registries with the names that contain "model" - -```python -import wandb - -api = wandb.Api() # specify an org if your entity belongs to multiple orgs -api.registries(filter={"name": {"$regex": "model"}}) -``` - -Find all collections in the registries with the name "my_collection" and the tag "my_tag" - -```python -api.registries().collections(filter={"name": "my_collection", "tag": "my_tag"}) -``` - -Find all artifact versions in the registries with a collection name that contains "my_collection" and a version that has the alias "best" - -```python -api.registries().collections( - filter={"name": {"$regex": "my_collection"}} -).versions(filter={"alias": "best"}) -``` - -Find all artifact versions in the registries that contain "model" and have the tag "prod" or alias "best" - -```python -api.registries(filter={"name": {"$regex": "model"}}).versions( - filter={"$or": [{"tag": "prod"}, {"alias": "best"}]} -) -``` - -Pause iteration and resume later from the same position by saving the paginator's `.cursor` and passing it as `start=`: - -```python -from itertools import islice - -import wandb - -api = wandb.Api() - -# Consume the first page of results, then save the cursor. -page_size = 10 -registries = api.registries(per_page=page_size) -first_page = list(islice(registries, page_size)) +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; -saved_cursor = registries.cursor -# Later (e.g. in a new process), resume iteration from the saved cursor. -remaining_registries = api.registries(per_page=page_size, start=saved_cursor) -``` + ---- -### method `Api.registry` ```python -registry(name: 'str', organization: 'str | None' = None) → Registry +overrides: 'dict[str, Any] | None' = None, +timeout: 'int | None' = None, +api_key: 'str | None' = None ``` -Return a registry given a registry name. - - - -**Args:** - - - `name`: The name of the registry. This is without the `wandb-registry-` prefix. - - `organization`: The organization of the registry. If no organization is set in the settings, the organization will be fetched from the entity if the entity only belongs to one organization. - +## Description +Used for querying the W&B server. -**Returns:** - A registry object. - - - -**Examples:** - Fetch and update a registry - -```python -import wandb - -api = wandb.Api() -registry = api.registry(name="my-registry", organization="my-org") -registry.description = "This is an updated description" -registry.save() -``` - ---- - -### method `Api.reports` +## Examples: ```python -reports( - path: 'str' = '', - name: 'str | None' = None, - per_page: 'int' = 50 -) → public.Reports -``` - -Get reports for a given project path. - -Note: `wandb.Api.reports()` API is in beta and will likely change in future releases. - - - -**Args:** - - - `path`: The path to the project the report resides in. Specify the entity that created the project as a prefix followed by a forward slash. - - `name`: Name of the report requested. - - `per_page`: Sets the page size for query pagination. Usually there is no reason to change this. - - - -**Returns:** - A `Reports` object which is an iterable collection of `BetaReport` objects. - - - -**Examples:** - ```python import wandb -wandb.Api.reports("entity/project") -``` - ---- - -### method `Api.run` - -```python -run(path='') -``` - -Return a single run by parsing path in the form `entity/project/run_id`. - - - -**Args:** - - - `path`: Path to run in the form `entity/project/run_id`. If `api.entity` is set, this can be in the form `project/run_id` and if `api.project` is set this can just be the run_id. - - - -**Returns:** - A `Run` object. - ---- - -### method `Api.run_queue` - -```python -run_queue(entity: 'str', name: 'str') -``` - -Return the named `RunQueue` for entity. - -See `Api.create_run_queue` for more information on how to create a run queue. - ---- - -### method `Api.runs` - -```python -runs( - path: 'str | None' = None, - filters: 'dict[str, Any] | None' = None, - order: 'str' = '+created_at', - per_page: 'int' = 50, - include_sweeps: 'bool' = True, - lazy: 'bool' = True -) +wandb.Api() ``` -Returns a `Runs` object, which lazily iterates over `Run` objects. - -Fields you can filter by include: -- `createdAt`: The timestamp when the run was created. (in ISO 8601 format, e.g. "2023-01-01T12:00:00Z") -- `displayName`: The human-readable display name of the run. (e.g. "eager-fox-1") -- `duration`: The total runtime of the run in seconds. -- `group`: The group name used to organize related runs together. -- `host`: The hostname where the run was executed. -- `jobType`: The type of job or purpose of the run. -- `name`: The unique identifier of the run. (e.g. "a1b2cdef") -- `state`: The current state of the run. -- `tags`: The tags associated with the run. -- `username`: The username of the user who initiated the run - -Additionally, you can filter by items in the run config or summary metrics. Such as `config.experiment_name`, `summary_metrics.loss`, etc. - -For more complex filtering, you can use MongoDB query operators. For details, see: https://docs.mongodb.com/manual/reference/operator/query The following operations are supported: -- `$and` -- `$or` -- `$nor` -- `$eq` -- `$ne` -- `$gt` -- `$gte` -- `$lt` -- `$lte` -- `$in` -- `$nin` -- `$exists` -- `$regex` - - - - - - - -**Args:** - - - `path`: (str) path to project, should be in the form: "entity/project" - - `filters`: (dict) queries for specific runs using the MongoDB query language. You can filter by run properties such as config.key, summary_metrics.key, state, entity, createdAt, etc. - - `For example`: `{"config.experiment_name": "foo"}` would find runs with a config entry of experiment name set to "foo" - - `order`: (str) Order can be `created_at`, `heartbeat_at`, `config.*.value`, or `summary_metrics.*`. If you prepend order with a + order is ascending (default). If you prepend order with a - order is descending. The default order is run.created_at from oldest to newest. - - `per_page`: (int) Sets the page size for query pagination. - - `include_sweeps`: (bool) Whether to include the sweep runs in the results. - - `lazy`: (bool) Whether to use lazy loading for faster performance. When True (default), only essential run metadata is loaded initially. Heavy fields like config, summaryMetrics, and systemMetrics are loaded on-demand when accessed. Set to False for full data upfront. - - - -**Returns:** - A `Runs` object, which is an iterable collection of `Run` objects. - - +## Args: -**Examples:** - ```python -import wandb -from wandb.apis.public import Api - -# Find runs in project where config.experiment_name has been set to "foo" -Api.runs(path="my_entity/project", filters={"config.experiment_name": "foo"}) -``` - -```python -# Find runs in project where config.experiment_name has been set to "foo" or "bar" -Api.runs( - path="my_entity/project", - filters={ - "$or": [ - {"config.experiment_name": "foo"}, - {"config.experiment_name": "bar"}, - ] - }, -) -``` - -```python -# Find runs in project where config.experiment_name matches a regex -# (anchors are not supported) -Api.runs( - path="my_entity/project", - filters={"config.experiment_name": {"$regex": "b.*"}}, -) -``` - -```python -# Find runs in project where the run name matches a regex -# (anchors are not supported) -Api.runs( - path="my_entity/project", filters={"display_name": {"$regex": "^foo.*"}} -) -``` +- **overrides**: You can set `base_url` if you are +- **timeout**: HTTP timeout in seconds for API requests. If not specified, the default timeout will be used. +- **api_key**: API key to use for authentication. If not provided, the API key from the current environment or configuration will be used. Prompts for an API key if none is provided or configured in the environment. -```python -# Find runs in project sorted by ascending loss -Api.runs(path="my_entity/project", order="+summary_metrics.loss") -``` - ---- - -### method `Api.slack_integrations` -```python -slack_integrations( - entity: 'str | None' = None, - per_page: 'int' = 50, - start: 'str | None' = None -) → Iterator[SlackIntegration] -``` +## Properties: -Returns an iterator of Slack integrations for an entity. +### client +Returns the client object. +### user_agent -**Args:** - - - `entity`: The entity (e.g. team name) for which to fetch integrations. If not provided, the user's default entity will be used. - - `per_page`: Number of integrations to fetch per page. Defaults to 50. Usually there is no reason to change this. +Returns W&B public user agent. +### default_entity +Returns the default W&B entity. -**Yields:** - - - `Iterator[SlackIntegration]`: An iterator of Slack integrations. +### viewer +Returns the viewer object. +Raises: + ValueError: If viewer data is not able to be fetched from W&B. + requests.RequestException: If an error occurs while making the graphql request. -**Examples:** - Get all registered Slack integrations for the team "my-team": -```python -import wandb -api = wandb.Api() -slack_integrations = api.slack_integrations(entity="my-team") -``` +## Methods: -Find only Slack integrations that post to channel names starting with "team-alerts-": +### artifact -```python -slack_integrations = api.slack_integrations(entity="my-team") -team_alert_integrations = [ - ig - for ig in slack_integrations - if ig.channel_name.startswith("team-alerts-") -] -``` +Returns a single artifact. ---- +### artifact_collection -### method `Api.sweep` +Returns a single artifact collection by type. -```python -sweep(path='') -``` +You can use the returned `ArtifactCollection` object to retrieve +information about specific artifacts in that collection, and more. -Return a sweep by parsing path in the form `entity/project/sweep_id`. +### artifact_collection_exists +Whether an artifact collection exists within a specified project and entity. +### artifact_collections -**Args:** - - - `path`: Path to sweep in the form entity/project/sweep_id. If `api.entity` is set, this can be in the form project/sweep_id and if `api.project` is set this can just be the sweep_id. +Returns a collection of matching artifact collections. +### artifact_exists +Whether an artifact version exists within the specified project and entity. -**Returns:** - A `Sweep` object. +### artifact_type ---- +Returns the matching `ArtifactType`. -### method `Api.sync_tensorboard` +### artifact_types -```python -sync_tensorboard(root_dir, run_id=None, project=None, entity=None) -``` +Returns a collection of matching artifact types. -Sync a local directory containing tfevent files to wandb. +### artifact_versions ---- +Deprecated. Use `Api.artifacts(type_name, name)` method instead. -### method `Api.team` +### artifacts -```python -team(team: 'str') → Team -``` +Return an `Artifacts` collection. -Return the matching `Team` with the given name. +### automation +Returns the only Automation matching the parameters. +### automations -**Args:** - - - `team`: The name of the team. +Returns an iterator over all Automations that match the given parameters. +If no parameters are provided, the returned iterator will contain all +Automations that the user has access to. +### create_automation -**Returns:** - A `Team` object. +Create a new Automation. ---- +### create_custom_chart -### method `Api.update_automation` +Create a custom chart preset and return its id. -```python -update_automation( - obj: 'Automation', - create_missing: 'bool' = False, - **kwargs: 'Unpack[WriteAutomationsKwargs]' -) → Automation -``` +### create_project -Update an existing automation. +Create a new project. +### create_registry +Create a new registry. -**Args:** - - - `obj`: The automation to update. Must be an existing automation. create_missing (bool): If True, and the automation does not exist, create it. **kwargs: Any additional values to assign to the automation before updating it. If given, these will override any values that may already be set on the automation: - - `name`: The name of the automation. - - `description`: The description of the automation. - - `enabled`: Whether the automation is enabled. - - `scope`: The scope of the automation. - - `event`: The event that triggers the automation. - - `action`: The action that is triggered by the automation. +### create_run +Create a new run. +### create_run_queue -**Returns:** - The updated automation. +Create a new run queue in W&B Launch. +### create_team +Create a new team. -**Examples:** - Disable and edit the description of an existing automation ("my-automation"): +### create_user -```python -import wandb +Create a new user. -api = wandb.Api() +### delete_automation -automation = api.automation(name="my-automation") -automation.enabled = False -automation.description = "Kept for reference, but no longer used." +Delete an automation. -updated_automation = api.update_automation(automation) -``` +### flush -OR +Flush the local cache. -```python -import wandb +The api object keeps a local cache of runs, so if the state of the run +may change while executing your script you must clear the local cache +with `api.flush()` to get the latest values associated with the run. -api = wandb.Api() +### from_path -automation = api.automation(name="my-automation") +Return a run, sweep, project or report from a path. -updated_automation = api.update_automation( - automation, - enabled=False, - description="Kept for reference, but no longer used.", -) -``` +### integrations ---- +Return an iterator of all integrations for an entity. -### method `Api.upsert_run_queue` +### job -```python -upsert_run_queue( - name: 'str', - resource_config: 'dict', - resource_type: 'public.RunQueueResourceType', - entity: 'str | None' = None, - template_variables: 'dict | None' = None, - external_links: 'dict | None' = None, - prioritization_mode: 'public.RunQueuePrioritizationMode | None' = None -) -``` +Return a `Job` object. -Upsert a run queue in W&B Launch. +### list_jobs +Return a list of jobs, if any, for the given entity and project. +### project -**Args:** - - - `name`: Name of the queue to create - - `entity`: Optional name of the entity to create the queue. If `None`, use the configured or default entity. - - `resource_config`: Optional default resource configuration to be used for the queue. Use handlebars (eg. `{{var}}`) to specify template variables. - - `resource_type`: Type of resource to be used for the queue. One of "local-container", "local-process", "kubernetes", "sagemaker", or "gcp-vertex". - - `template_variables`: A dictionary of template variable schemas to be used with the config. - - `external_links`: Optional dictionary of external links to be used with the queue. - - `prioritization_mode`: Optional version of prioritization to use. Either "V0" or None +Return the `Project` with the given name (and entity, if given). +### projects +Get projects for a given entity. -**Returns:** - The upserted `RunQueue`. +### queued_run +Return a single queued run based on the path. +Parses paths of the form `entity/project/queue_id/run_queue_item_id`. -**Raises:** - ValueError if any of the parameters are invalid wandb.Error on wandb API errors +### registries ---- +Returns a lazy iterator of `Registry` objects. -### method `Api.user` +Use the iterator to search and filter registries, collections, +or artifact versions across your organization's registry. -```python -user(username_or_email: 'str') → User | None -``` +### registry -Return a user from a username or email address. +Return a registry given a registry name. -This function only works for local administrators. Use `api.viewer` to get your own user object. +### reports +Get reports for a given project path. +Note: `wandb.Api.reports()` API is in beta and will likely change in +future releases. -**Args:** - - - `username_or_email`: The username or email address of the user. +### run +Return a single run by parsing path in the form `entity/project/run_id`. +### run_queue -**Returns:** - A `User` object or None if a user is not found. +Return the named `RunQueue` for entity. ---- +See `Api.create_run_queue` for more information on how to create a run queue. -### method `Api.users` +### runs -```python -users(username_or_email: 'str') → list[User] -``` +Returns a `Runs` object, which lazily iterates over `Run` objects. -Return all users from a partial username or email address query. +Fields you can filter by include: +- `createdAt`: The timestamp when the run was created. (in ISO 8601 format, e.g. "2023-01-01T12:00:00Z") +- `displayName`: The human-readable display name of the run. (e.g. "eager-fox-1") +- `duration`: The total runtime of the run in seconds. +- `group`: The group name used to organize related runs together. +- `host`: The hostname where the run was executed. +- `jobType`: The type of job or purpose of the run. +- `name`: The unique identifier of the run. (e.g. "a1b2cdef") +- `state`: The current state of the run. +- `tags`: The tags associated with the run. +- `username`: The username of the user who initiated the run -This function only works for local administrators. Use `api.viewer` to get your own user object. +Additionally, you can filter by items in the run config or summary metrics. +Such as `config.experiment_name`, `summary_metrics.loss`, etc. +For more complex filtering, you can use MongoDB query operators. +For details, see: https://docs.mongodb.com/manual/reference/operator/query +The following operations are supported: +- `$and` +- `$or` +- `$nor` +- `$eq` +- `$ne` +- `$gt` +- `$gte` +- `$lt` +- `$lte` +- `$in` +- `$nin` +- `$exists` +- `$regex` +### slack_integrations -**Args:** - - - `username_or_email`: The prefix or suffix of the user you want to find. +Returns an iterator of Slack integrations for an entity. +### sweep +Return a sweep by parsing path in the form `entity/project/sweep_id`. -**Returns:** - An array of `User` objects. +### sync_tensorboard ---- +Sync a local directory containing tfevent files to wandb. -### method `Api.webhook_integrations` +### team -```python -webhook_integrations( - entity: 'str | None' = None, - per_page: 'int' = 50, - start: 'str | None' = None -) → Iterator[WebhookIntegration] -``` +Return the matching `Team` with the given name. -Returns an iterator of webhook integrations for an entity. +### update_automation +Update an existing automation. +### upsert_run_queue -**Args:** - - - `entity`: The entity (e.g. team name) for which to fetch integrations. If not provided, the user's default entity will be used. - - `per_page`: Number of integrations to fetch per page. Defaults to 50. Usually there is no reason to change this. +Upsert a run queue in W&B Launch. +### user +Return a user from a username or email address. -**Yields:** - - - `Iterator[WebhookIntegration]`: An iterator of webhook integrations. +This function only works for local administrators. Use `api.viewer` + to get your own user object. +### users +Return all users from a partial username or email address query. -**Examples:** - Get all registered webhook integrations for the team "my-team": +This function only works for local administrators. Use `api.viewer` + to get your own user object. -```python -import wandb +### webhook_integrations -api = wandb.Api() -webhook_integrations = api.webhook_integrations(entity="my-team") -``` +Returns an iterator of webhook integrations for an entity. -Find only webhook integrations that post requests to "https://my-fake-url.com": -```python -webhook_integrations = api.webhook_integrations(entity="my-team") -my_webhooks = [ - ig - for ig in webhook_integrations - if ig.url_endpoint.startswith("https://my-fake-url.com") -] -``` diff --git a/models/ref/python/public-api/artifactcollection.mdx b/models/ref/python/public-api/artifactcollection.mdx index b31a29d943..b483565d58 100644 --- a/models/ref/python/public-api/artifactcollection.mdx +++ b/models/ref/python/public-api/artifactcollection.mdx @@ -1,182 +1,100 @@ --- title: ArtifactCollection -namespace: public_apis_namespace -python_object_type: class +kind: class +namespace: wandb.apis.public.artifacts --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - - - - - - -## class `ArtifactCollection` -An artifact collection that represents a group of related artifacts. - - - -**Args:** - - - `client`: The client instance to use for querying W&B. - - `entity`: The entity (user or team) that owns the project. - - `project`: The name of the project to query for artifact collections. - - `name`: The name of the artifact collection. - - `type`: The type of the artifact collection (e.g., "dataset", "model"). - - `organization`: Optional organization name if applicable. - - `attrs`: Optional mapping of attributes to initialize the artifact collection. If not provided, the object will load its attributes from W&B upon initialization. - - -### property ArtifactCollection.aliases - -The aliases for all artifact versions contained in this collection. - - - -**Returns:** - - `list[str]`: The aliases property value. ---- - -### property ArtifactCollection.created_at - -The creation date of the artifact collection. - - - -**Returns:** - - `str`: The created_at property value. ---- - -### property ArtifactCollection.description - -A description of the artifact collection. - - - -**Returns:** - - `str | None`: The description property value. ---- - -### property ArtifactCollection.entity - -The entity (user or team) that owns the project. - - - -**Returns:** - - `str`: The entity property value. ---- - -### property ArtifactCollection.id - -The unique identifier of the artifact collection. - +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; -**Returns:** - - `str`: The id property value. ---- -### property ArtifactCollection.name + -The name of the artifact collection. -**Returns:** - - `str`: The name property value. ---- -### property ArtifactCollection.project +## Description -The project that contains the artifact collection. +An artifact collection that represents a group of related artifacts. -**Returns:** - - `str`: The project property value. ---- +## Args: -### property ArtifactCollection.tags +- **client**: The client instance to use for querying W&B. +- **entity**: The entity that owns the project. +- **project**: The name of the project to query for artifact collections. +- **name**: The name of the artifact collection. +- **type**: The type of the artifact collection (e.g., "dataset", "model"). +- **organization**: Optional organization name if applicable. +- **attrs**: Optional mapping of attributes to initialize the artifact collection. If not provided, the object will load its attributes from W&B upon initialization. -The tags associated with the artifact collection. +## Properties: +### id -**Returns:** - - `list[str]`: The tags property value. ---- +The unique identifier of the artifact collection. -### property ArtifactCollection.type +### entity -Returns the type of the artifact collection. +The entity that owns the project. ---- +### project -### property ArtifactCollection.updated_at +The project that contains the artifact collection. -The date at which the artifact collection was last updated. +### aliases +The aliases for all artifact versions contained in this collection. +### created_at +The creation date of the artifact collection. +### updated_at -**Returns:** - - `str | None`: The updated_at property value. ---- +The date at which the artifact collection was last updated. -### method `ArtifactCollection.artifacts` +### description -```python -artifacts(per_page: 'int' = 50, start: 'str | None' = None) → Artifacts -``` +A description of the artifact collection. -Get all artifacts in the collection. +### tags +The tags associated with the artifact collection. +### name -**Args:** - - - `per_page`: The number of artifacts to fetch per page. - - `start`: Pagination cursor for resuming a past query, captured from a previous paginator's `.cursor` attribute. +The name of the artifact collection. ---- +### type -### method `ArtifactCollection.change_type` +Returns the type of the artifact collection. -```python -change_type(new_type: 'str') → None -``` -Deprecated, change type directly with `save` instead. ---- +## Methods: -### method `ArtifactCollection.delete` +### artifacts -```python -delete() → None -``` +Get all artifacts in the collection. -Delete the entire artifact collection. +### change_type ---- +Deprecated, change type directly with `save` instead. -### method `ArtifactCollection.is_sequence` +### delete -```python -is_sequence() → bool -``` +Delete the entire artifact collection. -Return whether the artifact collection is a sequence. +### is_sequence ---- +Return whether the artifact collection is a sequence. +### save -### method `ArtifactCollection.save` +Persist any changes made to the artifact collection. -```python -save() → None -``` -Persist any changes made to the artifact collection. diff --git a/models/ref/python/public-api/artifactcollections.mdx b/models/ref/python/public-api/artifactcollections.mdx index 56645610d2..a49d4cc24e 100644 --- a/models/ref/python/public-api/artifactcollections.mdx +++ b/models/ref/python/public-api/artifactcollections.mdx @@ -1,48 +1,47 @@ --- title: ArtifactCollections -namespace: public_apis_namespace -python_object_type: class +kind: class +namespace: wandb.apis.public.artifacts --- + import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - + -## class `ArtifactCollections` -Artifact collections of a specific type in a project. +## Description -**Args:** - - - `client`: The client instance to use for querying W&B. - - `entity`: The entity (user or team) that owns the project. - - `project`: The name of the project to query for artifact collections. - - `type_name`: The name of the artifact type for which to fetch collections. - - `filters`: Optional mapping of filters to apply to the query. - - `order`: Optional string to specify the order of the results. If you prepend order with a + order is ascending (default). If you prepend order with a - order is descending. - - `per_page`: The number of artifact collections to fetch per page. Default is 50. +Artifact collections of a specific type in a project. -### property ArtifactCollections.cursor -An opaque cursor that marks the start of the next page to fetch. +## Args: -This value may be saved and passed as `start=` to a later paginated query to resume iteration from where this paginator left off. +- **client**: The client instance to use for querying W&B. +- **entity**: The entity that owns the project. +- **project**: The name of the project to query for artifact collections. +- **type_name**: The name of the artifact type for which to fetch collections. +- **filters**: Optional mapping of filters to apply to the query. +- **order**: Optional string to specify the order of the results. If you prepend order with a + order is ascending (default). If you prepend order with a - order is descending. +- **per_page**: The number of artifact collections to fetch per page. Default is 50. +- **start**: Pagination cursor for resuming a past query, captured from a previous paginator's `.cursor` attribute. -**Returns:** - - `str | None`: The cursor property value. ---- -### property ArtifactCollections.more +## Methods: +### next +Return the next item from the iterator. When exhausted, raise StopIteration +### update_variables +Update the query variables for the next page fetch. diff --git a/models/ref/python/public-api/artifactfiles.mdx b/models/ref/python/public-api/artifactfiles.mdx index 5c30acb541..bcc001dc2d 100644 --- a/models/ref/python/public-api/artifactfiles.mdx +++ b/models/ref/python/public-api/artifactfiles.mdx @@ -1,47 +1,50 @@ --- title: ArtifactFiles -namespace: public_apis_namespace -python_object_type: class +kind: class +namespace: wandb.apis.public.artifacts --- + import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - + -## class `ArtifactFiles` -A paginator for files in an artifact. -### property ArtifactFiles.cursor +## Description -An opaque cursor that marks the start of the next page to fetch. +A paginator for files in an artifact. -This value may be saved and passed as `start=` to a later paginated query to resume iteration from where this paginator left off. +## Args: -**Returns:** - - `str | None`: The cursor property value. ---- +- **client**: The client instance to use for querying W&B. +- **artifact**: The artifact for which to fetch files. +- **names**: Optional list of file names to filter by. If None, fetches all files. +- **per_page**: The number of files to fetch per page. Default is 50. +- **start**: Pagination cursor for resuming a past query, captured from a previous paginator's `.cursor` attribute. -### property ArtifactFiles.more +## Properties: +### path +Returns the path of the artifact. ---- -### property ArtifactFiles.path +## Methods: -Returns the path of the artifact. +### next +Return the next item from the iterator. When exhausted, raise StopIteration +### update_variables +Update the query variables for the next page fetch. -**Returns:** - - `list[str]`: The path property value. \ No newline at end of file diff --git a/models/ref/python/public-api/artifacts.mdx b/models/ref/python/public-api/artifacts.mdx index 4fe34fcdce..2b711a448f 100644 --- a/models/ref/python/public-api/artifacts.mdx +++ b/models/ref/python/public-api/artifacts.mdx @@ -1,54 +1,51 @@ --- title: Artifacts -namespace: public_apis_namespace -python_object_type: class +kind: class +namespace: wandb.apis.public.artifacts --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; + -## class `Artifacts` -An iterable collection of artifact versions associated with a project. -Optionally pass in filters to narrow down the results based on specific criteria. +## Description -**Args:** - - - `client`: The client instance to use for querying W&B. - - `entity`: The entity (user or team) that owns the project. - - `project`: The name of the project to query for artifacts. - - `collection_name`: The name of the artifact collection to query. - - `type`: The type of the artifacts to query. Common examples include "dataset" or "model". - - `filters`: Optional mapping of filters to apply to the query. - - `order`: Optional string to specify the order of the results. - - `per_page`: The number of artifact versions to fetch per page. Default is 50. - - `tags`: Optional string or list of strings to filter artifacts by tags. +An iterable collection of artifact versions associated with a project. +Optionally pass in filters to narrow down the results based on specific criteria. -### property Artifacts.cursor -An opaque cursor that marks the start of the next page to fetch. -This value may be saved and passed as `start=` to a later paginated query to resume iteration from where this paginator left off. +## Args: +- **client**: The client instance to use for querying W&B. +- **entity**: The entity that owns the project. +- **project**: The name of the project to query for artifacts. +- **collection_name**: The name of the artifact collection to query. +- **type**: The type of the artifacts to query. Common examples include "dataset" or "model". +- **filters**: Optional mapping of filters to apply to the query. +- **order**: Optional string to specify the order of the results. +- **per_page**: The number of artifact versions to fetch per page. Default is 50. +- **tags**: Optional string or list of strings to filter artifacts by tags. +- **start**: Pagination cursor for resuming a past query, captured from a previous paginator's `.cursor` attribute. -**Returns:** - - `str | None`: The cursor property value. ---- -### property Artifacts.more +## Methods: +### next +Return the next item from the iterator. When exhausted, raise StopIteration +### update_variables +Update the query variables for the next page fetch. ---- diff --git a/models/ref/python/public-api/artifacttype.mdx b/models/ref/python/public-api/artifacttype.mdx index c8b1331576..e2c274b089 100644 --- a/models/ref/python/public-api/artifacttype.mdx +++ b/models/ref/python/public-api/artifacttype.mdx @@ -1,88 +1,54 @@ --- title: ArtifactType -namespace: public_apis_namespace -python_object_type: class +kind: class +namespace: wandb.apis.public.artifacts --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - - - - - - -## class `ArtifactType` -An artifact object that satisfies query based on the specified type. - - -**Args:** - - - `client`: The client instance to use for querying W&B. - - `entity`: The entity (user or team) that owns the project. - - `project`: The name of the project to query for artifact types. - - `type_name`: The name of the artifact type. - - `attrs`: Optional attributes to initialize the ArtifactType. If omitted, the object will load its attributes from W&B upon initialization. +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; -### property ArtifactType.id + -The unique identifier of the artifact type. -**Returns:** - - `str`: The id property value. ---- -### property ArtifactType.name +## Description -The name of the artifact type. +An artifact object that satisfies query based on the specified type. +## Args: +- **client**: The client instance to use for querying W&B. +- **entity**: The entity that owns the project. +- **project**: The name of the project to query for artifact types. +- **type_name**: The name of the artifact type. +- **attrs**: Optional attributes to initialize the ArtifactType. If omitted, the object will load its attributes from W&B upon initialization. -**Returns:** - - `str`: The name property value. ---- -### method `ArtifactType.collection` +## Properties: -```python -collection(name: 'str') → ArtifactCollection -``` +### id -Get a specific artifact collection by name. +The unique identifier of the artifact type. +### name +The name of the artifact type. -**Args:** - - - `name` (str): The name of the artifact collection to retrieve. ---- -### method `ArtifactType.collections` +## Methods: -```python -collections( - filters: 'Mapping[str, Any] | None' = None, - order: 'str | None' = None, - per_page: 'int' = 50, - start: 'str | None' = None -) → ArtifactCollections -``` +### collection -Get all artifact collections associated with this artifact type. +Get a specific artifact collection by name. +### collections +Get all artifact collections associated with this artifact type. -**Args:** - - - `filters` (dict): Optional mapping of filters to apply to the query. - - `order` (str): Optional string to specify the order of the results. If you prepend order with a + order is ascending (default). If you prepend order with a - order is descending. The default order is the collection ID in descending order. - - `per_page` (int): The number of artifact collections to fetch per page. Default is 50. - - `start`: Pagination cursor for resuming a past query, captured from a previous paginator's `.cursor` attribute. ---- diff --git a/models/ref/python/public-api/artifacttypes.mdx b/models/ref/python/public-api/artifacttypes.mdx index 506f4120a9..ca4ed8a9fb 100644 --- a/models/ref/python/public-api/artifacttypes.mdx +++ b/models/ref/python/public-api/artifacttypes.mdx @@ -1,36 +1,44 @@ --- title: ArtifactTypes -namespace: public_apis_namespace -python_object_type: class +kind: class +namespace: wandb.apis.public.artifacts --- + import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - + -## class `ArtifactTypes` -An lazy iterator of `ArtifactType` objects for a specific project. -### property ArtifactTypes.cursor +## Description -An opaque cursor that marks the start of the next page to fetch. +A lazy iterator of `ArtifactType` objects for a specific project. -This value may be saved and passed as `start=` to a later paginated query to resume iteration from where this paginator left off. + + +## Args: + +- **client**: The client instance to use for querying W&B. +- **entity**: The entity that owns the project. +- **project**: The name of the project to query for artifact types. +- **per_page**: The number of artifact types to fetch per page. Defaults to 50. +- **start**: Pagination cursor for resuming a past query, captured from a previous paginator's `.cursor` attribute. -**Returns:** - - `str | None`: The cursor property value. ---- -### property ArtifactTypes.more +## Methods: +### next +Return the next item from the iterator. When exhausted, raise StopIteration +### update_variables +Update the query variables for the next page fetch. diff --git a/models/ref/python/public-api/automations.mdx b/models/ref/python/public-api/automations.mdx index 48d098277b..13af5936a8 100644 --- a/models/ref/python/public-api/automations.mdx +++ b/models/ref/python/public-api/automations.mdx @@ -1,13 +1,44 @@ --- title: Automations -namespace: public_apis_namespace -python_object_type: class +kind: class +namespace: wandb.apis.public.automations --- + import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - + + + + + + +## Description + +A lazy iterator of `Automation` objects. + + + +## Args: + +- **client**: The client instance to use for querying W&B. +- **variables**: A mapping of variables to use in the GraphQL query. +- **per_page**: The number of automations to fetch per page. Default is 50. +- **start**: Pagination cursor for resuming a past query, captured from a previous paginator's `.cursor` attribute. +- **_query**: + + + + +## Methods: + +### next + +Return the next item from the iterator. When exhausted, raise StopIteration + +### update_variables +Update the query variables for the next page fetch. diff --git a/models/ref/python/public-api/betareport.mdx b/models/ref/python/public-api/betareport.mdx index f3fd9e08da..b9e4d30af3 100644 --- a/models/ref/python/public-api/betareport.mdx +++ b/models/ref/python/public-api/betareport.mdx @@ -1,151 +1,89 @@ --- title: BetaReport -namespace: public_apis_namespace -python_object_type: class ---- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - - - - - - -## class `BetaReport` -BetaReport is a class associated with reports created in W&B. - -Provides access to report attributes (name, description, user, spec, timestamps) and methods for retrieving associated runs, sections, and for rendering the report as HTML. - - - -**Attributes:** - - - `id` (string): Unique identifier of the report. - - `display_name` (string): Human-readable display name of the report. - - `name` (string): The name of the report. Use `display_name` for a more user-friendly name. - - `description` (string): Description of the report. - - `user` (User): Dictionary containing user info (username, email) who created the report. - - `spec` (dict): The spec of the report. - - `url` (string): The URL of the report. - - `updated_at` (string): Timestamp of last update. - - `created_at` (string): Timestamp when the report was created. - -### method `BetaReport.__init__` - -```python -__init__( - client: 'RetryingClient', - attrs: 'dict', - entity: 'str | None' = None, - project: 'str | None' = None -) -``` - - - - - - ---- - -### property BetaReport.created_at - - - - - +kind: class +namespace: wandb.apis.public.reports --- -### property BetaReport.description - - - - - ---- - -### property BetaReport.display_name - - - - - ---- +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; -### property BetaReport.id + ---- -### property BetaReport.name +## Description +BetaReport is a class associated with reports created in W&B. +Provides access to report attributes (name, description, user, spec, +timestamps) and methods for retrieving associated runs, +sections, and for rendering the report as HTML. ---- +## Args: -### property BetaReport.sections +- **client**: The API client instance to use for querying W&B. +- **attrs**: A dictionary of report attributes, typically obtained from a GraphQL response. +- **entity**: The entity name for the project. +- **project**: The project name for the report. -Get the panel sections (groups) from the report. ---- +## Properties: -### property BetaReport.spec +### spec +Get the spec of the report as a dictionary. +### sections +Get the panel sections (groups) from the report. +### id ---- +Get the unique identifier of the report. -### property BetaReport.updated_at +### name +Get the name of the report. +### display_name +Get the display name of the report. +### description ---- +Get the description of the report. -### property BetaReport.url +### user +Get the user who created the report. +### updated_at +Get the timestamp of the last update. +### created_at ---- +Get the timestamp when the report was created. -### property BetaReport.user +### url +Get the URL of the report. +## Methods: +### display +Display this object in jupyter. ---- - -### method `BetaReport.runs` - -```python -runs( - section: 'dict[str, Any]', - per_page: 'int' = 50, - only_selected: 'bool' = True -) → public.Runs -``` - -Get runs associated with a section of the report. - ---- +### runs -### method `BetaReport.to_html` +Get runs associated with a section of the report. -```python -to_html(height: 'int' = 1024, hidden: 'bool' = False) → str -``` -Generate HTML containing an iframe displaying this report. diff --git a/models/ref/python/public-api/downloadhistoryresult.mdx b/models/ref/python/public-api/downloadhistoryresult.mdx index 386e9ad89f..bfd1ddaea8 100644 --- a/models/ref/python/public-api/downloadhistoryresult.mdx +++ b/models/ref/python/public-api/downloadhistoryresult.mdx @@ -1,37 +1,40 @@ --- title: DownloadHistoryResult -namespace: public_apis_namespace -python_object_type: class +kind: class +namespace: wandb.apis.public.runhistory.downloads --- + import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - + -## class `DownloadHistoryResult` -Result of downloading a run's history exports. +```python +paths: 'list[pathlib.Path]', +contains_live_data: 'bool', +errors: 'dict[pathlib.Path, str] | None' = None +``` +## Description +Result of downloading a run's history exports. -**Attributes:** - - - `paths`: The paths to the downloaded history files. - - `errors`: A dictionary mapping file paths to error messages for files that failed to download. None if all downloads succeeded. - - `contains_live_data`: Whether the run contains live data, not yet exported to parquet files. +Attributes: + paths: The paths to the downloaded history files. + errors: A dictionary mapping file paths to error messages for files that + failed to download. None if all downloads succeeded. + contains_live_data: Whether the run contains live data, + not yet exported to parquet files. -### method `DownloadHistoryResult.__init__` -```python -__init__( - paths: 'list[pathlib.Path]', - contains_live_data: 'bool', - errors: 'dict[pathlib.Path, str] | None' = None -) → None -``` +## Args: +- **paths**: The paths to the downloaded history files. +- **contains_live_data**: Whether the run contains live data, not yet exported to parquet files. +- **errors**: A dictionary mapping file paths to error messages for files that failed to download. None if all downloads succeeded. diff --git a/models/ref/python/public-api/file.mdx b/models/ref/python/public-api/file.mdx index 0d375affa1..8b200c7013 100644 --- a/models/ref/python/public-api/file.mdx +++ b/models/ref/python/public-api/file.mdx @@ -1,104 +1,75 @@ --- title: File -namespace: public_apis_namespace -python_object_type: class +kind: class +namespace: wandb.apis.public.files --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - - - - - - -## class `File` -File saved to W&B. - -Represents a single file stored in W&B. Includes access to file metadata. Files are associated with a specific run and can include text files, model weights, datasets, visualizations, and other artifacts. You can download the file, delete the file, and access file properties. -Specify one or more attributes in a dictionary to fine a specific file logged to a specific run. You can search using the following keys: - - -- id (str): The ID of the run that contains the file -- name (str): Name of the file -- url (str): path to file -- direct_url (str): path to file in the bucket -- sizeBytes (int): size of file in bytes -- md5 (str): md5 of file -- mimetype (str): mimetype of file -- updated_at (str): timestamp of last update -- path_uri (str): path to file in the bucket, currently only available for S3 objects and reference files +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; + -**Args:** - - - `client`: The run object that contains the file - - `attrs` (dict): A dictionary of attributes that define the file - - `run`: The run object that contains the file -### property File.path_uri -Returns the URI path to the file in the storage bucket. +## Description +File saved to W&B. -**Returns:** - - - `str`: The S3 URI (e.g., 's3://bucket/path/to/file') if the file is stored in S3, the direct URL if it's a reference file, or an empty string if unavailable. +Represents a single file stored in W&B. Includes access to file metadata. +Files are associated with a specific run and +can include text files, model weights, datasets, visualizations, and other +artifacts. You can download the file, delete the file, and access file +properties. +Specify one or more attributes in a dictionary to fine a specific +file logged to a specific run. You can search using the following keys: +- id (str): The ID of the run that contains the file +- name (str): Name of the file +- url (str): path to file +- direct_url (str): path to file in the bucket +- sizeBytes (int): size of file in bytes +- md5 (str): md5 of file +- mimetype (str): mimetype of file +- updated_at (str): timestamp of last update +- path_uri (str): path to file in the bucket, currently only available for S3 objects and reference files -**Returns:** - - `str`: The path_uri property value. ---- -### property File.size -Returns the size of the file in bytes. +## Args: +- **client**: The run object that contains the file +- **attrs**: A dictionary of attributes that define the file +- **run**: The run object that contains the file +## Properties: +### size -**Returns:** - - `int`: The size property value. ---- +Returns the size of the file in bytes. -### method `File.delete` +### path_uri -```python -delete() → None -``` +Returns the URI path to the file in the storage bucket. -Delete the file from the W&B server. ---- -### method `File.download` +## Methods: -```python -download( - root: 'str' = '.', - replace: 'bool' = False, - exist_ok: 'bool' = False, - api: 'Api | None' = None -) → io.TextIOWrapper -``` +### delete -Downloads a file previously saved by a run from the wandb server. +Delete the file from the W&B server. +### display +Display this object in jupyter. -**Args:** - - - `root`: Local directory to save the file. Defaults to the current working directory ("."). - - `replace`: If `True`, download will overwrite a local file if it exists. Defaults to `False`. - - `exist_ok`: If `True`, will not raise ValueError if file already exists and will not re-download unless replace=True. Defaults to `False`. - - `api`: If specified, the `Api` instance used to download the file. +### download +Downloads a file previously saved by a run from the wandb server. -**Raises:** - `ValueError` if file already exists, `replace=False` and `exist_ok=False`. diff --git a/models/ref/python/public-api/files.mdx b/models/ref/python/public-api/files.mdx index f3226560d7..59fa3cd239 100644 --- a/models/ref/python/public-api/files.mdx +++ b/models/ref/python/public-api/files.mdx @@ -1,24 +1,28 @@ --- title: Files -namespace: public_apis_namespace -python_object_type: class +kind: class +namespace: wandb.apis.public.files --- + import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - + + -## class `Files` -A lazy iterator over a collection of `File` objects. -Access and manage files uploaded to W&B during a run. Handles pagination automatically when iterating through large collections of files. +## Description +A lazy iterator over a collection of `File` objects. +Access and manage files uploaded to W&B during a run. Handles pagination +automatically when iterating through large collections of files. -**Example:** - ```python +## Examples: + +```python from wandb.apis.public.files import Files from wandb.apis.public.api import Api @@ -30,53 +34,31 @@ files = Files(api.client, run) # Iterate over files for file in files: - print(file.name) - print(file.url) - print(file.size) + print(file.name) + print(file.url) + print(file.size) - # Download the file - file.download(root="download_directory", replace=True) -``` - -### method `Files.__init__` - -```python -__init__( - client: 'RetryingClient', - run: 'Run', - names: 'list[str] | None' = None, - per_page: 'int' = 50, - upload: 'bool' = False, - pattern: 'str | None' = None -) + # Download the file + file.download(root="download_directory", replace=True) ``` -Initialize a lazy iterator over a collection of `File` objects. +## Args: -Files are retrieved in pages from the W&B server as needed. +- **client**: The API client instance to use for querying W&B. +- **run**: The run object that contains the files. +- **names**: Optional list of file names to filter by. If None, fetches all files. +- **per_page**: The number of files to fetch per page. Default is 50. +- **upload**: If `True`, fetch the upload URL for each file. Default is `False`. +- **pattern**: Pattern to match when returning files from W&B. This pattern uses mySQL's LIKE syntax, so matching all files that end with .json would be "%.json". -**Args:** - - - `client`: The run object that contains the files - - `run`: The run object that contains the files - - `names` (list, optional): A list of file names to filter the files - - `per_page` (int, optional): The number of files to fetch per page - - `upload` (bool, optional): If `True`, fetch the upload URL for each file - - `pattern` (str, optional): Pattern to match when returning files from W&B This pattern uses mySQL's LIKE syntax, so matching all files that end with .json would be "%.json". If both names and pattern are provided, a ValueError will be raised. +## Methods: ---- +### next - -### property Files.length - - - - - ---- +Return the next item from the iterator. When exhausted, raise StopIteration diff --git a/models/ref/python/public-api/incompleterunhistoryerror.mdx b/models/ref/python/public-api/incompleterunhistoryerror.mdx index dc6125b1c3..adea033726 100644 --- a/models/ref/python/public-api/incompleterunhistoryerror.mdx +++ b/models/ref/python/public-api/incompleterunhistoryerror.mdx @@ -1,20 +1,42 @@ --- title: IncompleteRunHistoryError -namespace: public_apis_namespace -python_object_type: class +kind: class +namespace: wandb.apis.public.runhistory.downloads --- + import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - + + + + + + + +## Description + +Raised when run history has incomplete history. + +Incomplete history occurs when some data has not been exported to +parquet files yet, typically because the run is still ongoing. + + + + + +## Methods: +### add_note -## class `IncompleteRunHistoryError` -Raised when run history has incomplete history. +Exception.add_note(note) -- +add a note to the exception -Incomplete history occurs when some data has not been exported to parquet files yet, typically because the run is still ongoing. +### with_traceback +Exception.with_traceback(tb) -- +set self.__traceback__ to tb and return self. diff --git a/models/ref/python/public-api/member.mdx b/models/ref/python/public-api/member.mdx index 85bf4281d3..5088636b4d 100644 --- a/models/ref/python/public-api/member.mdx +++ b/models/ref/python/public-api/member.mdx @@ -1,50 +1,42 @@ --- title: Member -namespace: public_apis_namespace -python_object_type: class +kind: class +namespace: wandb.apis.public.teams --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; + -## class `Member` -A member of a team. -### method `Member.__init__` -```python -__init__(client: 'RetryingClient', team: 'str', attrs: 'Mapping[str, Any]') -``` -**Args:** - - - `client` (`wandb.apis.internal.Api`): The client instance to use - - `team` (str): The name of the team this member belongs to - - `attrs` (dict): The member attributes +## Description +A member of a team. +## Args: +- **client**: The client instance to use +- **team**: The name of the team this member belongs to +- **attrs**: The member attributes ---- +## Methods: -### method `Member.delete` +### delete -```python -delete() -``` +Remove a member from a team. -Remove a member from a team. +### display +Display this object in jupyter. -**Returns:** - Boolean indicating success diff --git a/models/ref/python/public-api/project.mdx b/models/ref/python/public-api/project.mdx index 76d34cf1e4..1f4a13103b 100644 --- a/models/ref/python/public-api/project.mdx +++ b/models/ref/python/public-api/project.mdx @@ -1,146 +1,73 @@ --- title: Project -namespace: public_apis_namespace -python_object_type: class +kind: class +namespace: wandb.apis.public.projects --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - - - - - - -## class `Project` -A project is a namespace for runs. - -### method `Project.__init__` - -```python -__init__( - client: 'RetryingClient', - entity: 'str', - project: 'str', - attrs: 'Mapping[str, Any]' -) → Project -``` - -**Args:** - - - `client`: W&B API client instance. - - `name` (str): The name of the project. - - `entity` (str): The entity name that owns the project. - - -A single project associated with an entity. - - - -**Args:** - - - `client`: The API client used to query W&B. - - `entity`: The entity which owns the project. - - `project`: The name of the project to query. - - `attrs`: The attributes of the project. - - ---- - -### property Project.id - - - - - ---- - -### property Project.owner - -Returns the project owner as a User object. - +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; -**Raises:** - - - `ValueError`: when no user information is found for the project. + -**Returns:** - - `public.User`: The owner property value. ---- -### property Project.path -Returns the path of the project. The path is a list containing the entity and project name. +## Description +A project is a namespace for runs. -**Returns:** - - `list[str]`: The path property value. ---- -### property Project.url -Returns the URL of the project. +## Args: +- **client**: W&B API client instance. +- **entity**: The entity name that owns the project. +- **project**: The name of the project. +- **attrs**: A dictionary of project attributes, typically obtained from a GraphQL response. +## Properties: +### owner -**Returns:** - - `str`: The url property value. ---- +Returns the project owner as a User object. -### method `Project.artifacts_types` +Raises: + ValueError: when no user information is found for the project. -```python -artifacts_types(per_page: 'int' = 50) → public.ArtifactTypes -``` +### path -Returns all artifact types associated with this project. +Returns the path of the project. The path is a list containing the +entity and project name. ---- - -### method `Project.collections` +### url -```python -collections( - filters: 'Mapping[str, Any] | None' = None, - order: 'str | None' = None, - per_page: 'int' = 50 -) → public.ProjectArtifactCollections -``` +Returns the URL of the project. -Returns all artifact collections associated with this project. +### id +Returns the unique identifier of the project. -**Args:** - - - `filters`: Optional mapping of filters to apply to the query. - - `order`: Optional string to specify the order of the results. If you prepend order with a + order is ascending (default). If you prepend order with a - order is descending. - - `per_page`: The number of artifact collections to fetch per page. Default is 50. ---- +## Methods: -### method `Project.sweeps` +### artifacts_types -```python -sweeps(per_page: 'int' = 50) → Sweeps -``` +Returns all artifact types associated with this project. -Return a paginated collection of sweeps in this project. +### collections +Returns all artifact collections associated with this project. +### display -**Args:** - - - `per_page`: The number of sweeps to fetch per request to the API. +Display this object in jupyter. +### sweeps +Return a paginated collection of sweeps in this project. -**Returns:** - A `Sweeps` object, which is an iterable collection of `Sweep` objects. ---- diff --git a/models/ref/python/public-api/projectartifactcollections.mdx b/models/ref/python/public-api/projectartifactcollections.mdx index 412d916eab..1e15890ae3 100644 --- a/models/ref/python/public-api/projectartifactcollections.mdx +++ b/models/ref/python/public-api/projectartifactcollections.mdx @@ -1,40 +1,46 @@ --- title: ProjectArtifactCollections -namespace: public_apis_namespace -python_object_type: class +kind: class +namespace: wandb.apis.public.artifacts --- + import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - + -## class `ProjectArtifactCollections` -Artifact collections in a project. +## Description -**Args:** - - - `client`: The client instance to use for querying W&B. - - `entity`: The entity (user or team) that owns the project. - - `project`: The name of the project to query for artifact collections. - - `filters`: Optional mapping of filters to apply to the query. - - `order`: Optional string to specify the order of the results. If you prepend order with a + order is ascending (default). If you prepend order with a - order is descending. - - `per_page`: The number of artifact collections to fetch per page. Default is 50. +Artifact collections in a project. -### property ProjectArtifactCollections.cursor -An opaque cursor that marks the start of the next page to fetch. +## Args: -This value may be saved and passed as `start=` to a later paginated query to resume iteration from where this paginator left off. +- **client**: The client instance to use for querying W&B. +- **entity**: The entity that owns the project. +- **project**: The name of the project to query for artifact collections. +- **filters**: Optional mapping of filters to apply to the query. +- **order**: Optional string to specify the order of the results. If you prepend order with a + order is ascending (default). If you prepend order with a - order is descending. +- **per_page**: The number of artifact collections to fetch per page. Default is 50. +- **start**: Pagination cursor for resuming a past query, captured from a previous paginator's `.cursor` attribute. -**Returns:** - - `str | None`: The cursor property value. ---- -### property ProjectArtifactCollections.more +## Methods: + +### next + +Return the next item from the iterator. When exhausted, raise StopIteration + +### update_variables + +Update the query variables for the next page fetch. + + + diff --git a/models/ref/python/public-api/projects.mdx b/models/ref/python/public-api/projects.mdx index 60861427cc..a814fed3c4 100644 --- a/models/ref/python/public-api/projects.mdx +++ b/models/ref/python/public-api/projects.mdx @@ -1,40 +1,27 @@ --- title: Projects -namespace: public_apis_namespace -python_object_type: class +kind: class +namespace: wandb.apis.public.projects --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; + -## class `Projects` -An lazy iterator of `Project` objects. -An iterable interface to access projects created and saved by the entity. -### method `Projects.__init__` -```python -__init__( - client: 'RetryingClient', - entity: 'str', - per_page: 'int' = 50 -) → Projects -``` +## Description -**Args:** - - - `client` (`wandb.apis.internal.Api`): The API client instance to use. - - `entity` (str): The entity name (username or team) to fetch projects for. - - `per_page` (int): Number of projects to fetch per request (default is 50). +A lazy iterator of `Project` objects. +An iterable interface to access projects created and saved by the entity. +## Examples: -**Example:** - ```python +```python from wandb.apis.public.api import Api # Find projects that belong to this entity @@ -46,40 +33,26 @@ for project in projects: print(f"- URL: {project.url}") print(f"- Created at: {project.created_at}") print(f"- Is benchmark: {project.is_benchmark}") -``` - - -An iterable collection of `Project` objects. - - - -**Args:** - - - `client`: The API client used to query W&B. - - `entity`: The entity which owns the projects. - - `per_page`: The number of projects to fetch per request to the API. - - ---- - -### property Projects.cursor - -An opaque cursor that marks the start of the next page to fetch. +``` -This value may be saved and passed as `start=` to a later paginated query to resume iteration from where this paginator left off. +## Args: +- **client**: The API client instance to use. +- **entity**: The entity name (username or team) to fetch projects for. +- **per_page**: Number of projects to fetch per request (default is 50). -**Returns:** - - `str | None`: The cursor property value. ---- -### property Projects.more +## Methods: +### next +Return the next item from the iterator. When exhausted, raise StopIteration +### update_variables +Update the query variables for the next page fetch. diff --git a/models/ref/python/public-api/registry.mdx b/models/ref/python/public-api/registry.mdx index b8e716facc..bea1447055 100644 --- a/models/ref/python/public-api/registry.mdx +++ b/models/ref/python/public-api/registry.mdx @@ -1,459 +1,148 @@ --- title: Registry -namespace: public_apis_namespace -python_object_type: class +kind: class +namespace: wandb.apis.public.registries.registry --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - - - - - - -## class `Registry` -A single registry in the Registry. - -### method `Registry.__init__` - -```python -__init__( - client: 'RetryingClient', - organization: 'str', - entity: 'str', - name: 'str', - attrs: 'RegistryFragment | None' = None -) -``` - - - - - - ---- - -### property Registry.allow_all_artifact_types - -Return whether all artifact types are allowed in the registry. - -If `True`, artifacts of any type can be added. If `False`, artifacts are restricted to the types listed in `artifact_types`. - - - -**Returns:** - - `bool`: The allow_all_artifact_types property value. ---- - -### property Registry.artifact_types - -Returns the artifact types allowed in the registry. - -If `allow_all_artifact_types` is `True` then `artifact_types` reflects the types previously saved or currently used in the registry. If `allow_all_artifact_types` is `False` then artifacts are restricted to the types in `artifact_types`. - - - -**Note:** - -> Previously saved artifact types cannot be removed. -> - -**Example:** - ```python -import wandb - -registry = wandb.Api().create_registry() -registry.artifact_types.append("model") -registry.save() # once saved, the artifact type `model` cannot be removed -registry.artifact_types.append("accidentally_added") -registry.artifact_types.remove( - "accidentally_added" -) # Types can only be removed if it has not been saved yet -``` - - - -**Returns:** - - `AddOnlyArtifactTypesList`: The artifact_types property value. ---- - -### property Registry.created_at - -Timestamp of when the registry was created. - - - -**Returns:** - - `str`: The created_at property value. ---- - -### property Registry.description - -Description of the registry. - - - -**Returns:** - - `str | None`: The description property value. ---- - -### property Registry.entity - -Organization entity of the registry. - - - -**Returns:** - - `str`: The entity property value. ---- - -### property Registry.full_name - -Full name of the registry including the `wandb-registry-` prefix. - - - -**Returns:** - - `str`: The full_name property value. ---- - -### property Registry.id - -The unique ID for this registry. - - - -**Returns:** - - `str`: The id property value. ---- - -### property Registry.name - -Name of the registry without the `wandb-registry-` prefix. - - - -**Returns:** - - `str`: The name property value. ---- - -### property Registry.organization - -Organization name of the registry. - - - -**Returns:** - - `str`: The organization property value. ---- - -### property Registry.path - - - - - ---- - -### property Registry.updated_at - -Timestamp of when the registry was last updated. - - - -**Returns:** - - `str`: The updated_at property value. ---- - -### property Registry.visibility - -Visibility of the registry. - - - -**Returns:** - - - `Literal["organization", "restricted"]`: The visibility level. - - "organization": Anyone in the organization can view this registry. You can edit their roles later from the settings in the UI. - - "restricted": Only invited members via the UI can access this registry. Public sharing is disabled. - - - - - -**Returns:** - - `Literal['organization', 'restricted']`: The visibility property value. ---- - -### method `Registry.add_members` - -```python -add_members(*members: 'User | UserMember | Team | TeamMember | str') → Self -``` - -Adds users or teams to this registry. - - - -**Args:** - - - `members`: The users or teams to add to the registry. Accepts `User` objects, `Team` objects, or their string IDs. - - - -**Returns:** - This registry for further method chaining, if needed. - - - -**Raises:** - - - `TypeError`: If no members are passed as arguments. - - `ValueError`: If unable to infer or parse the user or team IDs. - - - -**Examples:** - ```python -import wandb - -api = wandb.Api() - -# Fetch an existing registry -registry = api.registry(name="my-registry", organization="my-org") - -user1 = api.user(username="some-user") -user2 = api.user(username="other-user") -registry.add_members(user1, user2) - -my_team = api.team(name="my-team") -registry.add_members(my_team) -``` - ---- - -### method `Registry.collections` - -```python -collections( - filter: 'dict[str, Any] | None' = None, - per_page: 'PositiveInt' = 100, - start: 'str | None' = None -) → Collections -``` - -Returns the collections belonging to the registry. - ---- - -### classmethod `Registry.create` - -```python -create( - client: 'RetryingClient', - organization: 'str', - name: 'str', - visibility: "Literal['organization', 'restricted']", - description: 'str | None' = None, - artifact_types: 'list[str] | None' = None -) → Self -``` - -Create a new registry. - -The registry name must be unique within the organization. This function should be called using `api.create_registry()` - - - -**Args:** - - - `client`: The GraphQL client. - - `organization`: The name of the organization. - - `name`: The name of the registry (without the `wandb-registry-` prefix). - - `visibility`: The visibility level ('organization' or 'restricted'). - - `description`: An optional description for the registry. - - `artifact_types`: An optional list of allowed artifact types. - +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; -**Returns:** - - - `Registry`: The newly created Registry object. + -**Raises:** - - - `ValueError`: If a registry with the same name already exists in the organization or if the creation fails. ---- -### method `Registry.delete` -```python -delete() → None -``` +## Description -Delete the registry. This is irreversible. +A single registry in the Registry. ---- -### method `Registry.load` -```python -load() → None -``` +## Args: -Load registry attributes from the backend. +- **client**: The API client used to query W&B. +- **organization**: +- **entity**: The entity which owns the registry. +- **name**: The name of the registry (without the `wandb-registry-` prefix). +- **attrs**: The attributes of the registry, typically obtained from a GraphQL response. ---- -### method `Registry.members` +## Properties: -```python -members() → list[UserMember | TeamMember] -``` +### id -Returns the current members (users and teams) of this registry. +The unique ID for this registry. ---- +### full_name -### method `Registry.remove_members` +Full name of the registry including the `wandb-registry-` prefix. -```python -remove_members(*members: 'User | UserMember | Team | TeamMember | str') → Self -``` +### name -Removes users or teams from this registry. +Name of the registry without the `wandb-registry-` prefix. +### entity +Organization entity of the registry. -**Args:** - - - `members`: The users or teams to remove from the registry. Accepts `User` objects, `Team` objects, or their string IDs. +### organization +Organization name of the registry. +### description -**Returns:** - This registry for further method chaining, if needed. +Description of the registry. +### allow_all_artifact_types +Return whether all artifact types are allowed in the registry. -**Raises:** - - - `TypeError`: If no members are passed as arguments. - - `ValueError`: If unable to infer or parse the user or team IDs. +If `True`, artifacts of any type can be added. If `False`, artifacts are +restricted to the types listed in `artifact_types`. +### artifact_types +Returns the artifact types allowed in the registry. -**Examples:** - ```python -import wandb +If `allow_all_artifact_types` is `True` then `artifact_types` reflects the +types previously saved or currently used in the registry. +If `allow_all_artifact_types` is `False` then artifacts are restricted to the +types in `artifact_types`. -api = wandb.Api() +Note: + Previously saved artifact types cannot be removed. -# Fetch an existing registry -registry = api.registry(name="my-registry", organization="my-org") +### created_at -user1 = api.user(username="some-user") -user2 = api.user(username="other-user") -registry.remove_members(user1, user2) +Timestamp of when the registry was created. -old_team = api.team(name="old-team") -registry.remove_members(old_team) -``` +### updated_at ---- +Timestamp of when the registry was last updated. -### method `Registry.save` +### path -```python -save() → None -``` +Returns the path of the registry. -Save registry attributes to the backend. +### visibility ---- +Visibility of the registry. -### method `Registry.team_members` -```python -team_members() → list[TeamMember] -``` -Returns the current member teams of this registry. +## Methods: ---- +### add_members -### method `Registry.update_member` +Adds users or teams to this registry. -```python -update_member( - member: 'User | UserMember | Team | TeamMember | str', - role: 'MemberRole | str' -) → Self -``` +### collections -Updates the role of a member (user or team) within this registry. +Returns the collections belonging to the registry. +### create +Create a new registry. -**Args:** - - - `member`: The user or team to update the role of. Accepts a `User` object, `Team` object, or their string ID. - - `role`: The new role to assign to the member. May be one of: - - "admin" - - "member" - - "viewer" - - "restricted_viewer" (if supported by the W&B server) +The registry name must be unique within the organization. +This function should be called using `api.create_registry()` +### delete +Delete the registry. This is irreversible. -**Returns:** - This registry for further method chaining, if needed. +### load +Load registry attributes from the backend. +### members -**Raises:** - - - `ValueError`: If unable to infer the user or team ID. +Returns the current members (users and teams) of this registry. +### remove_members +Removes users or teams from this registry. -**Examples:** -Make all users in the registry admins +### save -```python -import wandb +Save registry attributes to the backend. -api = wandb.Api() +### team_members -# Fetch an existing registry -registry = api.registry(name="my-registry", organization="my-org") +Returns the current member teams of this registry. -for member in registry.user_members(): - registry.update_member(member.user, role="admin") -``` +### update_member ---- +Updates the role of a member within this registry. -### method `Registry.user_members` +### user_members -```python -user_members() → list[UserMember] -``` +Returns the current member users of this registry. -Returns the current member users of this registry. +### versions ---- +Returns the versions belonging to the registry. -### method `Registry.versions` -```python -versions( - filter: 'dict[str, Any] | None' = None, - per_page: 'PositiveInt' = 100, - start: 'str | None' = None -) → Versions -``` -Returns the versions belonging to the registry. diff --git a/models/ref/python/public-api/reports.mdx b/models/ref/python/public-api/reports.mdx index 749987bdfc..0fa3004fa6 100644 --- a/models/ref/python/public-api/reports.mdx +++ b/models/ref/python/public-api/reports.mdx @@ -1,71 +1,48 @@ --- title: Reports -namespace: public_apis_namespace -python_object_type: class +kind: class +namespace: wandb.apis.public.reports --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - - - - - - -## class `Reports` -Reports is a lazy iterator of `BetaReport` objects. -### method `Reports.__init__` +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; -```python -__init__( - client: 'RetryingClient', - project: 'Project', - name: 'str | None' = None, - entity: 'str | None' = None, - per_page: 'int' = 50 -) -``` -**Args:** - - - `client` (`wandb.apis.internal.Api`): The API client instance to use. - - `project` (`wandb.sdk.internal.Project`): The project to fetch reports from. - - `name` (str, optional): The name of the report to filter by. If `None`, fetches all reports. - - `entity` (str, optional): The entity name for the project. Defaults to the project entity. - - `per_page` (int): Number of reports to fetch per page (default is 50). + +## Description +Reports is a lazy iterator of `BetaReport` objects. ---- -### property Reports.length +## Args: +- **client**: The API client instance to use. +- **project**: The project to fetch reports from. +- **name**: The name of the report to filter by. If `None`, fetches all reports. +- **entity**: The entity name for the project. Defaults to the project entity. +- **per_page**: Number of reports to fetch per page (default is 50). ---- +## Methods: +### convert_objects -### method `Reports.convert_objects` +Converts GraphQL edges to File objects. -```python -convert_objects() → list[BetaReport] -``` +### next -Converts GraphQL edges to File objects. +Return the next item from the iterator. When exhausted, raise StopIteration ---- +### update_variables -### method `Reports.update_variables` +Updates the GraphQL query variables for pagination. -```python -update_variables() → None -``` -Updates the GraphQL query variables for pagination. diff --git a/models/ref/python/public-api/run.mdx b/models/ref/python/public-api/run.mdx index 12e97556c2..18005b01a9 100644 --- a/models/ref/python/public-api/run.mdx +++ b/models/ref/python/public-api/run.mdx @@ -1,760 +1,222 @@ --- title: Run -namespace: public_apis_namespace -python_object_type: class +kind: class +namespace: wandb.apis.public.runs --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - - - - - - -## class `Run` -A single run associated with an entity and project. - -### method `Run.__init__` - -```python -__init__( - client: 'RetryingClient', - entity: 'str', - project: 'str', - run_id: 'str', - attrs: 'Mapping | None' = None, - include_sweeps: 'bool' = True, - lazy: 'bool' = True, - service_api: 'ServiceApi | None' = None -) -``` - -**Args:** - - - `client`: The W&B API client. - - `entity`: The entity associated with the run. - - `project`: The project associated with the run. - - `run_id`: The unique identifier for the run. - - `attrs`: The attributes of the run. - - `include_sweeps`: Whether to include sweeps in the run. - - - -**Attributes:** - - - `tags` ([str]): a list of tags associated with the run - - `url` (str): the url of this run - - `id` (str): unique identifier for the run (defaults to eight characters) - - `name` (str): the name of the run - - `state` (str): one of: running, finished, crashed, killed, preempting, preempted - - `config` (dict): a dict of hyperparameters associated with the run - - `created_at` (str): ISO timestamp when the run was started - - `system_metrics` (dict): the latest system metrics recorded for the run - - `summary` (dict): A mutable dict-like property that holds the current summary. Calling update will persist any changes. - - `project` (str): the project associated with the run - - `entity` (str): the name of the entity associated with the run - - `project_internal_id` (int): the internal id of the project - - `user` (str): the name of the user who created the run - - `path` (str): Unique identifier [entity]/[project]/[run_id] - - `notes` (str): Notes about the run - - `read_only` (boolean): Whether the run is editable - - `history_keys` (str): History metric keys logged with `wandb.Run.log({"key": "value"})` - - `metadata` (str): Metadata about the run from wandb-metadata.json - - -Initialize a Run object. - -Run is always initialized by calling api.runs() where api is an instance of wandb.Api. - - ---- - -### property Run.config - -Get run config. Auto-loads full data if in lazy mode. - - - -**Returns:** - - `dict[str, Any]`: The config property value. ---- - -### property Run.entity - -The entity associated with the run. - - - -**Returns:** - - `str`: The entity property value. ---- - -### property Run.id - -The unique identifier for the run. - - - -**Returns:** - - `str`: The id property value. ---- - - -### property Run.lastHistoryStep - -Returns the last step logged in the run's history. - - - -**Returns:** - - `int`: The lastHistoryStep property value. ---- - -### property Run.metadata - -Metadata about the run from wandb-metadata.json. - -Metadata includes the run's description, tags, start time, memory usage and more. - - - -**Returns:** - - `dict[str, Any] | None`: The metadata property value. ---- - -### property Run.name - -The name of the run. - - - -**Returns:** - - `str | None`: The name property value. ---- - -### property Run.path - -The path of the run. The path is a list containing the entity, project, and run_id. - - - -**Returns:** - - `list[str]`: The path property value. ---- - -### property Run.rawconfig - -Get raw run config including internal keys. Auto-loads full data if in lazy mode. - - - -**Returns:** - - `dict[str, Any]`: The rawconfig property value. ---- - -### property Run.state - -The state of the run. Can be one of: Finished, Failed, Crashed, or Running. - - - -**Returns:** - - `str`: The state property value. ---- - -### property Run.storage_id - -The unique storage identifier for the run. - - - -**Returns:** - - `str`: The storage_id property value. ---- - -### property Run.summary - -Get run summary metrics. Auto-loads full data if in lazy mode. - - - -**Returns:** - - `HTTPSummary`: The summary property value. ---- - -### property Run.summary_metrics - -Get run summary metrics. Auto-loads full data if in lazy mode. - - - -**Returns:** - - `dict[str, Any]`: The summary_metrics property value. ---- - -### property Run.sweep_name - -Get sweep name. Always available since sweepName is in lightweight fragment. - - - -**Returns:** - - `str | None`: The sweep_name property value. ---- - -### property Run.system_metrics - -Get run system metrics. Auto-loads full data if in lazy mode. - - - -**Returns:** - - `dict[str, Any]`: The system_metrics property value. ---- - -### property Run.url - -The URL of the run. - -The run URL is generated from the entity, project, and run_id. For SaaS users, it takes the form of `https://wandb.ai/entity/project/run_id`. - - - -**Returns:** - - `str`: The url property value. ---- - -### property Run.username - -This API is deprecated. Use `entity` instead. - - - - - -**Returns:** - - `str`: The username property value. ---- - -### method `Run.beta_scan_history` - -```python -beta_scan_history( - keys: 'list[str] | None' = None, - page_size: 'int' = 1000, - min_step: 'int' = 0, - max_step: 'int | None' = None, - use_cache: 'bool' = True -) → public.BetaHistoryScan -``` - -Returns an iterable collection of all history records for a run. - -This function is still in development and may not work as expected. It uses wandb-core to read history from a run's exported parquet history locally. - - - -**Args:** - - - `keys`: list of metrics to read from the run's history. if no keys are provided then all metrics will be returned. - - `page_size`: the number of history records to read at a time. - - `min_step`: The minimum step to start reading history from (inclusive). - - `max_step`: The maximum step to read history up to (exclusive). - - `use_cache`: When set to True, checks the WANDB_CACHE_DIR for a run history. If the run history is not found in the cache, it will be downloaded from the server. If set to False, the run history will be downloaded every time. - - - -**Returns:** - A BetaHistoryScan object, which can be iterator over to get history records. - ---- - -### classmethod `Run.create` - -```python -create( - api: 'public.Api', - run_id: 'str | None' = None, - project: 'str | None' = None, - entity: 'str | None' = None, - state: "Literal['running', 'pending']" = 'running' -) → Self -``` - -Create a run for the given project. - -For most use cases, use `wandb.init()`. `wandb.init()` provides more robust logic for creating and updating runs. `wandb.apis.public.Run.create` is intended for specific scenarios such as creating runs in a "pending" state for jobs that may be unschedulable (for example, in a Kubernetes cluster with insufficient GPUs or high contention). These pending runs can later be resumed and tracked by W&B. - -Runs created with this method have limited functionality. Calling `update()` on a run created this way may not work as expected. - - - -**Args:** - - - `api`: The W&B API instance. - - `run_id`: Optional run ID. If not provided, a random ID will be generated. - - `project`: Optional project name. Defaults to the project in API settings or "uncategorized". - - `entity`: Optional entity (user or team) name. - - `state`: Initial state of the run. Use "pending" for runs that will be resumed later, or "running" for immediate execution. - - - -**Returns:** - A Run object representing the created run. - - - -**Example:** - Creating a pending run for later execution - -```python -import wandb - -api = wandb.Api() - -run_name = "my-pending-run" - -run = Run.create( - api=api, - project="project", - entity="entity", - state="pending", - run_id=run_name, -) -``` - ---- - -### method `Run.delete` - -```python -delete(delete_artifacts: 'bool' = False) → None -``` - -Delete the given run from the wandb backend. - - - -**Args:** - - - `delete_artifacts` (bool, optional): Whether to delete the artifacts associated with the run. - ---- - -### method `Run.download_history_exports` - -```python -download_history_exports( - download_dir: 'pathlib.Path | str', - require_complete_history: 'bool' = True -) → runhistory.DownloadHistoryResult -``` - -Download any parquet history files for the run to the provided directory. - - - -**Args:** - - - `download_dir`: The directory to download the history files to. - - `require_complete_history`: Whether to require the complete history to be downloaded. If true, and the run contains data that has not been exported to parquet files yet, an IncompleteRunHistoryError will be raised. - - - -**Returns:** - A DownloadHistoryResult. - - - -**Raises:** - - - `IncompleteRunHistoryError`: If require_complete_history is True and the run contains data not yet exported to parquet files. - - `WandbApiFailedError`: If the API request fails for reasons other than incomplete history. - ---- - -### method `Run.file` - -```python -file(name: 'str') → public.File -``` - -Return the path of a file with a given name in the artifact. - - - -**Args:** - - - `name` (str): name of requested file. - - - -**Returns:** - A `File` matching the name argument. - ---- - -### method `Run.files` - -```python -files( - names: 'list[str] | None' = None, - pattern: 'str | None' = None, - per_page: 'int' = 50 -) → public.Files -``` - -Returns a `Files` object for all files in the run which match the given criteria. - -You can specify a list of exact file names to match, or a pattern to match against. If both are provided, the pattern will be ignored. - - - -**Args:** - - - `names` (list): names of the requested files, if empty returns all files - - `pattern` (str, optional): Pattern to match when returning files from W&B. This pattern uses mySQL's LIKE syntax, so matching all files that end with .json would be "%.json". If both names and pattern are provided, a ValueError will be raised. - - `per_page` (int): number of results per page. - - - -**Returns:** - A `Files` object, which is an iterator over `File` objects. - ---- - -### method `Run.history` - -```python -history( - samples: 'int' = 500, - keys: 'list[str] | None' = None, - x_axis: 'str' = '_step', - pandas: 'bool' = True, - stream: "Literal['default', 'system']" = 'default' -) → list[dict[str, Any]] | pd.DataFrame -``` - -Return sampled history metrics for a run. - -This is simpler and faster if you are ok with the history records being sampled. - - - -**Args:** - - - `samples `: (int, optional) The number of samples to return - - `pandas `: (bool, optional) Return a pandas dataframe - - `keys `: (list, optional) Only return metrics for specific keys - - `x_axis `: (str, optional) Use this metric as the xAxis defaults to _step - - `stream `: (str, optional) "default" for metrics, "system" for machine metrics - - - -**Returns:** - - - `pandas.DataFrame`: If pandas=True returns a `pandas.DataFrame` of history metrics. - - `list of dicts`: If pandas=False returns a list of dicts of history metrics. - ---- - -### method `Run.load` - -```python -load(force: 'bool' = False) → dict[str, Any] -``` - -Load run data using appropriate fragment based on lazy mode. - ---- - -### method `Run.load_full_data` - -```python -load_full_data(force: 'bool' = False) → dict[str, Any] -``` - -Load full run data including heavy fields like config, systemMetrics, summaryMetrics. - -This method is useful when you initially used lazy=True for listing runs, but need access to the full data for specific runs. - - - -**Args:** - - - `force`: Force reload even if data is already loaded - - - -**Returns:** - The loaded run attributes - ---- - -### method `Run.log_artifact` - -```python -log_artifact( - artifact: 'wandb.Artifact', - aliases: 'Collection[str] | None' = None, - tags: 'Collection[str] | None' = None -) → wandb.Artifact -``` - -Declare an artifact as output of a run. - +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; -**Args:** - - - `artifact` (`Artifact`): An artifact returned from `wandb.Api().artifact(name)`. - - `aliases` (list, optional): Aliases to apply to this artifact. - - `tags`: (list, optional) Tags to apply to this artifact, if any. + -**Returns:** - A `Artifact` object. ---- -### method `Run.logged_artifacts` -```python -logged_artifacts(per_page: 'int' = 100) → public.RunArtifacts -``` +## Description -Fetches all artifacts logged by this run. +A single run associated with an entity and project. -Retrieves all output artifacts that were logged during the run. Returns a paginated result that can be iterated over or collected into a single list. +## Args: -**Args:** - - - `per_page`: Number of artifacts to fetch per API request. +- **client**: The W&B API client. +- **entity**: The entity associated with the run. +- **project**: The project associated with the run. +- **run_id**: The unique identifier for the run. +- **attrs**: The attributes of the run. +- **include_sweeps**: Whether to include sweeps in the run. +- **lazy**: Whether to lazily load run data or fetch full data immediately. +- **service_api**: Optional ServiceApi instance for making additional API calls. +## Properties: -**Returns:** - An iterable collection of all Artifact objects logged as outputs during this run. +### state +The state of the run. Can be one of: Finished, Failed, Crashed, or Running. +### entity -**Example:** - ```python -import wandb -import tempfile +The entity associated with the run. -with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".txt") as tmp: - tmp.write("This is a test artifact") - tmp_path = tmp.name -run = wandb.init(project="artifact-example") -artifact = wandb.Artifact("test_artifact", type="dataset") -artifact.add_file(tmp_path) -run.log_artifact(artifact) -run.finish() +### username -api = wandb.Api() +This API is deprecated. Use `entity` instead. -finished_run = api.run(f"{run.entity}/{run.project}/{run.id}") +### storage_id -for logged_artifact in finished_run.logged_artifacts(): - print(logged_artifact.name) -``` +The unique storage identifier for the run. ---- +### id -### method `Run.save` +The unique identifier for the run. -```python -save() → None -``` +### name -Persist changes to the run object to the W&B backend. +The name of the run. ---- +### config -### method `Run.scan_history` +Get run config. Auto-loads full data if in lazy mode. -```python -scan_history( - keys: 'list[str] | None' = None, - page_size: 'int' = 1000, - min_step: 'int | None' = None, - max_step: 'int | None' = None -) → Iterator[dict[str, Any]] -``` +### summary -Returns an iterable collection of all history records for a run. +Get run summary metrics. Auto-loads full data if in lazy mode. +### system_metrics +Get run system metrics. Auto-loads full data if in lazy mode. -**Args:** - - - `keys` ([str], optional): only fetch these keys, and only fetch rows that have all of keys defined. - - `page_size` (int, optional): size of pages to fetch from the api. - - `min_step` (int, optional): the minimum number of pages to scan at a time. - - `max_step` (int, optional): the maximum number of pages to scan at a time. +### summary_metrics +Get run summary metrics. Auto-loads full data if in lazy mode. +### rawconfig -**Returns:** - An iterable collection over history records (dict). +Get raw run config including internal keys. Auto-loads full data if in lazy mode. +### sweep_name +Get sweep name. Always available since sweepName is in lightweight fragment. -**Example:** - Export all the loss values for an example run +### path -```python -run = api.run("entity/project-name/run-id") -history = run.scan_history(keys=["Loss"]) -losses = [row["Loss"] for row in history] -``` +The path of the run. The path is a list containing the entity, project, and run_id. ---- +### url -### method `Run.to_html` +The URL of the run. -```python -to_html(height: 'int' = 420, hidden: 'bool' = False) → str -``` +The run URL is generated from the entity, project, and run_id. For +SaaS users, it takes the form of `https://wandb.ai/entity/project/run_id`. -Generate HTML containing an iframe displaying this run. +### metadata ---- +Metadata about the run from wandb-metadata.json. -### method `Run.update` +Metadata includes the run's description, tags, start time, memory +usage and more. -```python -update() → None -``` +### lastHistoryStep -Persist changes to the run object to the wandb backend. +Returns the last step logged in the run's history. ---- -### method `Run.update_state` -```python -update_state(state: "Literal['pending']") → bool -``` +## Methods: -Update the state of a run. +### beta_scan_history -Allows transitioning runs from 'failed' or 'crashed' to 'pending'. +Returns an iterable collection of all history records for a run. +This function is still in development and may not work as expected. +It uses wandb-core to read history from a run's exported +parquet history locally. +### create -**Args:** - - - `state`: The target run state. Only `"pending"` is supported. +Create a run for the given project. +For most use cases, use `wandb.init()`. `wandb.init()` provides more robust +logic for creating and updating runs. `wandb.apis.public.Run.create` +is intended for specific scenarios such as creating runs in +a "pending" state for jobs that may be unschedulable +(for example, in a Kubernetes cluster with insufficient GPUs or high +contention). These pending runs can later be resumed and tracked by W&B. +Runs created with this method have limited functionality. Calling +`update()` on a run created this way may not work as expected. -**Returns:** - `True` if the state was successfully updated. +### delete +Delete the given run from the wandb backend. +### display -**Raises:** - - - ``wandb.Error``: If the requested state transition is not allowed, or the server does not support this operation. +Display this object in jupyter. ---- +### download_history_exports -### method `Run.upload_file` +Download any parquet history files for the run to the provided directory. -```python -upload_file(path: 'str', root: 'str' = '.') → public.File -``` +### file -Upload a local file to W&B, associating it with this run. +Return the path of a file with a given name in the artifact. +### files +Returns a `Files` object for all files in the run which match the given criteria. -**Args:** - - - `path` (str): Path to the file to upload. Can be absolute or relative. - - `root` (str): The root path to save the file relative to. For example, if you want to have the file saved in the run as "my_dir/file.txt" and you're currently in "my_dir" you would set root to "../". Defaults to current directory ("."). +You can specify a list of exact file names to match, or a pattern to match against. +If both are provided, the pattern will be ignored. +### history +Return sampled history metrics for a run. -**Returns:** - A `File` object representing the uploaded file. +This is simpler and faster if you are ok with the history records being sampled. ---- +### load -### method `Run.use_artifact` +Load run data using appropriate fragment based on lazy mode. -```python -use_artifact( - artifact: 'wandb.Artifact', - use_as: 'str | None' = None -) → wandb.Artifact -``` +### load_full_data -Declare an artifact as an input to a run. +Load full run data including heavy fields like config, systemMetrics, summaryMetrics. +This method is useful when you initially used lazy=True for listing runs, +but need access to the full data for specific runs. +### log_artifact -**Args:** - - - `artifact` (`Artifact`): An artifact returned from `wandb.Api().artifact(name)` - - `use_as` (string, optional): A string identifying how the artifact is used in the script. Used to easily differentiate artifacts used in a run, when using the beta wandb launch feature's artifact swapping functionality. +Declare an artifact as output of a run. +### logged_artifacts +Fetches all artifacts logged by this run. -**Returns:** - An `Artifact` object. +Retrieves all output artifacts that were logged during the run. Returns a +paginated result that can be iterated over or collected into a single list. ---- +### save -### method `Run.used_artifacts` +Persist changes to the run object to the W&B backend. -```python -used_artifacts(per_page: 'int' = 100) → public.RunArtifacts -``` +### scan_history -Fetches artifacts explicitly used by this run. +Returns an iterable collection of all history records for a run. -Retrieves only the input artifacts that were explicitly declared as used during the run, typically via `run.use_artifact()`. Returns a paginated result that can be iterated over or collected into a single list. +### update +Persist changes to the run object to the wandb backend. +### update_state -**Args:** - - - `per_page`: Number of artifacts to fetch per API request. +Update the state of a run. +Allows transitioning runs from 'failed' or 'crashed' to 'pending'. +### upload_file -**Returns:** - An iterable collection of Artifact objects explicitly used as inputs in this run. +Upload a local file to W&B, associating it with this run. +### use_artifact +Declare an artifact as an input to a run. -**Example:** - ```python -import wandb +### used_artifacts -run = wandb.init(project="artifact-example") -run.use_artifact("test_artifact:latest") -run.finish() +Fetches artifacts explicitly used by this run. -api = wandb.Api() -finished_run = api.run(f"{run.entity}/{run.project}/{run.id}") -for used_artifact in finished_run.used_artifacts(): - print(used_artifact.name) -test_artifact -``` +Retrieves only the input artifacts that were explicitly declared as used +during the run, typically via `run.use_artifact()`. Returns a paginated +result that can be iterated over or collected into a single list. ---- +### wait_until_finished -### method `Run.wait_until_finished` +Check the state of the run until it is finished. -```python -wait_until_finished() → None -``` -Check the state of the run until it is finished. diff --git a/models/ref/python/public-api/runartifacts.mdx b/models/ref/python/public-api/runartifacts.mdx index eedbe04bfe..0ab3cc5740 100644 --- a/models/ref/python/public-api/runartifacts.mdx +++ b/models/ref/python/public-api/runartifacts.mdx @@ -1,36 +1,44 @@ --- title: RunArtifacts -namespace: public_apis_namespace -python_object_type: class +kind: class +namespace: wandb.apis.public.artifacts --- + import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - + -## class `RunArtifacts` -An iterable collection of artifacts associated with a specific run. -### property RunArtifacts.cursor +## Description -An opaque cursor that marks the start of the next page to fetch. +An iterable collection of artifacts associated with a specific run. -This value may be saved and passed as `start=` to a later paginated query to resume iteration from where this paginator left off. + + +## Args: + +- **client**: The client instance to use for querying W&B. +- **run**: The run for which to fetch artifacts. +- **mode**: The mode of artifacts to fetch, either "logged" or "used". +- **per_page**: The number of artifact versions to fetch per page. Default is 50. +- **start**: Pagination cursor for resuming a past query, captured from a previous paginator's `.cursor` attribute. -**Returns:** - - `str | None`: The cursor property value. ---- -### property RunArtifacts.more +## Methods: +### next +Return the next item from the iterator. When exhausted, raise StopIteration +### update_variables +Update the query variables for the next page fetch. diff --git a/models/ref/python/public-api/runs.mdx b/models/ref/python/public-api/runs.mdx index aebd7ce9fe..e34382876a 100644 --- a/models/ref/python/public-api/runs.mdx +++ b/models/ref/python/public-api/runs.mdx @@ -1,106 +1,64 @@ --- title: Runs -namespace: public_apis_namespace -python_object_type: class +kind: class +namespace: wandb.apis.public.runs --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - - - - +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; -## class `Runs` -A lazy iterator of `Run` objects associated with a project and optional filter. - -Runs are retrieved in pages from the W&B server as needed. - -This is generally used indirectly using the `Api.runs` namespace. - -### method `Runs.__init__` - -```python -__init__( - client: 'RetryingClient', - entity: 'str', - project: 'str', - filters: 'dict[str, Any] | None' = None, - order: 'str' = '+created_at', - per_page: 'int' = 50, - include_sweeps: 'bool' = True, - lazy: 'bool' = True, - service_api: 'ServiceApi | None' = None -) -``` - -**Args:** - - - `client`: (`wandb.apis.public.RetryingClient`) The API client to use for requests. - - `entity`: (str) The entity (username or team) that owns the project. - - `project`: (str) The name of the project to fetch runs from. - - `filters`: (Optional[Dict[str, Any]]) A dictionary of filters to apply to the runs query. - - `order`: (str) Order can be `created_at`, `heartbeat_at`, `config.*.value`, or `summary_metrics.*`. If you prepend order with a + order is ascending (default). If you prepend order with a - order is descending. The default order is run.created_at from oldest to newest. - - `per_page`: (int) The number of runs to fetch per request (default is 50). - - `include_sweeps`: (bool) Whether to include sweep information in the runs. Defaults to True. + +## Description ---- +A lazy iterator of `Run` objects associated with a project and optional filter. +Runs are retrieved in pages from the W&B server as needed. -### property Runs.length +This is generally used indirectly using the `Api.runs` namespace. +## Args: +- **client**: (`wandb.apis.public.RetryingClient`) The API client to use for requests. +- **entity**: (str) The entity (username or team) that owns the project. +- **project**: (str) The name of the project to fetch runs from. +- **filters**: (Optional[Dict[str, Any]]) A dictionary of filters to apply to the runs query. +- **order**: (str) Order can be `created_at`, `heartbeat_at`, `config.*.value`, or `summary_metrics.*`. If you prepend order with a + order is ascending (default). If you prepend order with a - order is descending. The default order is run.created_at from oldest to newest. +- **per_page**: (int) The number of runs to fetch per request (default is 50). +- **include_sweeps**: (bool) Whether to include sweep information in the runs. Defaults to True. +- **lazy**: (bool) Whether to lazily load run data or fetch full data immediately. +- **service_api**: (Optional[ServiceApi]) An optional ServiceApi instance for making additional API calls, such as fetching run history exports. ---- -### method `Runs.histories` +## Methods: -```python -histories( - samples: 'int' = 500, - keys: 'list[str] | None' = None, - x_axis: 'str' = '_step', - format: "Literal['default', 'pandas', 'polars']" = 'default', - stream: "Literal['default', 'system']" = 'default' -) → list[dict[str, Any]] | pd.DataFrame | pl.DataFrame -``` +### histories -Return sampled history metrics for all runs that fit the filters conditions. +Return sampled history metrics for all runs that fit the filters conditions. +### next +Return the next item from the iterator. When exhausted, raise StopIteration -**Args:** - - - `samples`: The number of samples to return per run - - `keys`: Only return metrics for specific keys - - `x_axis`: Use this metric as the xAxis defaults to _step - - `format`: Format to return data in, options are "default", "pandas", "polars" - - `stream`: "default" for metrics, "system" for machine metrics +### update_variables -**Returns:** - - - `pandas.DataFrame`: If `format="pandas"`, returns a `pandas.DataFrame` of history metrics. - - `polars.DataFrame`: If `format="polars"`, returns a `polars.DataFrame` of history metrics. - - `list of dicts`: If `format="default"`, returns a list of dicts containing history metrics with a `run_id` key. +Update the query variables for the next page fetch. ---- +### upgrade_to_full -### method `Runs.upgrade_to_full` +Upgrade this Runs collection from lazy to full mode. -```python -upgrade_to_full() → None -``` +This switches to fetching full run data and +upgrades any already-loaded Run objects to have full data. +Uses parallel loading for better performance when upgrading multiple runs. -Upgrade this Runs collection from lazy to full mode. -This switches to fetching full run data and upgrades any already-loaded Run objects to have full data. Uses parallel loading for better performance when upgrading multiple runs. diff --git a/models/ref/python/public-api/sweep.mdx b/models/ref/python/public-api/sweep.mdx index b9c21383c6..b17fd106bd 100644 --- a/models/ref/python/public-api/sweep.mdx +++ b/models/ref/python/public-api/sweep.mdx @@ -1,190 +1,103 @@ --- title: Sweep -namespace: public_apis_namespace -python_object_type: class ---- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - - - - - - -## class `Sweep` -The set of runs associated with the sweep. - - - -**Attributes:** - - - `runs` (Runs): List of runs - - `id` (str): Sweep ID - - `project` (str): The name of the project the sweep belongs to - - `config` (dict): Dictionary containing the sweep configuration - - `state` (str): The state of the sweep. Can be "Finished", "Failed", "Crashed", or "Running". - - `expected_run_count` (int): The number of expected runs for the sweep - -### method `Sweep.__init__` - -```python -__init__( - client: 'RetryingClient', - entity: 'str', - project: 'str', - sweep_id: 'str', - attrs: 'Mapping[str, Any] | None' = None -) -``` - - - - - - ---- - -### property Sweep.config - -The sweep configuration used for the sweep. - +kind: class +namespace: wandb.apis.public.sweeps --- -### property Sweep.entity - -The entity associated with the sweep. - - - -**Returns:** - - `str`: The entity property value. ---- - -### property Sweep.expected_run_count - -Return the number of expected runs in the sweep or None for infinite runs. - - - -**Returns:** - - `int | None`: The expected_run_count property value. ---- +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; -### property Sweep.name -The name of the sweep. + -Returns the first name that exists in the following priority order: -1. User-edited display name 2. Name configured at creation time 3. Sweep ID ---- -### property Sweep.order -Return the order key for the sweep. +## Description ---- +The set of runs associated with the sweep. -### property Sweep.path -Returns the path of the project. -The path is a list containing the entity, project name, and sweep ID. +## Args: ---- +- **client**: The API client used to query W&B. +- **entity**: The entity which owns the sweep. +- **project**: The project which contains the sweep. +- **sweep_id**: The unique identifier for the sweep. +- **attrs**: The attributes of the sweep, typically obtained from a GraphQL response. -### property Sweep.url -The URL of the sweep. +## Properties: -The sweep URL is generated from the entity, project, the term "sweeps", and the sweep ID.run_id. For SaaS users, it takes the form of `https://wandb.ai/entity/project/sweeps/sweeps_ID`. +### entity ---- +The entity associated with the sweep. -### property Sweep.username +### username -Deprecated. Use `Sweep.entity` instead. +Deprecated. Use `Sweep.entity` instead. +### config +The sweep configuration used for the sweep. +### order +Return the order key for the sweep. -**Returns:** - - `str`: The username property value. ---- +### expected_run_count -### method `Sweep.agent` +Return the number of expected runs in the sweep or None for infinite runs. -```python -agent(agent_id: 'str') → Agent -``` +### path -Query an agent by ID for this sweep. +Returns the path of the project. +The path is a list containing the entity, project name, and sweep ID. +### url -**Args:** - - - `agent_id`: The ID of the agent to look up. +The URL of the sweep. ---- +The sweep URL is generated from the entity, project, the term +"sweeps", and the sweep ID.run_id. For +SaaS users, it takes the form +of `https://wandb.ai/entity/project/sweeps/sweeps_ID`. -### method `Sweep.agents` +### name -```python -agents() → list[Agent] -``` +The name of the sweep. -Query the list of all agents for this sweep. +Returns the first name that exists in the following priority order: ---- +1. User-edited display name +2. Name configured at creation time +3. Sweep ID -### method `Sweep.best_run` -```python -best_run(order=None) -``` -Return the best run sorted by the metric defined in config or the order passed in. +## Methods: ---- +### agent -### classmethod `Sweep.get` +Query an agent by ID for this sweep. -```python -get( - client: 'RetryingClient', - entity: 'str | None' = None, - project: 'str | None' = None, - sid: 'str | None' = None, - order: 'str | None' = None, - query: 'Document | None' = None, - **kwargs -) -``` +### agents -Execute a query against the cloud backend. +Query the list of all agents for this sweep. +### best_run +Return the best run sorted by the metric defined in config or the order passed in. -**Args:** - - - `client`: The client to use to execute the query. - - `entity`: The entity (username or team) that owns the project. - - `project`: The name of the project to fetch sweep from. - - `sid`: The sweep ID to query. - - `order`: The order in which the sweep's runs are returned. - - `query`: The query to use to execute the query. - - `**kwargs`: Additional keyword arguments to pass to the query. +### display ---- +Display this object in jupyter. +### get -### method `Sweep.to_html` +Execute a query against the cloud backend. -```python -to_html(height: 'int' = 420, hidden: 'bool' = False) → str -``` -Generate HTML containing an iframe displaying this sweep. diff --git a/models/ref/python/public-api/sweeps.mdx b/models/ref/python/public-api/sweeps.mdx index 968110b396..8461c9548e 100644 --- a/models/ref/python/public-api/sweeps.mdx +++ b/models/ref/python/public-api/sweeps.mdx @@ -1,66 +1,56 @@ --- title: Sweeps -namespace: public_apis_namespace -python_object_type: class +kind: class +namespace: wandb.apis.public.sweeps --- + import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - + + + -## class `Sweeps` -A lazy iterator over a collection of `Sweep` objects. +## Description +A lazy iterator over a collection of `Sweep` objects. +## Examples: -**Examples:** - ```python +```python from wandb.apis.public import Api sweeps = Api().project(name="project_name", entity="entity").sweeps() # Iterate over sweeps and print details for sweep in sweeps: - print(f"Sweep name: {sweep.name}") - print(f"Sweep ID: {sweep.id}") - print(f"Sweep URL: {sweep.url}") - print("----------") -``` - -### method `Sweeps.__init__` - -```python -__init__( - client: 'RetryingClient', - entity: 'str', - project: 'str', - per_page: 'int' = 50 -) → Sweeps + print(f"Sweep name: {sweep.name}") + print(f"Sweep ID: {sweep.id}") + print(f"Sweep URL: {sweep.url}") + print("----------") ``` -An iterable collection of `Sweep` objects. - +## Args: +- **client**: The API client used to query W&B. +- **entity**: The entity which owns the sweeps. +- **project**: The project which contains the sweeps. +- **per_page**: The number of sweeps to fetch per request to the API. -**Args:** - - - `client`: The API client used to query W&B. - - `entity`: The entity which owns the sweeps. - - `project`: The project which contains the sweeps. - - `per_page`: The number of sweeps to fetch per request to the API. ---- +## Methods: -### property Sweeps.length +### next +Return the next item from the iterator. When exhausted, raise StopIteration +### update_variables +Update the query variables for the next page fetch. ---- - diff --git a/models/ref/python/public-api/team.mdx b/models/ref/python/public-api/team.mdx index 61eda62f1f..ce65f245a7 100644 --- a/models/ref/python/public-api/team.mdx +++ b/models/ref/python/public-api/team.mdx @@ -1,115 +1,54 @@ --- title: Team -namespace: public_apis_namespace -python_object_type: class +kind: class +namespace: wandb.apis.public.teams --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - - - - - - -## class `Team` -A class that represents a W&B team. - -This class provides methods to manage W&B teams, including creating teams, inviting members, and managing service accounts. It inherits from Attrs to handle team attributes. - -### method `Team.__init__` - -```python -__init__( - client: 'RetryingClient', - name: 'str', - attrs: 'Mapping[str, Any] | None' = None -) -``` - -**Args:** - - - `client` (`wandb.apis.public.Api`): The api instance to use - - `name` (str): The name of the team - - `attrs` (dict): Optional dictionary of team attributes - - - -**Note:** - -> Team management requires appropriate permissions. - +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; + ---- - -### classmethod `Team.create` - -```python -create(api: 'Api', team: 'str', admin_username: 'str | None' = None) → Self -``` - -Create a new team. - - - -**Args:** - - - `api`: (`Api`) The api instance to use - - `team`: (str) The name of the team - - `admin_username`: (str) optional username of the admin user of the team, defaults to the current user. - - +## Description -**Returns:** - A `Team` object +A class that represents a W&B team. ---- +This class provides methods to manage W&B teams, including creating teams, +inviting members, and managing service accounts. It inherits from Attrs +to handle team attributes. -### method `Team.create_service_account` -```python -create_service_account(description: 'str') → Member | None -``` -Create a service account for the team. +## Args: +- **client**: The api instance to use +- **name**: The name of the team +- **attrs**: Optional dictionary of team attributes -**Args:** - - - `description`: (str) A description for this service account +## Methods: -**Returns:** - The service account `Member` object, or None on failure +### create ---- +Create a new team. -### method `Team.invite` +### create_service_account -```python -invite(username_or_email: 'str', admin: 'bool' = False) → bool -``` +Create a service account for the team. -Invite a user to a team. +### display +Display this object in jupyter. +### invite -**Args:** - - - `username_or_email`: (str) The username or email address of the user you want to invite. - - `admin`: (bool) Whether to make this user a team admin. Defaults to `False`. +Invite a user to a team. -**Returns:** - `True` on success, `False` if user was already invited or didn't exist. - ---- - diff --git a/models/ref/python/public-api/user.mdx b/models/ref/python/public-api/user.mdx index 280747f38c..b432368c7f 100644 --- a/models/ref/python/public-api/user.mdx +++ b/models/ref/python/public-api/user.mdx @@ -1,106 +1,83 @@ --- title: User -namespace: public_apis_namespace -python_object_type: class +kind: class +namespace: wandb.apis.public.users --- -import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; - - - - - - -## class `User` -A user on a W&B instance. - -This allows managing a user's API keys and accessing information like team memberships. The `create` class method can be used to create a new user. - - -**Args:** - - - `client`: The GraphQL client to use for network operations. - - `attrs`: A subset of the User type in the GraphQL schema. - - -### property User.api_keys - -Names of the user's API keys. +import { GitHubLink } from '/snippets/_includes/github-source-link.mdx'; -This property returns the names of the API keys, *not* the secret associated with the key. The name of the key cannot be used as an API key. -The list is empty if the user has no API keys or if API keys have not been loaded. + -**Returns:** - - `list[str]`: The api_keys property value. ---- -### property User.teams -Names of the user's teams. +## Description -This is an empty list if the user has no team memberships or if teams data was not loaded. +A user on a W&B instance. +This allows managing a user's API keys and accessing information like +team memberships. The `create` class method can be used to create a new +user. -**Returns:** - - `list[str]`: The teams property value. ---- -### property User.user_api +## Args: -A `wandb.Api` instance using the user's credentials. +- **client**: The GraphQL client to use for network operations. +- **attrs**: A subset of the User type in the GraphQL schema. +- **api_key**: An optional API key for the user, used to create a `wandb.Api` instance for the user. This is required for some operations, such as generating new API keys for the user. +## Properties: +### user_api +A `wandb.Api` instance using the user's credentials. -**Returns:** - - `Api | None`: The user_api property value. ---- +### api_keys +Names of the user's API keys. -### method `User.delete_api_key` +This property returns the names of the the API keys, *not* the secret +associated with the key. The name of the key cannot be used as an API +key. -```python -delete_api_key(api_key: 'str') → bool -``` +The list is empty if the user has no API keys or if API keys have not +been loaded. -Delete a user's API key. +### teams -Only the owner of the key or an admin can delete it. +Names of the user's teams. +This is an empty list if the user has no team memberships or if teams +data was not loaded. -**Args:** - - - `api_key`: The name of the API key to delete. Use one of the names returned by the `api_keys` property. +## Methods: +### create -**Returns:** - True on success, false on failure. +Create a new user. ---- +This is an internal method. Use the `create_user()` method of +`wandb.Api` instead. -### method `User.generate_api_key` +### delete_api_key -```python -generate_api_key(description: 'str | None' = None) → str | None -``` +Delete a user's API key. -Generate a new API key. +Only the owner of the key or an admin can delete it. +### display +Display this object in jupyter. -**Args:** - - - `description`: A description for the new API key. This can be used to identify the purpose of the API key. +### generate_api_key +Generate a new API key. -**Returns:** - The generated API key (the full secret, not just the name), or None on failure.