Query and analyze data logged to W&B.
This is the multi-page printable view of this section. Click here to print.
Analytics and Query API
- 1: api
- 2: artifacts
- 3: files
- 4: history
- 5: jobs
- 6: projects
- 7: query_generator
- 8: reports
- 9: runs
- 10: sweeps
- 11: teams
- 12: users
1 - api
module wandb.apis.public
Use the Public API to export or update data that you have saved to W&B.
Before using this API, you’ll want to log data from your script — check the Quickstart for more details.
You might use the Public API to
- update metadata or metrics for an experiment after it has been completed,
- pull down your results as a dataframe for post-hoc analysis in a Jupyter notebook, or
- check your saved model artifacts for those tagged as
ready-to-deploy
.
For more on using the Public API, check out our guide.
class RetryingClient
method RetryingClient.__init__
__init__(client: wandb_gql.client.Client)
property RetryingClient.app_url
property RetryingClient.server_info
method RetryingClient.execute
execute(*args, **kwargs)
method RetryingClient.version_supported
version_supported(min_version: str) → bool
class Api
Used for querying the wandb server.
Examples:
Most common way to initialize wandb.Api()
Args:
-
overrides
: (dict) You can setbase_url
if you are using a wandb server -
other than https
: //api.wandb.ai. You can also set defaults forentity
,project
, andrun
.
method Api.__init__
__init__(
overrides: Optional[Dict[str, Any]] = None,
timeout: Optional[int] = None,
api_key: Optional[str] = None
) → None
property Api.api_key
property Api.client
property Api.default_entity
property Api.user_agent
property Api.viewer
method Api.artifact
artifact(name: str, type: Optional[str] = None)
Return a single artifact by parsing path in the form project/name
or entity/project/name
.
Args:
name
: (str) An artifact name. May be prefixed with project/ 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
: versionname
: aliastype
: (str, optional) 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.
Note:
This method is intended for external use only. Do not call
api.artifact()
within the wandb repository code.
method Api.artifact_collection
artifact_collection(type_name: str, name: str) → public.ArtifactCollection
Return a single artifact collection by type and parsing path in the form entity/project/name
.
Args:
type_name
: (str) The type of artifact collection to fetch.name
: (str) An artifact collection name. May be prefixed with entity/project.
Returns:
An ArtifactCollection
object.
method Api.artifact_collection_exists
artifact_collection_exists(name: str, type: str) → bool
Return whether an artifact collection exists within a specified project and entity.
Args:
name
: (str) An artifact collection name. May be prefixed with entity/project. If entity or project is not specified, it will be inferred from the override params if populated. Otherwise, entity will be pulled from the user settings and project will default to “uncategorized”.type
: (str) The type of artifact collection
Returns: True if the artifact collection exists, False otherwise.
method Api.artifact_collections
artifact_collections(
project_name: str,
type_name: str,
per_page: int = 50
) → public.ArtifactCollections
Return a collection of matching artifact collections.
Args:
project_name
: (str) The name of the project to filter on.type_name
: (str) The name of the artifact type to filter on.per_page
: (int) Sets the page size for query pagination. Usually there is no reason to change this.
Returns:
An iterable ArtifactCollections
object.
method Api.artifact_exists
artifact_exists(name: str, type: Optional[str] = None) → bool
Return whether an artifact version exists within a specified project and entity.
Args:
name
: (str) An artifact name. May be prefixed with entity/project. If entity or project is not specified, it will be inferred from the override params if populated. Otherwise, entity will be pulled from the user settings and project will default to “uncategorized”. Valid names can be in the following forms:name
: versionname
: aliastype
: (str, optional) The type of artifact
Returns: True if the artifact version exists, False otherwise.
method Api.artifact_type
artifact_type(
type_name: str,
project: Optional[str] = None
) → public.ArtifactType
Return the matching ArtifactType
.
Args:
type_name
: (str) The name of the artifact type to retrieve.project
: (str, optional) If given, a project name or path to filter on.
Returns:
An ArtifactType
object.
method Api.artifact_types
artifact_types(project: Optional[str] = None) → public.ArtifactTypes
Return a collection of matching artifact types.
Args:
project
: (str, optional) If given, a project name or path to filter on.
Returns:
An iterable ArtifactTypes
object.
method Api.artifact_versions
artifact_versions(type_name, name, per_page=50)
Deprecated, use artifacts(type_name, name)
instead.
method Api.artifacts
artifacts(
type_name: str,
name: str,
per_page: int = 50,
tags: Optional[List[str]] = None
) → public.Artifacts
Return an Artifacts
collection from the given parameters.
Args:
type_name
: (str) The type of artifacts to fetch.name
: (str) An artifact collection name. May be prefixed with entity/project.per_page
: (int) Sets the page size for query pagination. Usually there is no reason to change this.tags
: (list[str], optional) Only return artifacts with all of these tags.
Returns:
An iterable Artifacts
object.
method Api.create_project
create_project(name: str, entity: str) → None
Create a new project.
Args:
name
: (str) The name of the new project.entity
: (str) The entity of the new project.
method Api.create_run
create_run(
run_id: Optional[str] = None,
project: Optional[str] = None,
entity: Optional[str] = None
) → public.Run
Create a new run.
Args:
run_id
: (str, optional) The ID to assign to the run, if given. The run ID is automatically generated by default, so in general, you do not need to specify this and should only do so at your own risk.project
: (str, optional) If given, the project of the new run.entity
: (str, optional) If given, the entity of the new run.
Returns:
The newly created Run
.
method Api.create_run_queue
create_run_queue(
name: str,
type: 'public.RunQueueResourceType',
entity: Optional[str] = None,
prioritization_mode: Optional[ForwardRef('public.RunQueuePrioritizationMode')] = None,
config: Optional[dict] = None,
template_variables: Optional[dict] = None
) → public.RunQueue
Create a new run queue (launch).
Args:
name
: (str) Name of the queue to createtype
: (str) Type of resource to be used for the queue. One of “local-container”, “local-process”, “kubernetes”, “sagemaker”, or “gcp-vertex”.entity
: (str) Optional name of the entity to create the queue. If None, will use the configured or default entity.prioritization_mode
: (str) Optional version of prioritization to use. Either “V0” or Noneconfig
: (dict) Optional default resource configuration to be used for the queue. Use handlebars (eg.{{var}}
) to specify template variables.template_variables
: (dict) A dictionary of template variable schemas to be used with the config. Expected format of: `{"var-name"
: {"schema"
: {"type"
: (“string”, “number”, or “integer”),"default"
: (optional value),"minimum"
: (optional minimum),"maximum"
: (optional maximum),"enum"
: […"(options)"] } } }`
Returns:
The newly created RunQueue
Raises: ValueError if any of the parameters are invalid wandb.Error on wandb API errors
method Api.create_team
create_team(team, admin_username=None)
Create a new team.
Args:
team
: (str) The name of the teamadmin_username
: (str) optional username of the admin user of the team, defaults to the current user.
Returns:
A Team
object
method Api.create_user
create_user(email, admin=False)
Create a new user.
Args:
email
: (str) The email address of the useradmin
: (bool) Whether this user should be a global instance admin
Returns:
A User
object
method Api.flush
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
from_path(path)
Return a run, sweep, project or report from a path.
Examples:
project = api.from_path("my_project")
team_project = api.from_path("my_team/my_project")
run = api.from_path("my_team/my_project/runs/id")
sweep = api.from_path("my_team/my_project/sweeps/id")
report = api.from_path("my_team/my_project/reports/My-Report-Vm11dsdf")
```
**Args:**
- `path`: (str) 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
---
### <kbd>method</kbd> `Api.job`
```python
job(name: Optional[str], path: Optional[str] = None) → public.Job
Return a Job
from the given parameters.
Args:
name
: (str) The job name.path
: (str, optional) If given, the root path in which to download the job artifact.
Returns:
A Job
object.
method Api.list_jobs
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
: (str) The entity for the listed job(s).project
: (str) The project for the listed job(s).
Returns: A list of matching jobs.
method Api.project
project(name: str, entity: Optional[str] = None) → public.Project
Return the Project
with the given name (and entity, if given).
Args:
name
: (str) The project name.entity
: (str) Name of the entity requested. If None, will fall back to the default entity passed toApi
. If no default entity, will raise aValueError
.
Returns:
A Project
object.
method Api.projects
projects(entity: Optional[str] = None, per_page: int = 200) → public.Projects
Get projects for a given entity.
Args:
entity
: (str) Name of the entity requested. If None, will fall back to the default entity passed toApi
. If no default entity, will raise aValueError
.per_page
: (int) 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
queued_run(
entity,
project,
queue_name,
run_queue_item_id,
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
registries(
organization: Optional[str] = None,
filter: Optional[Dict[str, Any]] = None
) → Registries
Returns a Registry iterator.
Use the iterator to search and filter registries, collections, or artifact versions across your organization’s registry.
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"}]} )
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 registry iterator. Fields available to filter for collections arename
,description
,created_at
,updated_at
. Fields available to filter for collections arename
,tag
,description
,created_at
,updated_at
Fields available to filter for versions aretag
,alias
,created_at
,updated_at
,metadata
Returns: A registry iterator.
method Api.reports
reports(
path: str = '',
name: Optional[str] = None,
per_page: int = 50
) → public.Reports
Get reports for a given project path.
WARNING: This api is in beta and will likely change in a future release
Args:
path
: (str) path to project the report resides in, should be in the form: “entity/project”name
: (str, optional) optional name of the report requested.per_page
: (int) 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.
method Api.run
run(path='')
Return a single run by parsing path in the form entity/project/run_id.
Args:
path
: (str) path to run in the formentity/project/run_id
. Ifapi.entity
is set, this can be in the formproject/run_id
and ifapi.project
is set this can just be the run_id.
Returns:
A Run
object.
method Api.run_queue
run_queue(entity, name)
Return the named RunQueue
for entity.
To create a new RunQueue
, use wandb.Api().create_run_queue(...)
.
method Api.runs
runs(
path: Optional[str] = None,
filters: Optional[Dict[str, Any]] = None,
order: str = '+created_at',
per_page: int = 50,
include_sweeps: bool = True
)
Return a set of runs from a project that match the filters provided.
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
Examples:
Find runs in my_project where config.experiment_name has been set to “foo” api.runs( path="my_entity/my_project", filters={"config.experiment_name": "foo"}, )
Find runs in my_project where config.experiment_name has been set to “foo” or “bar” api.runs( path="my_entity/my_project", filters={ "$or": [ {"config.experiment_name": "foo"}, {"config.experiment_name": "bar"}, ] }, )
Find runs in my_project where config.experiment_name matches a regex (anchors are not supported) api.runs( path="my_entity/my_project", filters={"config.experiment_name": {"$regex": "b.*"}}, )
Find runs in my_project where the run name matches a regex (anchors are not supported) api.runs( path="my_entity/my_project", filters={"display_name": {"$regex": "^foo.*"}}, )
Find runs in my_project where config.experiment contains a nested field “category” with value “testing” api.runs( path="my_entity/my_project", filters={"config.experiment.category": "testing"}, )
Find runs in my_project with a loss value of 0.5 nested in a dictionary under model1 in the summary metrics api.runs( path="my_entity/my_project", filters={"summary_metrics.model1.loss": 0.5}, )
Find runs in my_project sorted by ascending loss api.runs(path="my_entity/my_project", order="+summary_metrics.loss")
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 becreated_at
,heartbeat_at
,config.*.value
, orsummary_metrics.*
. If you prepend order with a + order is ascending. If you prepend order with a - order is descending (default). 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.
Returns:
A Runs
object, which is an iterable collection of Run
objects.
method Api.sweep
sweep(path='')
Return a sweep by parsing path in the form entity/project/sweep_id
.
Args:
path
: (str, optional) path to sweep in the form entity/project/sweep_id. Ifapi.entity
is set, this can be in the form project/sweep_id and ifapi.project
is set this can just be the sweep_id.
Returns:
A Sweep
object.
method Api.sync_tensorboard
sync_tensorboard(root_dir, run_id=None, project=None, entity=None)
Sync a local directory containing tfevent files to wandb.
method Api.team
team(team: str) → public.Team
Return the matching Team
with the given name.
Args:
team
: (str) The name of the team.
Returns:
A Team
object.
method Api.upsert_run_queue
upsert_run_queue(
name: str,
resource_config: dict,
resource_type: 'public.RunQueueResourceType',
entity: Optional[str] = None,
template_variables: Optional[dict] = None,
external_links: Optional[dict] = None,
prioritization_mode: Optional[ForwardRef('public.RunQueuePrioritizationMode')] = None
)
Upsert a run queue (launch).
Args:
name
: (str) Name of the queue to createentity
: (str) Optional name of the entity to create the queue. If None, will use the configured or default entity.resource_config
: (dict) Optional default resource configuration to be used for the queue. Use handlebars (eg.{{var}}
) to specify template variables.resource_type
: (str) Type of resource to be used for the queue. One of “local-container”, “local-process”, “kubernetes”, “sagemaker”, or “gcp-vertex”.template_variables
: (dict) A dictionary of template variable schemas to be used with the config. Expected format of: `{"var-name"
: {"schema"
: {"type"
: (“string”, “number”, or “integer”),"default"
: (optional value),"minimum"
: (optional minimum),"maximum"
: (optional maximum),"enum"
: […"(options)"] } } }`external_links
: (dict) Optional dictionary of external links to be used with the queue. Expected format of: `{"name"
: “url” }`prioritization_mode
: (str) Optional version of prioritization to use. Either “V0” or None
Returns:
The upserted RunQueue
.
Raises: ValueError if any of the parameters are invalid wandb.Error on wandb API errors
method Api.user
user(username_or_email: str) → Optional[ForwardRef('public.User')]
Return a user from a username or email address.
Note: This function only works for Local Admins, if you are trying to get your own user object, please use api.viewer
.
Args:
username_or_email
: (str) The username or email address of the user
Returns:
A User
object or None if a user couldn’t be found
method Api.users
users(username_or_email: str) → List[ForwardRef('public.User')]
Return all users from a partial username or email address query.
Note: This function only works for Local Admins, if you are trying to get your own user object, please use api.viewer
.
Args:
username_or_email
: (str) The prefix or suffix of the user you want to find
Returns:
An array of User
objects
2 - artifacts
module wandb.apis.public
W&B Public API for Artifact Management.
This module provides classes for interacting with W&B artifacts and their collections. Classes include:
ArtifactTypes: A paginated collection of artifact types in a project
- List and query artifact types
- Access type metadata
- Create new types
ArtifactCollection: A collection of related artifacts
- Manage artifact collections
- Update metadata and descriptions
- Work with tags and aliases
- Change collection types
Artifacts: A paginated collection of artifact versions
- Filter and query artifacts
- Access artifact metadata
- Download artifacts
ArtifactFiles: A paginated collection of files within an artifact
- List and query artifact files
- Access file metadata
- Download individual files
function server_supports_artifact_collections_gql_edges
server_supports_artifact_collections_gql_edges(
client: 'RetryingClient',
warn: bool = False
) → bool
Check if W&B server supports GraphQL edges for artifact collections.
function artifact_collection_edge_name
artifact_collection_edge_name(server_supports_artifact_collections: bool) → str
Return the GraphQL edge name for artifact collections or sequences.
function artifact_collection_plural_edge_name
artifact_collection_plural_edge_name(
server_supports_artifact_collections: bool
) → str
Return the GraphQL edge name for artifact collections or sequences.
class ArtifactTypes
An iterable collection of artifact types associated with a project.
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.per_page
: The number of artifact types to fetch per page. Default is 50.
method ArtifactTypes.__init__
__init__(
client: wandb_gql.client.Client,
entity: str,
project: str,
per_page: int = 50
)
property ArtifactTypes.cursor
Returns the cursor position for pagination of file results.
property ArtifactTypes.length
Returns None
.
property ArtifactTypes.more
Returns True
if there are more artifacts to fetch. Returns False
if there are no more files to fetch.
method ArtifactTypes.convert_objects
convert_objects()
Converts GraphQL edges to ArtifactType objects.
method ArtifactTypes.update_variables
update_variables()
Updates the variables dictionary with the cursor.
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 mapping of attributes to initialize the artifact type. If not provided, the object will load its attributes from W&B upon initialization.
method ArtifactType.__init__
__init__(
client: wandb_gql.client.Client,
entity: str,
project: str,
type_name: str,
attrs: Optional[Mapping[str, Any]] = None
)
property ArtifactType.id
The unique identifier of the artifact type.
property ArtifactType.name
The name of the artifact type.
method ArtifactType.collection
collection(name)
Get a specific artifact collection by name.
Args:
name
(str): The name of the artifact collection to retrieve.
method ArtifactType.collections
collections(per_page=50)
Get all artifact collections associated with this artifact type.
Args:
per_page
(int): The number of artifact collections to fetch per page. Default is 50.
method ArtifactType.load
load()
Load the artifact type metadata.
class ArtifactCollections
An iterable collection of artifact collections associated with a project and artifact 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 collections.type_name
: The name of the artifact type for which to fetch collections.per_page
: The number of artifact collections to fetch per page. Default is 50.
method ArtifactCollections.__init__
__init__(
client: wandb_gql.client.Client,
entity: str,
project: str,
type_name: str,
per_page: int = 50
)
property ArtifactCollections.cursor
Returns the cursor position for pagination of file results.
property ArtifactCollections.length
Returns the number of artifact collections.
property ArtifactCollections.more
Returns True
if there are more artifact collections to fetch.
Returns False
if there are no more files to fetch.
method ArtifactCollections.convert_objects
convert_objects()
Converts GraphQL edges to ArtifactCollection objects.
method ArtifactCollections.update_variables
update_variables()
Updates the variables dictionary with the cursor.
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.
method ArtifactCollection.__init__
__init__(
client: wandb_gql.client.Client,
entity: str,
project: str,
name: str,
type: str,
organization: Optional[str] = None,
attrs: Optional[Mapping[str, Any]] = None
)
property ArtifactCollection.aliases
The aliases associated with the artifact collection.
property ArtifactCollection.created_at
The creation timestamp of the artifact collection.
property ArtifactCollection.description
A description of the artifact collection.
property ArtifactCollection.id
The unique identifier of the artifact collection.
property ArtifactCollection.name
The name of the artifact collection.
property ArtifactCollection.tags
The tags associated with the artifact collection.
property ArtifactCollection.type
Returns the type of the artifact collection.
method ArtifactCollection.artifacts
artifacts(per_page=50)
Get all artifact versions associated with this artifact collection.
method ArtifactCollection.change_type
change_type(new_type: str) → None
Deprecated, change type directly with save
instead.
method ArtifactCollection.delete
delete()
Delete the entire artifact collection.
method ArtifactCollection.is_sequence
is_sequence() → bool
Return whether the artifact collection is a sequence.
method ArtifactCollection.load
load()
Load the artifact collection metadata.
method ArtifactCollection.save
save() → None
Persist any changes made to the artifact collection.
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.
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.
method Artifacts.__init__
__init__(
client: wandb_gql.client.Client,
entity: str,
project: str,
collection_name: str,
type: str,
filters: Optional[Mapping[str, Any]] = None,
order: Optional[str] = None,
per_page: int = 50,
tags: Optional[str, List[str]] = None
)
property Artifacts.cursor
Returns the cursor position for pagination of file results.
property Artifacts.length
Returns the number of artifact versions.
property Artifacts.more
Returns True
if there are more artifact versions to fetch.
method Artifacts.convert_objects
convert_objects()
Converts GraphQL edges to Artifact objects.
class RunArtifacts
An iterable collection of artifacts associated with a run.
Args:
client
: The client instance to use for querying W&B.run
: The run object to query for artifacts.mode
: The mode of artifacts to fetch, either “logged” (output artifacts) or “used” (input artifacts). Default is “logged”.per_page
: The number of artifacts to fetch per page. Default is 50.
method RunArtifacts.__init__
__init__(
client: wandb_gql.client.Client,
run: 'Run',
mode='logged',
per_page: int = 50
)
property RunArtifacts.cursor
Returns the cursor position for pagination of file results.
property RunArtifacts.length
Returns the number of artifacts associated with the run.
property RunArtifacts.more
Returns True
if there are more artifacts to fetch.
method RunArtifacts.convert_objects
convert_objects()
Converts GraphQL edges to Artifact objects.
class ArtifactFiles
An iterable collection of files associated with an artifact version.
Args:
client
: The client instance to use for querying W&B.artifact
: The artifact object to query for files.names
: Optional sequence of file names to filter the results by. IfNone
, all files will be returned.per_page
: The number of files to fetch per page. Default is 50.
method ArtifactFiles.__init__
__init__(
client: wandb_gql.client.Client,
artifact: 'wandb.Artifact',
names: Optional[Sequence[str]] = None,
per_page: int = 50
)
property ArtifactFiles.cursor
Returns the cursor position for pagination of file results.
property ArtifactFiles.length
Returns the number of files in the artifact.
property ArtifactFiles.more
Returns True
if there are more files to fetch. Returns
property ArtifactFiles.path
Returns the path of the artifact.
The path is a list containingthe entity, project name, and artifact name.
method ArtifactFiles.convert_objects
convert_objects()
Converts GraphQL edges to File objects.
method ArtifactFiles.update_variables
update_variables()
Updates the variables dictionary with the cursor and limit.
3 - files
module wandb.apis.public
W&B Public API for File Management.
This module provides classes for interacting with files stored in W&B. Classes include:
Files: A paginated collection of files associated with a run
- Iterate through files with automatic pagination
- Filter files by name
- Access file metadata and properties
- Download multiple files
File: A single file stored in W&B
- Access file metadata (size, mimetype, URLs)
- Download files to local storage
- Delete files from W&B
- Work with S3 URIs for direct access
Example:
from wandb.apis.public import Api
# Initialize API
api = Api()
# Get files from a specific run
run = api.run("entity/project/run_id")
files = run.files()
# Work with files
for file in files:
print(f"File: {file.name}")
print(f"Size: {file.size} bytes")
print(f"Type: {file.mimetype}")
# Download file
if file.size < 1000000: # Less than 1MB
file.download(root="./downloads")
# Get S3 URI for large files
if file.size >= 1000000:
print(f"S3 URI: {file.path_uri}")
Note:
This module is part of the W&B Public API and provides methods to access, download, and manage files stored in W&B. Files are typically associated with specific runs and can include model weights, datasets, visualizations, and other artifacts.
class Files
An iterable 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.
Args:
client
: The run object that contains the filesrun
: The run object that contains the filesnames
(list, optional): A list of file names to filter the filesper_page
(int, optional): The number of files to fetch per pageupload
(bool, optional): IfTrue
, fetch the upload URL for each file
Example:
from wandb.apis.public.files import Files
from wandb.apis.public.api import Api
# Initialize the API client
api = Api()
# Example run object
run = api.run("entity/project/run-id")
# Create a Files object to iterate over files in the run
files = Files(api.client, run)
# Iterate over files
for file in files:
print(file.name)
print(file.url)
print(file.size)
# Download the file
file.download(root="download_directory", replace=True)
method Files.__init__
__init__(client, run, names=None, per_page=50, upload=False)
property Files.cursor
Returns the cursor position for pagination of file results.
property Files.length
The number of files saved to the specified run.
property Files.more
Returns True
if there are more files to fetch. Returns False
if there are no more files to fetch.
method Files.convert_objects
convert_objects()
Converts GraphQL edges to File objects.
method Files.update_variables
update_variables()
Updates the GraphQL query variables for pagination.
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 files stored in S3
Args:
client
: The run object that contains the fileattrs
(dict): A dictionary of attributes that define the filerun
: The run object that contains the file
Example:
from wandb.apis.public.files import File
from wandb.apis.public.api import Api
# Initialize the API client
api = Api()
# Example attributes dictionary
file_attrs = {
"id": "file-id",
"name": "example_file.txt",
"url": "https://example.com/file",
"direct_url": "https://example.com/direct_file",
"sizeBytes": 1024,
"mimetype": "text/plain",
"updated_at": "2025-03-25T21:43:51Z",
"md5": "d41d8cd98f00b204e9800998ecf8427e",
}
# Example run object
run = api.run("entity/project/run-id")
# Create a File object
file = File(api.client, file_attrs, run)
# Access some of the attributes
print("File ID:", file.id)
print("File Name:", file.name)
print("File URL:", file.url)
print("File MIME Type:", file.mimetype)
print("File Updated At:", file.updated_at)
# Access File properties
print("File Size:", file.size)
print("File Path URI:", file.path_uri)
# Download the file
file.download(root="download_directory", replace=True)
# Delete the file
file.delete()
method File.__init__
__init__(client, attrs, run=None)
property File.path_uri
Returns the URI path to the file in the storage bucket.
property File.size
Returns the size of the file in bytes.
method File.delete
delete()
Deletes the file from the W&B server.
method File.download
download(
root: str = '.',
replace: bool = False,
exist_ok: bool = False,
api: Optional[wandb.apis.public.api.Api] = None
) → TextIOWrapper
Downloads a file previously saved by a run from the wandb server.
Args:
root
: Local directory to save the file. Defaults to “.”.replace
: IfTrue
, download will overwrite a local file if it exists. Defaults toFalse
.exist_ok
: IfTrue
, will not raise ValueError if file already exists and will not re-download unless replace=True. Defaults toFalse
.api
: If specified, theApi
instance used to download the file.
Raises:
ValueError
if file already exists, replace=False
and exist_ok=False
.
4 - history
module wandb.apis.public
W&B Public API for Run History.
This module provides classes for efficiently scanning and sampling run history data. Classes include:
HistoryScan: Iterator for scanning complete run history
- Paginated access to all metrics
- Configure step ranges and page sizes
- Raw access to all logged data
SampledHistoryScan: Iterator for sampling run history data
- Efficient access to downsampled metrics
- Filter by specific keys
- Control sample size and step ranges
Note:
This module is part of the W&B Public API and provides methods to access run history data. It handles pagination automatically and offers both complete and sampled access to metrics logged during training runs.
class HistoryScan
Iterator for scanning complete run history.
Args:
client
: (wandb.apis.internal.Api
) The client instance to userun
: (wandb.sdk.internal.Run
) The run object to scan history formin_step
: (int) The minimum step to start scanning frommax_step
: (int) The maximum step to scan up topage_size
: (int) Number of samples per page (default is 1000)
method HistoryScan.__init__
__init__(client, run, min_step, max_step, page_size=1000)
class SampledHistoryScan
Iterator for sampling run history data.
Args:
client
: (wandb.apis.internal.Api
) The client instance to userun
: (wandb.sdk.internal.Run
) The run object to sample history fromkeys
: (list) List of keys to sample from the historymin_step
: (int) The minimum step to start sampling frommax_step
: (int) The maximum step to sample up topage_size
: (int) Number of samples per page (default is 1000)
method SampledHistoryScan.__init__
__init__(client, run, keys, min_step, max_step, page_size=1000)
5 - jobs
module wandb.apis.public
W&B Public API for Job Management and Queuing.
This module provides classes for managing W&B jobs, queued runs, and run queues. Classes include:
Job: Manage W&B job definitions and execution
- Load and configure jobs from artifacts
- Set entrypoints and runtime configurations
- Execute jobs with different resource types
- Handle notebook and container-based jobs
QueuedRun: Track and manage individual queued runs
- Monitor run state and execution
- Wait for run completion
- Access run results and artifacts
- Delete queued runs
RunQueue: Manage job queues and execution resources
- Create and configure run queues
- Set resource types and configurations
- Monitor queue items and status
- Control queue access and priorities
class Job
method Job.__init__
__init__(api: 'Api', name, path: Optional[str] = None) → None
property Job.name
The name of the job.
method Job.call
call(
config,
project=None,
entity=None,
queue=None,
resource='local-container',
resource_args=None,
template_variables=None,
project_queue=None,
priority=None
)
Call the job with the given configuration.
Args:
config
(dict): The configuration to pass to the job. This should be a dictionary containing key-value pairs that match the input types defined in the job.project
(str, optional): The project to log the run to. Defaults to the job’s project.entity
(str, optional): The entity to log the run under. Defaults to the job’s entity.queue
(str, optional): The name of the queue to enqueue the job to. Defaults to None.resource
(str, optional): The resource type to use for execution. Defaults to “local-container”.resource_args
(dict, optional): Additional arguments for the resource type. Defaults to None.template_variables
(dict, optional): Template variables to use for the job. Defaults to None.project_queue
(str, optional): The project that manages the queue. Defaults to None.priority
(int, optional): The priority of the queued run. Defaults to None.
method Job.set_entrypoint
set_entrypoint(entrypoint: List[str])
Set the entrypoint for the job.
class QueuedRun
A single queued run associated with an entity and project.
Args:
entity
: The entity associated with the queued run.project
(str): The project where runs executed by the queue are logged to.queue_name
(str): The name of the queue.run_queue_item_id
(int): The id of the run queue item.project_queue
(str): The project that manages the queue.priority
(str): The priority of the queued run.
Call run = queued_run.wait_until_running()
or run = queued_run.wait_until_finished()
to access the run.
method QueuedRun.__init__
__init__(
client,
entity,
project,
queue_name,
run_queue_item_id,
project_queue='model-registry',
priority=None
)
property QueuedRun.entity
The entity associated with the queued run.
property QueuedRun.id
The id of the queued run.
property QueuedRun.project
The project associated with the queued run.
property QueuedRun.queue_name
The name of the queue.
property QueuedRun.state
The state of the queued run.
method QueuedRun.delete
delete(delete_artifacts=False)
Delete the given queued run from the wandb backend.
method QueuedRun.wait_until_finished
wait_until_finished()
Wait for the queued run to complete and return the finished run.
method QueuedRun.wait_until_running
wait_until_running()
Wait until the queued run is running and return the run.
class RunQueue
Class that represents a run queue in W&B.
Args:
client
: W&B API client instance.name
: Name of the run queueentity
: The entity (user or team) that owns this queueprioritization_mode
: Queue priority mode Can be “DISABLED” or “V0”. Defaults toNone
._access
: Access level for the queue Can be “project” or “user”. Defaults toNone
._default_resource_config_id
: ID of default resource config_default_resource_config
: Default resource configuration
method RunQueue.__init__
__init__(
client: 'RetryingClient',
name: str,
entity: str,
prioritization_mode: Optional[Literal['DISABLED', 'V0']] = None,
_access: Optional[Literal['project', 'user']] = None,
_default_resource_config_id: Optional[int] = None,
_default_resource_config: Optional[dict] = None
) → None
property RunQueue.access
The access level of the queue.
property RunQueue.default_resource_config
The default configuration for resources.
property RunQueue.entity
The entity that owns the queue.
property RunQueue.external_links
External resource links for the queue.
property RunQueue.id
The id of the queue.
property RunQueue.items
Up to the first 100 queued runs. Modifying this list will not modify the queue or any enqueued items!
property RunQueue.name
The name of the queue.
property RunQueue.prioritization_mode
The prioritization mode of the queue.
Can be set to “DISABLED” or “V0”.
property RunQueue.template_variables
Variables for resource templates.
property RunQueue.type
The resource type for execution.
classmethod RunQueue.create
create(
name: str,
resource: 'RunQueueResourceType',
entity: Optional[str] = None,
prioritization_mode: Optional[ForwardRef('RunQueuePrioritizationMode')] = None,
config: Optional[dict] = None,
template_variables: Optional[dict] = None
) → RunQueue
Create a RunQueue.
Args:
name
: The name of the run queue to create.resource
: The resource type for execution.entity
: The entity (user or team) that will own the queue. Defaults to the default entity of the API client.prioritization_mode
: The prioritization mode for the queue. Can be “DISABLED” or “V0”. Defaults to None.config
: Optional dictionary for the default resource configuration. Defaults to None.template_variables
: Optional dictionary for template variables used in the resource configuration.
method RunQueue.delete
delete()
Delete the run queue from the wandb backend.
6 - projects
module wandb.apis.public
W&B Public API for Projects.
This module provides classes for interacting with W&B projects and their associated data. Classes include:
Projects: A paginated collection of projects associated with an entity
- Iterate through all projects
- Access project metadata
- Query project information
Project: A single project that serves as a namespace for runs
- Access project properties
- Work with artifacts and their types
- Manage sweeps
- Generate HTML representations for Jupyter
Example:
from wandb.apis.public import Api
# Initialize API
api = Api()
# Get all projects for an entity
projects = api.projects("entity")
# Access project data
for project in projects:
print(f"Project: {project.name}")
print(f"URL: {project.url}")
# Get artifact types
for artifact_type in project.artifacts_types():
print(f"Artifact Type: {artifact_type.name}")
# Get sweeps
for sweep in project.sweeps():
print(f"Sweep ID: {sweep.id}")
print(f"State: {sweep.state}")
Note:
This module is part of the W&B Public API and provides methods to access and manage projects. For creating new projects, use wandb.init() with a new project name.
class Projects
An iterable collection of Project
objects.
An iterable interface to access projects created and saved by the entity.
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).
Example:
from wandb.apis.public.api import Api
# Initialize the API client
api = Api()
# Find projects that belong to this entity
projects = api.projects(entity="entity")
# Iterate over files
for project in projects:
print(f"Project: {project.name}")
print(f"- URL: {project.url}")
print(f"- Created at: {project.created_at}")
print(f"- Is benchmark: {project.is_benchmark}")
method Projects.__init__
__init__(client, entity, per_page=50)
property Projects.cursor
Returns the cursor position for pagination of project results.
property Projects.length
Returns the total number of projects.
Note: This property is not available for projects.
property Projects.more
Returns True
if there are more projects to fetch. Returns False
if there are no more projects to fetch.
method Projects.convert_objects
convert_objects()
Converts GraphQL edges to File objects.
class Project
A project is a namespace for runs.
Args:
client
: W&B API client instance.name
(str): The name of the project.entity
(str): The entity name that owns the project.
method Project.__init__
__init__(client, entity, project, attrs)
property Project.path
Returns the path of the project. The path is a list containing the entity and project name.
property Project.url
Returns the URL of the project.
method Project.artifacts_types
artifacts_types(per_page=50)
Returns all artifact types associated with this project.
method Project.sweeps
sweeps()
Fetches all sweeps associated with the project.
method Project.to_html
to_html(height=420, hidden=False)
Generate HTML containing an iframe displaying this project.
7 - query_generator
module wandb.apis.public
method QueryGenerator.filter_to_mongo
filter_to_mongo(filter)
Returns dictionary with filter format converted to MongoDB filter.
classmethod QueryGenerator.format_order_key
format_order_key(key: str)
Format a key for sorting.
method QueryGenerator.key_to_server_path
key_to_server_path(key)
Convert a key dictionary to the corresponding server path string.
method QueryGenerator.keys_to_order
keys_to_order(keys)
Convert a list of key dictionaries to an order string.
method QueryGenerator.mongo_to_filter
mongo_to_filter(filter)
Returns dictionary with MongoDB filter converted to filter format.
method QueryGenerator.order_to_keys
order_to_keys(order)
Convert an order string to a list of key dictionaries.
method QueryGenerator.server_path_to_key
server_path_to_key(path)
Convert a server path string to the corresponding key dictionary.
8 - reports
module wandb.apis.public
Public API: reports.
class Reports
Reports is an iterable collection of BetaReport
objects.
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. IfNone
, 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).
method Reports.__init__
__init__(client, project, name=None, entity=None, per_page=50)
property Reports.cursor
Returns the cursor position for pagination of file results.
property Reports.length
The number of reports in the project.
property Reports.more
Returns True
if there are more files to fetch. Returns False
if there are no more files to fetch.
method Reports.convert_objects
convert_objects()
Converts GraphQL edges to File objects.
method Reports.update_variables
update_variables()
Updates the GraphQL query variables for pagination.
class BetaReport
BetaReport is a class associated with reports created in wandb.
WARNING: this API will likely change in a future release
Attributes:
name
(string): report namedescription
(string): report descriptionuser
(User): the user that created the reportspec
(dict): the spec off the reportupdated_at
(string): timestamp of last update
method BetaReport.__init__
__init__(client, attrs, entity=None, project=None)
property BetaReport.sections
Get the panel sections (groups) from the report.
property BetaReport.updated_at
Timestamp of last update
property BetaReport.url
URL of the report.
Contains the entity, project, display name, and id.
method BetaReport.runs
runs(section, per_page=50, only_selected=True)
Get runs associated with a section of the report.
method BetaReport.to_html
to_html(height=1024, hidden=False)
Generate HTML containing an iframe displaying this report.
9 - runs
module wandb.apis.public
W&B Public API for ML Runs.
This module provides classes for interacting with W&B runs and their associated data. Classes include:
Runs: A paginated collection of runs associated with a project
- Filter and query runs
- Access run histories and metrics
- Export data in various formats (pandas, polars)
Run: A single machine learning training run
- Access run metadata, configs, and metrics
- Upload and download files
- Work with artifacts
- Query run history
- Update run information
Example:
from wandb.apis.public import Api
# Initialize API
api = Api()
# Get runs matching filters
runs = api.runs(
path="entity/project", filters={"state": "finished", "config.batch_size": 32}
)
# Access run data
for run in runs:
print(f"Run: {run.name}")
print(f"Config: {run.config}")
print(f"Metrics: {run.summary}")
# Get history with pandas
history_df = run.history(keys=["loss", "accuracy"], pandas=True)
# Work with artifacts
for artifact in run.logged_artifacts():
print(f"Artifact: {artifact.name}")
Note:
This module is part of the W&B Public API and provides read/write access to run data. For logging new runs, use the wandb.init() function from the main wandb package.
class Runs
An iterable collection of runs associated with a project and optional filter.
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
: (Optional[str]) The order of the runs, can be “asc” or “desc” Defaults to “desc”.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.
Examples:
from wandb.apis.public.runs import Runs
from wandb.apis.public import Api
# Initialize the API client
api = Api()
# Get all runs from a project that satisfy the filters
filters = {"state": "finished", "config.optimizer": "adam"}
runs = Runs(
client=api.client,
entity="entity",
project="project_name",
filters=filters,
)
# Iterate over runs and print details
for run in runs:
print(f"Run name: {run.name}")
print(f"Run ID: {run.id}")
print(f"Run URL: {run.url}")
print(f"Run state: {run.state}")
print(f"Run config: {run.config}")
print(f"Run summary: {run.summary}")
print(f"Run history (samples=5): {run.history(samples=5)}")
print("----------")
# Get histories for all runs with specific metrics
histories_df = runs.histories(
samples=100, # Number of samples per run
keys=["loss", "accuracy"], # Metrics to fetch
x_axis="_step", # X-axis metric
format="pandas", # Return as pandas DataFrame
)
method Runs.__init__
__init__(
client: 'RetryingClient',
entity: str,
project: str,
filters: Optional[Dict[str, Any]] = None,
order: Optional[str] = None,
per_page: int = 50,
include_sweeps: bool = True
)
property Runs.cursor
Returns the cursor position for pagination of runs results.
property Runs.length
Returns the total number of runs.
property Runs.more
Returns True
if there are more runs to fetch. Returns False
if there are no more runs to fetch.
method Runs.convert_objects
convert_objects()
Converts GraphQL edges to Runs objects.
method Runs.histories
histories(
samples: int = 500,
keys: Optional[List[str]] = None,
x_axis: str = '_step',
format: Literal['default', 'pandas', 'polars'] = 'default',
stream: Literal['default', 'system'] = 'default'
)
Return sampled history metrics for all runs that fit the filters conditions.
Args:
samples
: The number of samples to return per runkeys
: Only return metrics for specific keysx_axis
: Use this metric as the xAxis defaults to _stepformat
: Format to return data in, options are “default”, “pandas”, “polars”stream
: “default” for metrics, “system” for machine metrics
Returns:
pandas.DataFrame
: Ifformat="pandas"
, returns apandas.DataFrame
of history metrics.polars.DataFrame
: Ifformat="polars"
, returns apolars.DataFrame
of history metrics.list of dicts
: Ifformat="default"
, returns a list of dicts containing history metrics with arun_id
key.
class Run
A single run associated with an entity and project.
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 runurl
(str): the url of this runid
(str): unique identifier for the run (defaults to eight characters)name
(str): the name of the runstate
(str): one of: running, finished, crashed, killed, preempting, preemptedconfig
(dict): a dict of hyperparameters associated with the runcreated_at
(str): ISO timestamp when the run was startedsystem_metrics
(dict): the latest system metrics recorded for the runsummary
(dict): A mutable dict-like property that holds the current summary. Calling update will persist any changes.project
(str): the project associated with the runentity
(str): the name of the entity associated with the runproject_internal_id
(int): the internal id of the projectuser
(str): the name of the user who created the runpath
(str): Unique identifier [entity]/[project]/[run_id]notes
(str): Notes about the runread_only
(boolean): Whether the run is editablehistory_keys
(str): Keys of the history metrics that have been loggedwith
wandb.log({key: value})
metadata
(str): Metadata about the run from wandb-metadata.json
method Run.__init__
__init__(
client: 'RetryingClient',
entity: str,
project: str,
run_id: str,
attrs: Optional[Mapping] = None,
include_sweeps: bool = True
)
Initialize a Run object.
Run is always initialized by calling api.runs() where api is an instance of wandb.Api.
property Run.entity
The entity associated with the run.
property Run.id
The unique identifier for the run.
property Run.json_config
property Run.lastHistoryStep
Returns the last step logged in the run’s history.
property Run.metadata
Metadata about the run from wandb-metadata.json.
Metadata includes the run’s description, tags, start time, memory usage and more.
property Run.name
The name of the run.
property Run.path
The path of the run. The path is a list containing the entity, project, and run_id.
property Run.state
The state of the run. Can be one of: Finished, Failed, Crashed, or Running.
property Run.storage_id
The unique storage identifier for the run.
property Run.summary
A mutable dict-like property that holds summary values associated with the run.
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
.
property Run.username
This API is deprecated. Use entity
instead.
classmethod Run.create
create(api, run_id=None, project=None, entity=None)
Create a run for the given project.
method Run.delete
delete(delete_artifacts=False)
Delete the given run from the wandb backend.
Args:
delete_artifacts
(bool, optional): Whether to delete the artifacts associated with the run.
method Run.file
file(name)
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
files(names=None, per_page=50)
Return a file path for each file named.
Args:
names
(list): names of the requested files, if empty returns all filesper_page
(int): number of results per page.
Returns:
A Files
object, which is an iterator over File
objects.
method Run.history
history(samples=500, keys=None, x_axis='_step', pandas=True, stream='default')
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 returnpandas
: (bool, optional) Return a pandas dataframekeys
: (list, optional) Only return metrics for specific keysx_axis
: (str, optional) Use this metric as the xAxis defaults to _stepstream
: (str, optional) “default” for metrics, “system” for machine metrics
Returns:
pandas.DataFrame
: If pandas=True returns apandas.DataFrame
of history metrics.list of dicts
: If pandas=False returns a list of dicts of history metrics.
method Run.load
load(force=False)
Fetch and update run data from GraphQL database.
Ensures run data is up to date.
Args:
force
(bool): Whether to force a refresh of the run data.
method Run.log_artifact
log_artifact(
artifact: 'wandb.Artifact',
aliases: Optional[Collection[str]] = None,
tags: Optional[Collection[str]] = None
)
Declare an artifact as output of a run.
Args:
artifact
(Artifact
): An artifact returned fromwandb.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
logged_artifacts(per_page: int = 100) → RunArtifacts
Fetches all artifacts logged by this run.
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:
per_page
: Number of artifacts to fetch per API request.
Returns: An iterable collection of all Artifact objects logged as outputs during this run.
Example:
import wandb
import tempfile
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()
api = wandb.Api()
finished_run = api.run(f"{run.entity}/{run.project}/{run.id}")
for logged_artifact in finished_run.logged_artifacts():
print(logged_artifact.name)
method Run.save
save()
Persist changes to the run object to the W&B backend.
method Run.scan_history
scan_history(keys=None, page_size=1000, min_step=None, max_step=None)
Returns an iterable collection of all history records for a run.
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.
Returns: An iterable collection over history records (dict).
Example: Export all the loss values for an example run
run = api.run("entity/project-name/run-id")
history = run.scan_history(keys=["Loss"])
losses = [row["Loss"] for row in history]
method Run.to_html
to_html(height=420, hidden=False)
Generate HTML containing an iframe displaying this run.
method Run.update
update()
Persist changes to the run object to the wandb backend.
method Run.upload_file
upload_file(path, root='.')
Uploads a local file to W&B, associating it with this run.
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 (".").
Returns:
A File
object representing the uploaded file.
method Run.use_artifact
use_artifact(artifact, use_as=None)
Declare an artifact as an input to a run.
Args:
artifact
(Artifact
): An artifact returned fromwandb.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.
Returns:
A Artifact
object.
method Run.used_artifacts
used_artifacts(per_page: int = 100) → RunArtifacts
Fetches artifacts explicitly used by this 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.
Args:
per_page
: Number of artifacts to fetch per API request.
Returns: An iterable collection of Artifact objects explicitly used as inputs in this run.
Example:
import wandb
run = wandb.init(project="artifact-example")
run.use_artifact("test_artifact:latest")
run.finish()
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
method Run.wait_until_finished
wait_until_finished()
Check the state of the run until it is finished.
10 - sweeps
module wandb.apis.public
W&B Public API for Hyperparameter Sweeps.
This module provides classes for interacting with W&B hyperparameter optimization sweeps. Classes include:
Sweep: Represents a hyperparameter optimization sweep, providing access to:
- Sweep configuration and state
- Associated runs and their metrics
- Best performing runs
- URLs for visualization
Example:
from wandb.apis.public import Api
# Initialize API
api = Api()
# Get a specific sweep
sweep = api.sweep("entity/project/sweep_id")
# Access sweep properties
print(f"Sweep: {sweep.name}")
print(f"State: {sweep.state}")
print(f"Best Loss: {sweep.best_loss}")
# Get best performing run
best_run = sweep.best_run()
print(f"Best Run: {best_run.name}")
print(f"Metrics: {best_run.summary}")
Note:
This module is part of the W&B Public API and provides read-only access to sweep data. For creating and controlling sweeps, use the wandb.sweep() and wandb.agent() functions from the main wandb package.
class Sweep
The set of runs associated with the sweep.
Attributes:
runs
(Runs
): List of runsid
(str): Sweep IDproject
(str): The name of the project the sweep belongs toconfig
(dict): Dictionary containing the sweep configurationstate
(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__
__init__(client, entity, project, sweep_id, attrs=None)
property Sweep.config
The sweep configuration used for the sweep.
property Sweep.entity
The entity associated with the sweep.
property Sweep.expected_run_count
Return the number of expected runs in the sweep or None for infinite runs.
property Sweep.name
The name of the sweep.
If the sweep has a name, it will be returned. Otherwise, the sweep ID will be returned.
property Sweep.order
Return the order key for the sweep.
property Sweep.path
Returns the path of the project.
The path is a list containing the entity, project name, and sweep ID.
property Sweep.url
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
.
property Sweep.username
Note: Deprecated. Use entity instead.
method Sweep.best_run
best_run(order=None)
Return the best run sorted by the metric defined in config or the order passed in.
classmethod Sweep.get
get(
client,
entity=None,
project=None,
sid=None,
order=None,
query=None,
**kwargs
)
Execute a query against the cloud backend.
method Sweep.load
load(force: bool = False)
Fetch and update sweep data logged to the run from GraphQL database.
method Sweep.to_html
to_html(height=420, hidden=False)
Generate HTML containing an iframe displaying this sweep.
11 - teams
module wandb.apis.public
W&B Public API for managing teams and team members.
This module provides classes for managing W&B teams and their members. Classes include:
Team: Manage W&B teams and their settings
- Create new teams
- Invite team members
- Create service accounts
- Manage team permissions and settings
Member: Represent and manage team members
- Access member information
- Delete members
- Manage member permissions
Note:
This module is part of the W&B Public API and provides methods to manage teams and their members. Team management operations require appropriate permissions.
class Member
A member of a team.
Args:
client
(wandb.apis.internal.Api
): The client instance to useteam
(str): The name of the team this member belongs toattrs
(dict): The member attributes
method Member.__init__
__init__(client, team, attrs)
method Member.delete
delete()
Remove a member from a team.
Returns: Boolean indicating success
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.
Args:
client
(wandb.apis.public.Api
): The api instance to usename
(str): The name of the teamattrs
(dict): Optional dictionary of team attributes
Note:
Team management requires appropriate permissions.
method Team.__init__
__init__(client, name, attrs=None)
classmethod Team.create
create(api, team, admin_username=None)
Create a new team.
Args:
api
: (Api
) The api instance to useteam
: (str) The name of the teamadmin_username
: (str) optional username of the admin user of the team, defaults to the current user.
Returns:
A Team
object
method Team.create_service_account
create_service_account(description)
Create a service account for the team.
Args:
description
: (str) A description for this service account
Returns:
The service account Member
object, or None on failure
method Team.invite
invite(username_or_email, admin=False)
Invite a user to a team.
Args:
username_or_email
: (str) The username or email address of the user you want to inviteadmin
: (bool) Whether to make this user a team admin, defaults to False
Returns: True on success, False if user was already invited or didn’t exist
method Team.load
load(force=False)
Return members that belong to a team.
12 - users
module wandb.apis.public
W&B Public API for User Management.
This module provides classes for managing W&B users and their API keys. Classes include:
User: Manage W&B user accounts and authentication
- Create new users
- Generate and manage API keys
- Access team memberships
- Handle user properties and permissions
Note:
This module is part of the W&B Public API and provides methods to manage users and their authentication. Some operations require admin privileges.
class User
A class representing a W&B user with authentication and management capabilities.
This class provides methods to manage W&B users, including creating users, managing API keys, and accessing team memberships. It inherits from Attrs to handle user attributes.
Args:
client
: (wandb.apis.internal.Api
) The client instance to useattrs
: (dict) The user attributes
Note:
Some operations require admin privileges
method User.__init__
__init__(client, attrs)
property User.api_keys
List of API key names associated with the user.
Returns:
list[str]
: Names of API keys associated with the user. Empty list if user has no API keys or if API key data hasn’t been loaded.
property User.teams
List of team names that the user is a member of.
Returns:
list
(list): Names of teams the user belongs to. Empty list if user has no team memberships or if teams data hasn’t been loaded.
property User.user_api
An instance of the api using credentials from the user.
classmethod User.create
create(api, email, admin=False)
Create a new user.
Args:
api
(Api
): The api instance to useemail
(str): The name of the teamadmin
(bool): Whether this user should be a global instance admin
Returns:
A User
object
method User.delete_api_key
delete_api_key(api_key)
Delete a user’s api key.
Args:
api_key
(str): The name of the API key to delete. This should be one of the names returned by theapi_keys
property.
Returns: Boolean indicating success
Raises: ValueError if the api_key couldn’t be found
method User.generate_api_key
generate_api_key(description=None)
Generate a new api key.
Args:
description
(str, optional): A description for the new API key. This can be used to identify the purpose of the API key.
Returns: The new api key, or None on failure