project_name stringlengths 6 104 | file_name stringlengths 4 89 | full_name stringlengths 1 102 | func_name stringlengths 1 85 | docstring stringlengths 13 836 | docstring_tokens listlengths 4 122 | code stringlengths 23 39.7k | code_tokens stringlengths 29 44.6k | url int64 3 986k |
|---|---|---|---|---|---|---|---|---|
wandb/wandb | test_kubernetes.py | test_add_label | test_add_label | Test that we add labels to pod specs correctly. | [
"Test",
"that",
"we",
"add",
"labels",
"to",
"pod",
"specs",
"correctly."
] | def test_add_label(manifest):
add_label_to_pods(manifest, 'test_label', 'test_value')
assert manifest['spec']['template']['metadata']['labels'] == {'app': 'wandb', 'test_label': 'test_value'} | ['def', 'test_add_label(manifest):', 'add_label_to_pods(manifest,', "'test_label',", "'test_value')", 'assert', "manifest['spec']['template']['metadata']['labels']", '==', "{'app':", "'wandb',", "'test_label':", "'test_value'}"] | 941,283 |
wandb/wandb | test_kubernetes.py | mock_core_api | mock_core_api | Patches the kubernetes core api with a mock and returns it. | [
"Patches",
"the",
"kubernetes",
"core",
"api",
"with",
"a",
"mock",
"and",
"returns",
"it."
] | def mock_core_api(monkeypatch):
core_api = MockCoreV1Api()
monkeypatch.setattr('wandb.sdk.launch.runner.kubernetes_runner.client.CoreV1Api', lambda *args, **kwargs: core_api)
return core_api | ['def', 'mock_core_api(monkeypatch):', 'core_api', '=', 'MockCoreV1Api()', "monkeypatch.setattr('wandb.sdk.launch.runner.kubernetes_runner.client.CoreV1Api',", 'lambda', '*args,', '**kwargs:', 'core_api)', 'return', 'core_api'] | 941,287 |
wandb/wandb | test_kubernetes.py | mock_custom_api | mock_custom_api | Patches the kubernetes custom api with a mock and returns it. | [
"Patches",
"the",
"kubernetes",
"custom",
"api",
"with",
"a",
"mock",
"and",
"returns",
"it."
] | def mock_custom_api(monkeypatch):
custom_api = MockCustomObjectsApi()
monkeypatch.setattr('wandb.sdk.launch.runner.kubernetes_runner.client.CustomObjectsApi', lambda *args, **kwargs: custom_api)
return custom_api | ['def', 'mock_custom_api(monkeypatch):', 'custom_api', '=', 'MockCustomObjectsApi()', "monkeypatch.setattr('wandb.sdk.launch.runner.kubernetes_runner.client.CustomObjectsApi',", 'lambda', '*args,', '**kwargs:', 'custom_api)', 'return', 'custom_api'] | 941,288 |
wandb/wandb | test_kubernetes.py | mock_create_from_yaml | mock_create_from_yaml | Patches the kubernetes create_from_yaml with a mock and returns it. | [
"Patches",
"the",
"kubernetes",
"create_from_yaml",
"with",
"a",
"mock",
"and",
"returns",
"it."
] | def mock_create_from_yaml(monkeypatch):
function_mock = MagicMock()
function_mock.return_value = [[MockDict({'metadata': MockDict({'name': 'test-job'})})]]
monkeypatch.setattr('kubernetes.utils.create_from_yaml', function_mock)
return function_mock | ['def', 'mock_create_from_yaml(monkeypatch):', 'function_mock', '=', 'MagicMock()', 'function_mock.return_value', '=', "[[MockDict({'metadata':", "MockDict({'name':", "'test-job'})})]]", "monkeypatch.setattr('kubernetes.utils.create_from_yaml',", 'function_mock)', 'return', 'function_mock'] | 941,290 |
wandb/wandb | test_kubernetes.py | job_factory | job_factory | Factory for creating job events. | [
"Factory",
"for",
"creating",
"job",
"events."
] | def job_factory(statuses):
return MockDict({'object': MockDict({'status': MockDict({f'{status}': 1 for status in statuses})})}) | ['def', 'job_factory(statuses):', 'return', "MockDict({'object':", "MockDict({'status':", "MockDict({f'{status}':", '1', 'for', 'status', 'in', 'statuses})})})'] | 941,294 |
wandb/wandb | test_kubernetes.py | test_monitor_preempted | test_monitor_preempted | Test if the monitor thread detects a preempted job. | [
"Test",
"if",
"the",
"monitor",
"thread",
"detects",
"a",
"preempted",
"job."
] | def test_monitor_preempted(mock_event_streams, mock_batch_api, mock_core_api, reason):
monitor = KubernetesRunMonitor(job_field_selector='foo=bar', pod_label_selector='foo=bar', batch_api=mock_batch_api, core_api=mock_core_api, namespace='wandb')
monitor.start()
(_, pod_event_stream) = mock_event_streams
... | ['def', 'test_monitor_preempted(mock_event_streams,', 'mock_batch_api,', 'mock_core_api,', 'reason):', 'monitor', '=', "KubernetesRunMonitor(job_field_selector='foo=bar',", "pod_label_selector='foo=bar',", 'batch_api=mock_batch_api,', 'core_api=mock_core_api,', "namespace='wandb')", 'monitor.start()', '(_,', 'pod_event... | 941,296 |
wandb/wandb | test_kubernetes.py | test_monitor_succeeded | test_monitor_succeeded | Test if the monitor thread detects a succeeded job. | [
"Test",
"if",
"the",
"monitor",
"thread",
"detects",
"a",
"succeeded",
"job."
] | def test_monitor_succeeded(mock_event_streams, mock_batch_api, mock_core_api):
monitor = KubernetesRunMonitor(job_field_selector='foo=bar', pod_label_selector='foo=bar', batch_api=mock_batch_api, core_api=mock_core_api, namespace='wandb')
monitor.start()
(job_event_stream, pod_event_stream) = mock_event_str... | ['def', 'test_monitor_succeeded(mock_event_streams,', 'mock_batch_api,', 'mock_core_api):', 'monitor', '=', "KubernetesRunMonitor(job_field_selector='foo=bar',", "pod_label_selector='foo=bar',", 'batch_api=mock_batch_api,', 'core_api=mock_core_api,', "namespace='wandb')", 'monitor.start()', '(job_event_stream,', 'pod_e... | 941,297 |
wandb/wandb | test_kubernetes.py | test_monitor_failed | test_monitor_failed | Test if the monitor thread detects a failed job. | [
"Test",
"if",
"the",
"monitor",
"thread",
"detects",
"a",
"failed",
"job."
] | def test_monitor_failed(mock_event_streams, mock_batch_api, mock_core_api):
monitor = KubernetesRunMonitor(job_field_selector='foo=bar', pod_label_selector='foo=bar', batch_api=mock_batch_api, core_api=mock_core_api, namespace='wandb')
monitor.start()
(job_event_stream, pod_event_stream) = mock_event_stream... | ['def', 'test_monitor_failed(mock_event_streams,', 'mock_batch_api,', 'mock_core_api):', 'monitor', '=', "KubernetesRunMonitor(job_field_selector='foo=bar',", "pod_label_selector='foo=bar',", 'batch_api=mock_batch_api,', 'core_api=mock_core_api,', "namespace='wandb')", 'monitor.start()', '(job_event_stream,', 'pod_even... | 941,298 |
wandb/wandb | test_kubernetes.py | test_monitor_running | test_monitor_running | Test if the monitor thread detects a running job. | [
"Test",
"if",
"the",
"monitor",
"thread",
"detects",
"a",
"running",
"job."
] | def test_monitor_running(mock_event_streams, mock_batch_api, mock_core_api):
monitor = KubernetesRunMonitor(job_field_selector='foo=bar', pod_label_selector='foo=bar', batch_api=mock_batch_api, core_api=mock_core_api, namespace='wandb')
monitor.start()
(job_event_stream, pod_event_stream) = mock_event_strea... | ['def', 'test_monitor_running(mock_event_streams,', 'mock_batch_api,', 'mock_core_api):', 'monitor', '=', "KubernetesRunMonitor(job_field_selector='foo=bar',", "pod_label_selector='foo=bar',", 'batch_api=mock_batch_api,', 'core_api=mock_core_api,', "namespace='wandb')", 'monitor.start()', '(job_event_stream,', 'pod_eve... | 941,299 |
wandb/wandb | test_kubernetes.py | test_monitor_thread_restart | test_monitor_thread_restart | Test that getting the status triggers the watch threads to be started. | [
"Test",
"that",
"getting",
"the",
"status",
"triggers",
"the",
"watch",
"threads",
"to",
"be",
"started."
] | def test_monitor_thread_restart(mock_event_streams, mock_batch_api, mock_core_api):
monitor = KubernetesRunMonitor(job_field_selector='foo=bar', pod_label_selector='foo=bar', batch_api=mock_batch_api, core_api=mock_core_api, namespace='wandb')
assert not monitor._watch_job_thread.is_alive()
assert not monit... | ['def', 'test_monitor_thread_restart(mock_event_streams,', 'mock_batch_api,', 'mock_core_api):', 'monitor', '=', "KubernetesRunMonitor(job_field_selector='foo=bar',", "pod_label_selector='foo=bar',", 'batch_api=mock_batch_api,', 'core_api=mock_core_api,', "namespace='wandb')", 'assert', 'not', 'monitor._watch_job_threa... | 941,300 |
wandb/wandb | test_kubernetes.py | condition_factory | condition_factory | Factory for creating conditions. | [
"Factory",
"for",
"creating",
"conditions."
] | def condition_factory(condition_type, condition_status, condition_reason, transition_time):
return MockDict({'type': condition_type, 'status': condition_status, 'reason': condition_reason, 'lastTransitionTime': transition_time}) | ['def', 'condition_factory(condition_type,', 'condition_status,', 'condition_reason,', 'transition_time):', 'return', "MockDict({'type':", 'condition_type,', "'status':", 'condition_status,', "'reason':", 'condition_reason,', "'lastTransitionTime':", 'transition_time})'] | 941,301 |
wandb/wandb | test_vertex.py | test_vertex_submitted_run | test_vertex_submitted_run | Test that the submitted run works as expected. | [
"Test",
"that",
"the",
"submitted",
"run",
"works",
"as",
"expected."
] | def test_vertex_submitted_run():
job = MockCustomJob(['PENDING', 'RUNNING', 'SUCCEEDED', 'FAILED'])
run = VertexSubmittedRun(job)
link = run.get_page_link()
assert link == 'https://console.cloud.google.com/vertex-ai/locations/test-location/training/test-name?project=test-project'
assert run.get_stat... | ['def', 'test_vertex_submitted_run():', 'job', '=', "MockCustomJob(['PENDING',", "'RUNNING',", "'SUCCEEDED',", "'FAILED'])", 'run', '=', 'VertexSubmittedRun(job)', 'link', '=', 'run.get_page_link()', 'assert', 'link', '==', "'https://console.cloud.google.com/vertex-ai/locations/test-location/training/test-name?project=... | 941,305 |
wandb/wandb | test_vertex.py | launch_project_factory | launch_project_factory | Construct a dummy LaunchProject with the given resource args. | [
"Construct",
"a",
"dummy",
"LaunchProject",
"with",
"the",
"given",
"resource",
"args."
] | def launch_project_factory(resource_args: dict, api: Api):
return LaunchProject(api=api, docker_config={'docker_image': 'test-image'}, resource_args=resource_args, uri='', job='', launch_spec={}, target_entity='', target_project='', name='', git_info={}, overrides={}, resource='vertex', run_id='') | ['def', 'launch_project_factory(resource_args:', 'dict,', 'api:', 'Api):', 'return', 'LaunchProject(api=api,', "docker_config={'docker_image':", "'test-image'},", 'resource_args=resource_args,', "uri='',", "job='',", 'launch_spec={},', "target_entity='',", "target_project='',", "name='',", 'git_info={},', 'overrides={}... | 941,306 |
wandb/wandb | test_vertex.py | vertex_runner | vertex_runner | Vertex runner initialized with no backend config. | [
"Vertex",
"runner",
"initialized",
"with",
"no",
"backend",
"config."
] | def vertex_runner(test_settings):
registry = MagicMock()
environment = MagicMock()
api = Api(default_settings=test_settings(), load_settings=False)
runner = VertexRunner(api, {'SYNCHRONOUS': False}, registry, environment)
return runner | ['def', 'vertex_runner(test_settings):', 'registry', '=', 'MagicMock()', 'environment', '=', 'MagicMock()', 'api', '=', 'Api(default_settings=test_settings(),', 'load_settings=False)', 'runner', '=', 'VertexRunner(api,', "{'SYNCHRONOUS':", 'False},', 'registry,', 'environment)', 'return', 'runner'] | 941,307 |
wandb/wandb | test_vertex.py | test_vertex_missing_worker_spec | test_vertex_missing_worker_spec | Test that a launch error is raised when we are missing a worker spec. | [
"Test",
"that",
"a",
"launch",
"error",
"is",
"raised",
"when",
"we",
"are",
"missing",
"a",
"worker",
"spec."
] | def test_vertex_missing_worker_spec(vertex_runner):
resource_args = {'vertex': {'worker_pool_specs': []}}
launch_project = launch_project_factory(resource_args, vertex_runner._api)
with pytest.raises(LaunchError) as e:
vertex_runner.run(launch_project, 'test-image')
assert 'requires at least one... | ['def', 'test_vertex_missing_worker_spec(vertex_runner):', 'resource_args', '=', "{'vertex':", "{'worker_pool_specs':", '[]}}', 'launch_project', '=', 'launch_project_factory(resource_args,', 'vertex_runner._api)', 'with', 'pytest.raises(LaunchError)', 'as', 'e:', 'vertex_runner.run(launch_project,', "'test-image')", '... | 941,309 |
wandb/wandb | test_vertex.py | test_vertex_missing_staging_bucket | test_vertex_missing_staging_bucket | Test that a launch error is raised when we are missing a staging bucket. | [
"Test",
"that",
"a",
"launch",
"error",
"is",
"raised",
"when",
"we",
"are",
"missing",
"a",
"staging",
"bucket."
] | def test_vertex_missing_staging_bucket(vertex_runner):
resource_args = {'vertex': {'spec': {'worker_pool_specs': [{'machine_spec': {'machine_type': 'n1-standard-4'}, 'replica_count': 1, 'container_spec': {'image_uri': 'test-image'}}]}}}
launch_project = launch_project_factory(resource_args, vertex_runner._api)
... | ['def', 'test_vertex_missing_staging_bucket(vertex_runner):', 'resource_args', '=', "{'vertex':", "{'spec':", "{'worker_pool_specs':", "[{'machine_spec':", "{'machine_type':", "'n1-standard-4'},", "'replica_count':", '1,', "'container_spec':", "{'image_uri':", "'test-image'}}]}}}", 'launch_project', '=', 'launch_projec... | 941,310 |
wandb/wandb | test_filesystem.py | test_mkdir_exists_ok_pathtypes | test_mkdir_exists_ok_pathtypes | Test that mkdir_exists_ok works with all path-like objects. | [
"Test",
"that",
"mkdir_exists_ok",
"works",
"with",
"all",
"path-like",
"objects."
] | def test_mkdir_exists_ok_pathtypes(tmp_path, pathtype):
new_dir = tmp_path / 'new'
mkdir_exists_ok(pathtype(new_dir))
assert new_dir.is_dir() | ['def', 'test_mkdir_exists_ok_pathtypes(tmp_path,', 'pathtype):', 'new_dir', '=', 'tmp_path', '/', "'new'", 'mkdir_exists_ok(pathtype(new_dir))', 'assert', 'new_dir.is_dir()'] | 941,314 |
wandb/wandb | test_mailbox.py | TestWithMockedTime.test_keepalive | test_keepalive | Make sure mock keepalive is called. | [
"Make",
"sure",
"mock",
"keepalive",
"is",
"called."
] | def test_keepalive(self):
with self._patch_mailbox() as (event_mock, _):
mailbox = Mailbox()
mailbox.enable_keepalive()
record = pb.Record()
iface = Mock(spec_set=['publish', '_publish', 'transport_failed', '_transport_mark_failed', '_transport_mark_success', '_transport_keepalive_fa... | ['def', 'test_keepalive(self):', 'with', 'self._patch_mailbox()', 'as', '(event_mock,', '_):', 'mailbox', '=', 'Mailbox()', 'mailbox.enable_keepalive()', 'record', '=', 'pb.Record()', 'iface', '=', "Mock(spec_set=['publish',", "'_publish',", "'transport_failed',", "'_transport_mark_failed',", "'_transport_mark_success'... | 941,315 |
wandb/wandb | test_trainium.py | neuron_monitor_mock | neuron_monitor_mock | Generate a stream of mock raw data for NeuronCoreStats to sample. | [
"Generate",
"a",
"stream",
"of",
"mock",
"raw",
"data",
"for",
"NeuronCoreStats",
"to",
"sample."
] | def neuron_monitor_mock(self: NeuronCoreStats):
self.write_neuron_monitor_config()
for data in itertools.cycle(MOCK_DATA):
if self.shutdown_event.is_set():
break
raw_data = json.dumps(data).encode()
self.raw_samples.append(raw_data)
self.shutdown_event.wait(1) | ['def', 'neuron_monitor_mock(self:', 'NeuronCoreStats):', 'self.write_neuron_monitor_config()', 'for', 'data', 'in', 'itertools.cycle(MOCK_DATA):', 'if', 'self.shutdown_event.is_set():', 'break', 'raw_data', '=', 'json.dumps(data).encode()', 'self.raw_samples.append(raw_data)', 'self.shutdown_event.wait(1)'] | 941,317 |
wandb/wandb | dummy_data.py | matplotlib_multiple_axes_figures | matplotlib_multiple_axes_figures | Helper generator which create a figure containing up to `total_plot_count` axes and optionally adds `data` to each axes in a permutation-style loop. | [
"Helper",
"generator",
"which",
"create",
"a",
"figure",
"containing",
"up",
"to",
"`total_plot_count`",
"axes",
"and",
"optionally",
"adds",
"`data`",
"to",
"each",
"axes",
"in",
"a",
"permutation-style",
"loop."
] | def matplotlib_multiple_axes_figures(total_plot_count=3, data=[1, 2, 3]):
for num_plots in range(1, total_plot_count + 1):
for permutation in range(2 ** num_plots):
has_data = [permutation & 1 << i > 0 for i in range(num_plots)]
(fig, ax) = plt.subplots(num_plots)
if num_... | ['def', 'matplotlib_multiple_axes_figures(total_plot_count=3,', 'data=[1,', '2,', '3]):', 'for', 'num_plots', 'in', 'range(1,', 'total_plot_count', '+', '1):', 'for', 'permutation', 'in', 'range(2', '**', 'num_plots):', 'has_data', '=', '[permutation', '&', '1', '<<', 'i', '>', '0', 'for', 'i', 'in', 'range(num_plots)]... | 941,321 |
wandb/wandb | parse_metrics.py | get_step_metric_dict | get_step_metric_dict | Get mapping from metric to preferred x-axis. | [
"Get",
"mapping",
"from",
"metric",
"to",
"preferred",
"x-axis."
] | def get_step_metric_dict(ml):
nl = [m['1'] for m in ml]
md = {m['1']: nl[m['5'] - 1] for m in ml if m.get('5')}
return md | ['def', 'get_step_metric_dict(ml):', 'nl', '=', "[m['1']", 'for', 'm', 'in', 'ml]', 'md', '=', "{m['1']:", "nl[m['5']", '-', '1]', 'for', 'm', 'in', 'ml', 'if', "m.get('5')}", 'return', 'md'] | 941,327 |
wandb/wandb | conftest.py | pytest_generate_tests | pytest_generate_tests | Fixture to make options available in tests. | [
"Fixture",
"to",
"make",
"options",
"available",
"in",
"tests."
] | def pytest_generate_tests(metafunc):
api_key = metafunc.config.option.api_key
if 'api_key' in metafunc.fixturenames:
metafunc.parametrize('api_key', [api_key])
base_url = metafunc.config.option.base_url
if 'base_url' in metafunc.fixturenames:
metafunc.parametrize('base_url', [base_url])
... | ['def', 'pytest_generate_tests(metafunc):', 'api_key', '=', 'metafunc.config.option.api_key', 'if', "'api_key'", 'in', 'metafunc.fixturenames:', "metafunc.parametrize('api_key',", '[api_key])', 'base_url', '=', 'metafunc.config.option.base_url', 'if', "'base_url'", 'in', 'metafunc.fixturenames:', "metafunc.parametrize(... | 941,333 |
wandb/wandb | conftest.py | pytest_configure | pytest_configure | Fixture to confirm the session has the correct credentials. | [
"Fixture",
"to",
"confirm",
"the",
"session",
"has",
"the",
"correct",
"credentials."
] | def pytest_configure(config):
client_config = botocore.config.Config(region_name='us-east-2')
sts = boto3.client('sts', config=client_config)
try:
sts.get_caller_identity()
except botocore.exceptions.ClientError:
raise Exception('Not logged into LaunchSandbox AWS account')
default_im... | ['def', 'pytest_configure(config):', 'client_config', '=', "botocore.config.Config(region_name='us-east-2')", 'sts', '=', "boto3.client('sts',", 'config=client_config)', 'try:', 'sts.get_caller_identity()', 'except', 'botocore.exceptions.ClientError:', 'raise', "Exception('Not", 'logged', 'into', 'LaunchSandbox', 'AWS'... | 941,334 |
wandb/wandb | utils.py | wait_for_k8s_job_completion | wait_for_k8s_job_completion | W&B's wait_until_finished() doesn't work for image based jobs, so poll the k8s output for job completion. | [
"W&B's",
"wait_until_finished()",
"doesn't",
"work",
"for",
"image",
"based",
"jobs,",
"so",
"poll",
"the",
"k8s",
"output",
"for",
"job",
"completion."
] | def wait_for_k8s_job_completion(namespace: str, entity: str, project: str, num_jobs: int) -> str:
config.load_kube_config()
v1 = client.CoreV1Api()
w = watch.Watch()
status = None
completed_jobs = 0
for event in w.stream(v1.list_namespaced_pod, namespace=namespace, timeout_seconds=300):
... | ['def', 'wait_for_k8s_job_completion(namespace:', 'str,', 'entity:', 'str,', 'project:', 'str,', 'num_jobs:', 'int)', '->', 'str:', 'config.load_kube_config()', 'v1', '=', 'client.CoreV1Api()', 'w', '=', 'watch.Watch()', 'status', '=', 'None', 'completed_jobs', '=', '0', 'for', 'event', 'in', 'w.stream(v1.list_namespac... | 941,336 |
wandb/wandb | utils.py | init_agent_in_launch_cluster | init_agent_in_launch_cluster | Deploy the agent in provided cluster namespace. | [
"Deploy",
"the",
"agent",
"in",
"provided",
"cluster",
"namespace."
] | def init_agent_in_launch_cluster(namespace: str, api_key: str, agent_image: Optional[str]):
create_config_files(api_key, agent_image)
run_cmd('kubectl apply -f tests/release_tests/test_launch/launch-config.yml')
run_cmd('kubectl apply -f tests/release_tests/test_launch/launch-agent.yml')
setup_cleanup_o... | ['def', 'init_agent_in_launch_cluster(namespace:', 'str,', 'api_key:', 'str,', 'agent_image:', 'Optional[str]):', 'create_config_files(api_key,', 'agent_image)', "run_cmd('kubectl", 'apply', '-f', "tests/release_tests/test_launch/launch-config.yml')", "run_cmd('kubectl", 'apply', '-f', "tests/release_tests/test_launch/... | 941,339 |
wandb/wandb | check-protobuf-version-compatibility.py | get_available_protobuf_versions | get_available_protobuf_versions | Get a list of available protobuf versions. | [
"Get",
"a",
"list",
"of",
"available",
"protobuf",
"versions."
] | def get_available_protobuf_versions() -> List[str]:
try:
output = subprocess.check_output(['pip', 'index', 'versions', 'protobuf']).decode('utf-8')
versions = list({o for o in output.split() if o[0].isnumeric()})
versions = [v if not v.endswith(',') else v[:-1] for v in versions]
ret... | ['def', 'get_available_protobuf_versions()', '->', 'List[str]:', 'try:', 'output', '=', "subprocess.check_output(['pip',", "'index',", "'versions',", "'protobuf']).decode('utf-8')", 'versions', '=', 'list({o', 'for', 'o', 'in', 'output.split()', 'if', 'o[0].isnumeric()})', 'versions', '=', '[v', 'if', 'not', "v.endswit... | 941,345 |
wandb/wandb | pr-title-bot.py | chat_completion_with_backoff | chat_completion_with_backoff | Call OpenAI's chat completion API with exponential backoff. | [
"Call",
"OpenAI's",
"chat",
"completion",
"API",
"with",
"exponential",
"backoff."
] | def chat_completion_with_backoff(**kwargs):
return openai.ChatCompletion.create(**kwargs) | ['def', 'chat_completion_with_backoff(**kwargs):', 'return', 'openai.ChatCompletion.create(**kwargs)'] | 941,351 |
wandb/wandb | pr-title-bot.py | get_pr_info | get_pr_info | Get the title and diff of a PR. | [
"Get",
"the",
"title",
"and",
"diff",
"of",
"a",
"PR."
] | def get_pr_info(pr_number: int, repo_name: str='wandb/wandb', get_diff: bool=True) -> Tuple[str, Optional[str]]:
g = Github(GITHUB_TOKEN)
repo = g.get_repo(repo_name)
pr = repo.get_pull(pr_number)
if not get_diff:
return (pr.title, None)
files = pr.get_files()
diff = '\n'.join([file.patc... | ['def', 'get_pr_info(pr_number:', 'int,', 'repo_name:', "str='wandb/wandb',", 'get_diff:', 'bool=True)', '->', 'Tuple[str,', 'Optional[str]]:', 'g', '=', 'Github(GITHUB_TOKEN)', 'repo', '=', 'g.get_repo(repo_name)', 'pr', '=', 'repo.get_pull(pr_number)', 'if', 'not', 'get_diff:', 'return', '(pr.title,', 'None)', 'files... | 941,352 |
wandb/wandb | pr-title-bot.py | generate_pr_title | generate_pr_title | Generate a PR title for a given PR number using the given model. | [
"Generate",
"a",
"PR",
"title",
"for",
"a",
"given",
"PR",
"number",
"using",
"the",
"given",
"model."
] | def generate_pr_title(pr_number: int, model: Model='gpt-4', repo_name: str='wandb/wandb') -> str:
messages = [{'role': 'system', 'content': f'Your task is to write a title for a GitHub pull request that will follow the conventional commit format and capture the essence of the change: <type>(<scope>): <description>.... | ['def', 'generate_pr_title(pr_number:', 'int,', 'model:', "Model='gpt-4',", 'repo_name:', "str='wandb/wandb')", '->', 'str:', 'messages', '=', "[{'role':", "'system',", "'content':", "f'Your", 'task', 'is', 'to', 'write', 'a', 'title', 'for', 'a', 'GitHub', 'pull', 'request', 'that', 'will', 'follow', 'the', 'conventio... | 941,354 |
wandb/wandb | data_types.py | Table.add_row | add_row | Deprecated: use add_data instead. | [
"Deprecated:",
"use",
"add_data",
"instead."
] | def add_row(self, *row):
logging.warning('add_row is deprecated, use add_data')
self.add_data(*row) | ['def', 'add_row(self,', '*row):', "logging.warning('add_row", 'is', 'deprecated,', 'use', "add_data')", 'self.add_data(*row)'] | 941,356 |
wandb/wandb | data_types.py | Table.add_computed_columns | add_computed_columns | Add one or more computed columns based on existing data. | [
"Add",
"one",
"or",
"more",
"computed",
"columns",
"based",
"on",
"existing",
"data."
] | def add_computed_columns(self, fn):
new_columns = {}
for (ndx, row) in self.iterrows():
row_dict = {self.columns[i]: row[i] for i in range(len(self.columns))}
new_row_dict = fn(ndx, row_dict)
assert isinstance(new_row_dict, dict)
for key in new_row_dict:
new_columns[k... | ['def', 'add_computed_columns(self,', 'fn):', 'new_columns', '=', '{}', 'for', '(ndx,', 'row)', 'in', 'self.iterrows():', 'row_dict', '=', '{self.columns[i]:', 'row[i]', 'for', 'i', 'in', 'range(len(self.columns))}', 'new_row_dict', '=', 'fn(ndx,', 'row_dict)', 'assert', 'isinstance(new_row_dict,', 'dict)', 'for', 'key... | 941,364 |
wandb/wandb | data_types.py | Node.id | id | Must be unique in the graph. | [
"Must",
"be",
"unique",
"in",
"the",
"graph."
] | def id(self):
return self._attributes.get('id') | ['def', 'id(self):', 'return', "self._attributes.get('id')"] | 941,366 |
wandb/wandb | data_types.py | Node.class_name | class_name | Usually the type of layer or sublayer. | [
"Usually",
"the",
"type",
"of",
"layer",
"or",
"sublayer."
] | def class_name(self):
return self._attributes.get('class_name') | ['def', 'class_name(self):', 'return', "self._attributes.get('class_name')"] | 941,368 |
wandb/wandb | jupyter.py | attempt_colab_login | attempt_colab_login | This renders an iframe to wandb in the hopes it posts back an api key. | [
"This",
"renders",
"an",
"iframe",
"to",
"wandb",
"in",
"the",
"hopes",
"it",
"posts",
"back",
"an",
"api",
"key."
] | def attempt_colab_login(app_url):
from google.colab import output
from google.colab._message import MessageError
from IPython import display
display.display(display.Javascript('\n window._wandbApiKey = new Promise((resolve, reject) => {\n function loadScript(url) {\n return ... | ['def', 'attempt_colab_login(app_url):', 'from', 'google.colab', 'import', 'output', 'from', 'google.colab._message', 'import', 'MessageError', 'from', 'IPython', 'import', 'display', "display.display(display.Javascript('\\n", 'window._wandbApiKey', '=', 'new', 'Promise((resolve,', 'reject)', '=>', '{\\n', 'function', ... | 941,374 |
wandb/wandb | jupyter.py | Notebook.probe_ipynb | probe_ipynb | Return notebook as dict or None. | [
"Return",
"notebook",
"as",
"dict",
"or",
"None."
] | def probe_ipynb(self):
relpath = self.settings._jupyter_path
if relpath:
if os.path.exists(relpath):
with open(relpath) as json_file:
data = json.load(json_file)
return data
colab_ipynb = attempt_colab_load_ipynb()
if colab_ipynb:
return colab_... | ['def', 'probe_ipynb(self):', 'relpath', '=', 'self.settings._jupyter_path', 'if', 'relpath:', 'if', 'os.path.exists(relpath):', 'with', 'open(relpath)', 'as', 'json_file:', 'data', '=', 'json.load(json_file)', 'return', 'data', 'colab_ipynb', '=', 'attempt_colab_load_ipynb()', 'if', 'colab_ipynb:', 'return', 'colab_ip... | 941,376 |
wandb/wandb | util.py | app_url | app_url | Return the frontend app url without a trailing slash. | [
"Return",
"the",
"frontend",
"app",
"url",
"without",
"a",
"trailing",
"slash."
] | def app_url(api_url: str) -> str:
app_url = wandb.env.get_app_url()
if app_url is not None:
return str(app_url.strip('/'))
if '://api.wandb.test' in api_url:
return api_url.replace('://api.', '://app.').strip('/')
elif '://api.wandb.' in api_url:
return api_url.replace('://api.',... | ['def', 'app_url(api_url:', 'str)', '->', 'str:', 'app_url', '=', 'wandb.env.get_app_url()', 'if', 'app_url', 'is', 'not', 'None:', 'return', "str(app_url.strip('/'))", 'if', "'://api.wandb.test'", 'in', 'api_url:', 'return', "api_url.replace('://api.',", "'://app.').strip('/')", 'elif', "'://api.wandb.'", 'in', 'api_u... | 941,381 |
wandb/wandb | util.py | json_friendly_val | json_friendly_val | Make any value (including dict, slice, sequence, dataclass) JSON friendly. | [
"Make",
"any",
"value",
"(including",
"dict,",
"slice,",
"sequence,",
"dataclass)",
"JSON",
"friendly."
] | def json_friendly_val(val: Any) -> Any:
converted: Union[dict, list]
if isinstance(val, dict):
converted = {}
for (key, value) in val.items():
converted[key] = json_friendly_val(value)
return converted
if isinstance(val, slice):
converted = dict(slice_start=val.st... | ['def', 'json_friendly_val(val:', 'Any)', '->', 'Any:', 'converted:', 'Union[dict,', 'list]', 'if', 'isinstance(val,', 'dict):', 'converted', '=', '{}', 'for', '(key,', 'value)', 'in', 'val.items():', 'converted[key]', '=', 'json_friendly_val(value)', 'return', 'converted', 'if', 'isinstance(val,', 'slice):', 'converte... | 941,387 |
wandb/wandb | util.py | launch_browser | launch_browser | Decide if we should launch a browser. | [
"Decide",
"if",
"we",
"should",
"launch",
"a",
"browser."
] | def launch_browser(attempt_launch_browser: bool=True) -> bool:
_display_variables = ['DISPLAY', 'WAYLAND_DISPLAY', 'MIR_SOCKET']
_webbrowser_names_blocklist = ['www-browser', 'lynx', 'links', 'elinks', 'w3m']
import webbrowser
launch_browser = attempt_launch_browser
if launch_browser:
if 'li... | ['def', 'launch_browser(attempt_launch_browser:', 'bool=True)', '->', 'bool:', '_display_variables', '=', "['DISPLAY',", "'WAYLAND_DISPLAY',", "'MIR_SOCKET']", '_webbrowser_names_blocklist', '=', "['www-browser',", "'lynx',", "'links',", "'elinks',", "'w3m']", 'import', 'webbrowser', 'launch_browser', '=', 'attempt_lau... | 941,388 |
wandb/wandb | util.py | parse_tfjob_config | parse_tfjob_config | Attempt to parse TFJob config, returning False if it can't find it. | [
"Attempt",
"to",
"parse",
"TFJob",
"config,",
"returning",
"False",
"if",
"it",
"can't",
"find",
"it."
] | def parse_tfjob_config() -> Any:
if os.getenv('TF_CONFIG'):
try:
return json.loads(os.environ['TF_CONFIG'])
except ValueError:
return False
else:
return False | ['def', 'parse_tfjob_config()', '->', 'Any:', 'if', "os.getenv('TF_CONFIG'):", 'try:', 'return', "json.loads(os.environ['TF_CONFIG'])", 'except', 'ValueError:', 'return', 'False', 'else:', 'return', 'False'] | 941,389 |
wandb/wandb | util.py | json_dumps_safer_history | json_dumps_safer_history | Convert obj to json, with some extra encodable types, including histograms. | [
"Convert",
"obj",
"to",
"json,",
"with",
"some",
"extra",
"encodable",
"types,",
"including",
"histograms."
] | def json_dumps_safer_history(obj: Any, **kwargs: Any) -> str:
return dumps(obj, cls=WandBHistoryJSONEncoder, **kwargs) | ['def', 'json_dumps_safer_history(obj:', 'Any,', '**kwargs:', 'Any)', '->', 'str:', 'return', 'dumps(obj,', 'cls=WandBHistoryJSONEncoder,', '**kwargs)'] | 941,393 |
wandb/wandb | util.py | prompt_choices | prompt_choices | Allow a user to choose from a list of options. | [
"Allow",
"a",
"user",
"to",
"choose",
"from",
"a",
"list",
"of",
"options."
] | def prompt_choices(choices: Sequence[str], input_timeout: Union[int, float, None]=None, jupyter: bool=False) -> str:
for (i, choice) in enumerate(choices):
wandb.termlog(f'({i + 1}) {choice}')
idx = -1
while idx < 0 or idx > len(choices) - 1:
choice = _prompt_choice(input_timeout=input_timeo... | ['def', 'prompt_choices(choices:', 'Sequence[str],', 'input_timeout:', 'Union[int,', 'float,', 'None]=None,', 'jupyter:', 'bool=False)', '->', 'str:', 'for', '(i,', 'choice)', 'in', 'enumerate(choices):', "wandb.termlog(f'({i", '+', '1})', "{choice}')", 'idx', '=', '-1', 'while', 'idx', '<', '0', 'or', 'idx', '>', 'len... | 941,407 |
wandb/wandb | util.py | host_from_path | host_from_path | Return the host of the path. | [
"Return",
"the",
"host",
"of",
"the",
"path."
] | def host_from_path(path: Optional[str]) -> str:
url = urllib.parse.urlparse(path)
return str(url.netloc) | ['def', 'host_from_path(path:', 'Optional[str])', '->', 'str:', 'url', '=', 'urllib.parse.urlparse(path)', 'return', 'str(url.netloc)'] | 941,409 |
wandb/wandb | util.py | is_unicode_safe | is_unicode_safe | Return True if the stream supports UTF-8. | [
"Return",
"True",
"if",
"the",
"stream",
"supports",
"UTF-8."
] | def is_unicode_safe(stream: TextIO) -> bool:
encoding = getattr(stream, 'encoding', None)
return encoding.lower() in {'utf-8', 'utf_8'} if encoding else False | ['def', 'is_unicode_safe(stream:', 'TextIO)', '->', 'bool:', 'encoding', '=', 'getattr(stream,', "'encoding',", 'None)', 'return', 'encoding.lower()', 'in', "{'utf-8',", "'utf_8'}", 'if', 'encoding', 'else', 'False'] | 941,411 |
wandb/wandb | util.py | fsync_open | fsync_open | Open a path for I/O and guarantee that the file is flushed and synced. | [
"Open",
"a",
"path",
"for",
"I/O",
"and",
"guarantee",
"that",
"the",
"file",
"is",
"flushed",
"and",
"synced."
] | def fsync_open(path: StrPath, mode: str='w', encoding: Optional[str]=None) -> Generator[IO[Any], None, None]:
with open(path, mode, encoding=encoding) as f:
yield f
f.flush()
os.fsync(f.fileno()) | ['def', 'fsync_open(path:', 'StrPath,', 'mode:', "str='w',", 'encoding:', 'Optional[str]=None)', '->', 'Generator[IO[Any],', 'None,', 'None]:', 'with', 'open(path,', 'mode,', 'encoding=encoding)', 'as', 'f:', 'yield', 'f', 'f.flush()', 'os.fsync(f.fileno())'] | 941,412 |
wandb/wandb | util.py | ensure_text | ensure_text | Coerce s to str. | [
"Coerce",
"s",
"to",
"str."
] | def ensure_text(string: Union[str, bytes], encoding: str='utf-8', errors: str='strict') -> str:
if isinstance(string, bytes):
return string.decode(encoding, errors)
elif isinstance(string, str):
return string
else:
raise TypeError(f'not expecting type {type(string)!r}') | ['def', 'ensure_text(string:', 'Union[str,', 'bytes],', 'encoding:', "str='utf-8',", 'errors:', "str='strict')", '->', 'str:', 'if', 'isinstance(string,', 'bytes):', 'return', 'string.decode(encoding,', 'errors)', 'elif', 'isinstance(string,', 'str):', 'return', 'string', 'else:', 'raise', "TypeError(f'not", 'expecting... | 941,413 |
wandb/wandb | util.py | make_docker_image_name_safe | make_docker_image_name_safe | Make a docker image name safe for use in artifacts. | [
"Make",
"a",
"docker",
"image",
"name",
"safe",
"for",
"use",
"in",
"artifacts."
] | def make_docker_image_name_safe(name: str) -> str:
safe_chars = RE_DOCKER_IMAGE_NAME_CHARS.sub('__', name.lower())
deduped = RE_DOCKER_IMAGE_NAME_SEPARATOR_REPEAT.sub('__', safe_chars)
trimmed_start = RE_DOCKER_IMAGE_NAME_SEPARATOR_START.sub('', deduped)
trimmed = RE_DOCKER_IMAGE_NAME_SEPARATOR_END.sub(... | ['def', 'make_docker_image_name_safe(name:', 'str)', '->', 'str:', 'safe_chars', '=', "RE_DOCKER_IMAGE_NAME_CHARS.sub('__',", 'name.lower())', 'deduped', '=', "RE_DOCKER_IMAGE_NAME_SEPARATOR_REPEAT.sub('__',", 'safe_chars)', 'trimmed_start', '=', "RE_DOCKER_IMAGE_NAME_SEPARATOR_START.sub('',", 'deduped)', 'trimmed', '=... | 941,415 |
wandb/wandb | util.py | merge_dicts | merge_dicts | Recursively merge two dictionaries. | [
"Recursively",
"merge",
"two",
"dictionaries."
] | def merge_dicts(source: Dict[str, Any], destination: Dict[str, Any]) -> Dict[str, Any]:
for (key, value) in source.items():
if isinstance(value, dict):
node = destination.setdefault(key, {})
merge_dicts(value, node)
elif isinstance(value, list):
if key in destinat... | ['def', 'merge_dicts(source:', 'Dict[str,', 'Any],', 'destination:', 'Dict[str,', 'Any])', '->', 'Dict[str,', 'Any]:', 'for', '(key,', 'value)', 'in', 'source.items():', 'if', 'isinstance(value,', 'dict):', 'node', '=', 'destination.setdefault(key,', '{})', 'merge_dicts(value,', 'node)', 'elif', 'isinstance(value,', 'l... | 941,416 |
wandb/wandb | sentry.py | Sentry.environment | environment | Return the environment we're running in. | [
"Return",
"the",
"environment",
"we're",
"running",
"in."
] | def environment(self) -> str:
is_git = pathlib.Path(__file__).parent.parent.parent.joinpath('.git').exists()
return 'development' if is_git else 'production' | ['def', 'environment(self)', '->', 'str:', 'is_git', '=', "pathlib.Path(__file__).parent.parent.parent.joinpath('.git').exists()", 'return', "'development'", 'if', 'is_git', 'else', "'production'"] | 941,430 |
wandb/wandb | sentry.py | Sentry.message | message | Send a message to Sentry. | [
"Send",
"a",
"message",
"to",
"Sentry."
] | def message(self, message: str, repeat: bool=True) -> None:
if not repeat and message in self._sent_messages:
return
self._sent_messages.add(message)
self.hub.capture_message(message) | ['def', 'message(self,', 'message:', 'str,', 'repeat:', 'bool=True)', '->', 'None:', 'if', 'not', 'repeat', 'and', 'message', 'in', 'self._sent_messages:', 'return', 'self._sent_messages.add(message)', 'self.hub.capture_message(message)'] | 941,432 |
wandb/wandb | sentry.py | Sentry.exception | exception | Log an exception to Sentry. | [
"Log",
"an",
"exception",
"to",
"Sentry."
] | def exception(self, exc: Union[str, BaseException, Tuple[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]], None], handled: bool=False, status: Optional['SessionStatus']=None) -> None:
error = Exception(exc) if isinstance(exc, str) else exc
if error is not None:
exc_info =... | ['def', 'exception(self,', 'exc:', 'Union[str,', 'BaseException,', 'Tuple[Optional[Type[BaseException]],', 'Optional[BaseException],', 'Optional[TracebackType]],', 'None],', 'handled:', 'bool=False,', 'status:', "Optional['SessionStatus']=None)", '->', 'None:', 'error', '=', 'Exception(exc)', 'if', 'isinstance(exc,', '... | 941,433 |
wandb/wandb | sentry.py | Sentry.start_session | start_session | Start a new session. | [
"Start",
"a",
"new",
"session."
] | def start_session(self) -> None:
assert self.hub is not None
(_, scope) = self.hub._stack[-1]
session = scope._session
if session is None:
self.hub.start_session() | ['def', 'start_session(self)', '->', 'None:', 'assert', 'self.hub', 'is', 'not', 'None', '(_,', 'scope)', '=', 'self.hub._stack[-1]', 'session', '=', 'scope._session', 'if', 'session', 'is', 'None:', 'self.hub.start_session()'] | 941,435 |
wandb/wandb | sentry.py | Sentry.end_session | end_session | End the current session. | [
"End",
"the",
"current",
"session."
] | def end_session(self) -> None:
assert self.hub is not None
(client, scope) = self.hub._stack[-1]
session = scope._session
if session is not None and client is not None:
self.hub.end_session()
client.flush() | ['def', 'end_session(self)', '->', 'None:', 'assert', 'self.hub', 'is', 'not', 'None', '(client,', 'scope)', '=', 'self.hub._stack[-1]', 'session', '=', 'scope._session', 'if', 'session', 'is', 'not', 'None', 'and', 'client', 'is', 'not', 'None:', 'self.hub.end_session()', 'client.flush()'] | 941,436 |
wandb/wandb | public.py | Api.sync_tensorboard | sync_tensorboard | Sync a local directory containing tfevent files to wandb. | [
"Sync",
"a",
"local",
"directory",
"containing",
"tfevent",
"files",
"to",
"wandb."
] | def sync_tensorboard(self, root_dir, run_id=None, project=None, entity=None):
from wandb.sync import SyncManager
run_id = run_id or runid.generate_id()
project = project or self.settings.get('project') or 'uncategorized'
entity = entity or self.default_entity
sm = SyncManager(project=project, entity... | ['def', 'sync_tensorboard(self,', 'root_dir,', 'run_id=None,', 'project=None,', 'entity=None):', 'from', 'wandb.sync', 'import', 'SyncManager', 'run_id', '=', 'run_id', 'or', 'runid.generate_id()', 'project', '=', 'project', 'or', "self.settings.get('project')", 'or', "'uncategorized'", 'entity', '=', 'entity', 'or', '... | 941,444 |
wandb/wandb | public.py | Attrs.display | display | Display this object in jupyter. | [
"Display",
"this",
"object",
"in",
"jupyter."
] | def display(self, height=420, hidden=False) -> bool:
html = self.to_html(height, hidden)
if html is None:
wandb.termwarn('This object does not support `.display()`')
return False
if ipython.in_jupyter():
ipython.display_html(html)
return True
else:
wandb.termwarn(... | ['def', 'display(self,', 'height=420,', 'hidden=False)', '->', 'bool:', 'html', '=', 'self.to_html(height,', 'hidden)', 'if', 'html', 'is', 'None:', "wandb.termwarn('This", 'object', 'does', 'not', 'support', "`.display()`')", 'return', 'False', 'if', 'ipython.in_jupyter():', 'ipython.display_html(html)', 'return', 'Tr... | 941,457 |
wandb/wandb | public.py | Project.to_html | to_html | Generate HTML containing an iframe displaying this project. | [
"Generate",
"HTML",
"containing",
"an",
"iframe",
"displaying",
"this",
"project."
] | def to_html(self, height=420, hidden=False):
url = self.url + '?jupyter=true'
style = f'border:none;width:100%;height:{height}px;'
prefix = ''
if hidden:
style += 'display:none;'
prefix = ipython.toggle_button('project')
return prefix + f'<iframe src={url!r} style={style!r}></iframe>... | ['def', 'to_html(self,', 'height=420,', 'hidden=False):', 'url', '=', 'self.url', '+', "'?jupyter=true'", 'style', '=', "f'border:none;width:100%;height:{height}px;'", 'prefix', '=', "''", 'if', 'hidden:', 'style', '+=', "'display:none;'", 'prefix', '=', "ipython.toggle_button('project')", 'return', 'prefix', '+', "f'<... | 941,466 |
wandb/wandb | public.py | Run.create | create | Create a run for the given project. | [
"Create",
"a",
"run",
"for",
"the",
"given",
"project."
] | def create(cls, api, run_id=None, project=None, entity=None):
run_id = run_id or runid.generate_id()
project = project or api.settings.get('project') or 'uncategorized'
mutation = gql('\n mutation UpsertBucket($project: String, $entity: String, $name: String!) {\n upsertBucket(input: {mode... | ['def', 'create(cls,', 'api,', 'run_id=None,', 'project=None,', 'entity=None):', 'run_id', '=', 'run_id', 'or', 'runid.generate_id()', 'project', '=', 'project', 'or', "api.settings.get('project')", 'or', "'uncategorized'", 'mutation', '=', "gql('\\n", 'mutation', 'UpsertBucket($project:', 'String,', '$entity:', 'Strin... | 941,467 |
wandb/wandb | public.py | Run.update | update | Persist changes to the run object to the wandb backend. | [
"Persist",
"changes",
"to",
"the",
"run",
"object",
"to",
"the",
"wandb",
"backend."
] | def update(self):
mutation = gql('\n mutation UpsertBucket($id: String!, $description: String, $display_name: String, $notes: String, $tags: [String!], $config: JSONString!, $groupName: String) {\n upsertBucket(input: {id: $id, description: $description, displayName: $display_name, notes: $notes, ... | ['def', 'update(self):', 'mutation', '=', "gql('\\n", 'mutation', 'UpsertBucket($id:', 'String!,', '$description:', 'String,', '$display_name:', 'String,', '$notes:', 'String,', '$tags:', '[String!],', '$config:', 'JSONString!,', '$groupName:', 'String)', '{\\n', 'upsertBucket(input:', '{id:', '$id,', 'description:', '... | 941,468 |
wandb/wandb | public.py | Run.to_html | to_html | Generate HTML containing an iframe displaying this run. | [
"Generate",
"HTML",
"containing",
"an",
"iframe",
"displaying",
"this",
"run."
] | def to_html(self, height=420, hidden=False):
url = self.url + '?jupyter=true'
style = f'border:none;width:100%;height:{height}px;'
prefix = ''
if hidden:
style += 'display:none;'
prefix = ipython.toggle_button()
return prefix + f'<iframe src={url!r} style={style!r}></iframe>' | ['def', 'to_html(self,', 'height=420,', 'hidden=False):', 'url', '=', 'self.url', '+', "'?jupyter=true'", 'style', '=', "f'border:none;width:100%;height:{height}px;'", 'prefix', '=', "''", 'if', 'hidden:', 'style', '+=', "'display:none;'", 'prefix', '=', 'ipython.toggle_button()', 'return', 'prefix', '+', "f'<iframe", ... | 941,477 |
wandb/wandb | public.py | QueuedRun.delete | delete | Delete the given queued run from the wandb backend. | [
"Delete",
"the",
"given",
"queued",
"run",
"from",
"the",
"wandb",
"backend."
] | def delete(self, delete_artifacts=False):
query = gql('\n query fetchRunQueuesFromProject($entityName: String!, $projectName: String!, $runQueueName: String!) {\n project(name: $projectName, entityName: $entityName) {\n runQueue(name: $runQueueName) {\n ... | ['def', 'delete(self,', 'delete_artifacts=False):', 'query', '=', "gql('\\n", 'query', 'fetchRunQueuesFromProject($entityName:', 'String!,', '$projectName:', 'String!,', '$runQueueName:', 'String!)', '{\\n', 'project(name:', '$projectName,', 'entityName:', '$entityName)', '{\\n', 'runQueue(name:', '$runQueueName)', '{\... | 941,478 |
wandb/wandb | public.py | RunQueue.delete | delete | Delete the run queue from the wandb backend. | [
"Delete",
"the",
"run",
"queue",
"from",
"the",
"wandb",
"backend."
] | def delete(self):
query = gql('\n mutation DeleteRunQueue($id: ID!) {\n deleteRunQueues(input: {queueIDs: [$id]}) {\n success\n clientMutationId\n }\n }\n ')
variable_values = {'id': self.id}
res = self._cli... | ['def', 'delete(self):', 'query', '=', "gql('\\n", 'mutation', 'DeleteRunQueue($id:', 'ID!)', '{\\n', 'deleteRunQueues(input:', '{queueIDs:', '[$id]})', '{\\n', 'success\\n', 'clientMutationId\\n', '}\\n', '}\\n', "')", 'variable_values', '=', "{'id':", 'self.id}', 'res', '=', 'self._client.execute(query,', 'variable_v... | 941,480 |
wandb/wandb | public.py | Sweep.best_run | best_run | Return the best run sorted by the metric defined in config or the order passed in. | [
"Return",
"the",
"best",
"run",
"sorted",
"by",
"the",
"metric",
"defined",
"in",
"config",
"or",
"the",
"order",
"passed",
"in."
] | def best_run(self, order=None):
if order is None:
order = self.order
else:
order = QueryGenerator.format_order_key(order)
if order is None:
wandb.termwarn("No order specified and couldn't find metric in sweep config, returning most recent run")
else:
wandb.termlog('Sortin... | ['def', 'best_run(self,', 'order=None):', 'if', 'order', 'is', 'None:', 'order', '=', 'self.order', 'else:', 'order', '=', 'QueryGenerator.format_order_key(order)', 'if', 'order', 'is', 'None:', 'wandb.termwarn("No', 'order', 'specified', 'and', "couldn't", 'find', 'metric', 'in', 'sweep', 'config,', 'returning', 'most... | 941,481 |
wandb/wandb | public.py | Sweep.expected_run_count | expected_run_count | Return the number of expected runs in the sweep or None for infinite runs. | [
"Return",
"the",
"number",
"of",
"expected",
"runs",
"in",
"the",
"sweep",
"or",
"None",
"for",
"infinite",
"runs."
] | def expected_run_count(self) -> Optional[int]:
return self._attrs.get('runCountExpected') | ['def', 'expected_run_count(self)', '->', 'Optional[int]:', 'return', "self._attrs.get('runCountExpected')"] | 941,482 |
wandb/wandb | public.py | Sweep.get | get | Execute a query against the cloud backend. | [
"Execute",
"a",
"query",
"against",
"the",
"cloud",
"backend."
] | def get(cls, client, entity=None, project=None, sid=None, order=None, query=None, **kwargs):
if query is None:
query = cls.QUERY
variables = {'entity': entity, 'project': project, 'name': sid}
variables.update(kwargs)
response = None
try:
response = client.execute(query, variable_val... | ['def', 'get(cls,', 'client,', 'entity=None,', 'project=None,', 'sid=None,', 'order=None,', 'query=None,', '**kwargs):', 'if', 'query', 'is', 'None:', 'query', '=', 'cls.QUERY', 'variables', '=', "{'entity':", 'entity,', "'project':", 'project,', "'name':", 'sid}', 'variables.update(kwargs)', 'response', '=', 'None', '... | 941,483 |
wandb/wandb | public.py | Sweep.to_html | to_html | Generate HTML containing an iframe displaying this sweep. | [
"Generate",
"HTML",
"containing",
"an",
"iframe",
"displaying",
"this",
"sweep."
] | def to_html(self, height=420, hidden=False):
url = self.url + '?jupyter=true'
style = f'border:none;width:100%;height:{height}px;'
prefix = ''
if hidden:
style += 'display:none;'
prefix = ipython.toggle_button('sweep')
return prefix + f'<iframe src={url!r} style={style!r}></iframe>' | ['def', 'to_html(self,', 'height=420,', 'hidden=False):', 'url', '=', 'self.url', '+', "'?jupyter=true'", 'style', '=', "f'border:none;width:100%;height:{height}px;'", 'prefix', '=', "''", 'if', 'hidden:', 'style', '+=', "'display:none;'", 'prefix', '=', "ipython.toggle_button('sweep')", 'return', 'prefix', '+', "f'<if... | 941,484 |
wandb/wandb | public.py | BetaReport.to_html | to_html | Generate HTML containing an iframe displaying this report. | [
"Generate",
"HTML",
"containing",
"an",
"iframe",
"displaying",
"this",
"report."
] | def to_html(self, height=1024, hidden=False):
url = self.url + '?jupyter=true'
style = f'border:none;width:100%;height:{height}px;'
prefix = ''
if hidden:
style += 'display:none;'
prefix = ipython.toggle_button('report')
return prefix + f'<iframe src={url!r} style={style!r}></iframe>... | ['def', 'to_html(self,', 'height=1024,', 'hidden=False):', 'url', '=', 'self.url', '+', "'?jupyter=true'", 'style', '=', "f'border:none;width:100%;height:{height}px;'", 'prefix', '=', "''", 'if', 'hidden:', 'style', '+=', "'display:none;'", 'prefix', '=', "ipython.toggle_button('report')", 'return', 'prefix', '+', "f'<... | 941,486 |
wandb/wandb | public.py | ArtifactCollection.is_sequence | is_sequence | Return True if this is a sequence. | [
"Return",
"True",
"if",
"this",
"is",
"a",
"sequence."
] | def is_sequence(self) -> bool:
query = gql('\n query FindSequence($entity: String!, $project: String!, $collection: String!, $type: String!) {\n project(name: $project, entityName: $entity) {\n artifactType(name: $type) {\n __typename\n ... | ['def', 'is_sequence(self)', '->', 'bool:', 'query', '=', "gql('\\n", 'query', 'FindSequence($entity:', 'String!,', '$project:', 'String!,', '$collection:', 'String!,', '$type:', 'String!)', '{\\n', 'project(name:', '$project,', 'entityName:', '$entity)', '{\\n', 'artifactType(name:', '$type)', '{\\n', '__typename\\n',... | 941,487 |
wandb/wandb | public.py | ArtifactCollection.delete | delete | Delete the entire artifact collection. | [
"Delete",
"the",
"entire",
"artifact",
"collection."
] | def delete(self):
if self.is_sequence():
mutation = gql('\n mutation deleteArtifactSequence($id: ID!) {\n deleteArtifactSequence(input: {\n artifactSequenceID: $id\n }) {\n artifactCollection {\n ... | ['def', 'delete(self):', 'if', 'self.is_sequence():', 'mutation', '=', "gql('\\n", 'mutation', 'deleteArtifactSequence($id:', 'ID!)', '{\\n', 'deleteArtifactSequence(input:', '{\\n', 'artifactSequenceID:', '$id\\n', '})', '{\\n', 'artifactCollection', '{\\n', 'state\\n', '}\\n', '}\\n', '}\\n', "')", 'else:', 'mutation... | 941,488 |
wandb/wandb | _templates.py | create_example_header | create_example_header | Create an example header with image at top. | [
"Create",
"an",
"example",
"header",
"with",
"image",
"at",
"top."
] | def create_example_header():
import wandb.apis.reports as wr
return [wr.P(), wr.HorizontalRule(), wr.P(), wr.Image('https://camo.githubusercontent.com/83839f20c90facc062330f8fee5a7ab910fdd04b80b4c4c7e89d6d8137543540/68747470733a2f2f692e696d6775722e636f6d2f676236423469672e706e67'), wr.P(), wr.HorizontalRule(), w... | ['def', 'create_example_header():', 'import', 'wandb.apis.reports', 'as', 'wr', 'return', '[wr.P(),', 'wr.HorizontalRule(),', 'wr.P(),', "wr.Image('https://camo.githubusercontent.com/83839f20c90facc062330f8fee5a7ab910fdd04b80b4c4c7e89d6d8137543540/68747470733a2f2f692e696d6775722e636f6d2f676236423469672e706e67'),", 'wr.... | 941,495 |
wandb/wandb | _templates.py | create_customer_landing_page | create_customer_landing_page | Create an example customer landing page using data from Andrew's demo. | [
"Create",
"an",
"example",
"customer",
"landing",
"page",
"using",
"data",
"from",
"Andrew's",
"demo."
] | def create_customer_landing_page(project=None, company_name='My Company', main_contact='My Contact (name@email.com)', slack_link='https://company.slack.com'):
import wandb.apis.reports as wr
project = coalesce(project, 'default-project')
return wr.Report(project, title=f'Weights & Biases @ {company_name}', ... | ['def', 'create_customer_landing_page(project=None,', "company_name='My", "Company',", "main_contact='My", 'Contact', "(name@email.com)',", "slack_link='https://company.slack.com'):", 'import', 'wandb.apis.reports', 'as', 'wr', 'project', '=', 'coalesce(project,', "'default-project')", 'return', 'wr.Report(project,', "... | 941,498 |
wandb/wandb | __init__.py | is_docker_installed | is_docker_installed | Return `True` if docker is installed and working, else `False`. | [
"Return",
"`True`",
"if",
"docker",
"is",
"installed",
"and",
"working,",
"else",
"`False`."
] | def is_docker_installed() -> bool:
try:
result = subprocess.run(['docker', '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if result.returncode == 0:
return True
else:
return False
except FileNotFoundError:
return False | ['def', 'is_docker_installed()', '->', 'bool:', 'try:', 'result', '=', "subprocess.run(['docker',", "'--version'],", 'stdout=subprocess.PIPE,', 'stderr=subprocess.PIPE)', 'if', 'result.returncode', '==', '0:', 'return', 'True', 'else:', 'return', 'False', 'except', 'FileNotFoundError:', 'return', 'False'] | 941,514 |
wandb/wandb | __init__.py | get_image_uid | get_image_uid | Retrieve the image default uid through brute force. | [
"Retrieve",
"the",
"image",
"default",
"uid",
"through",
"brute",
"force."
] | def get_image_uid(image_name: str) -> int:
image_uid = shell(['run', image_name, 'id', '-u'])
return int(image_uid) if image_uid else -1 | ['def', 'get_image_uid(image_name:', 'str)', '->', 'int:', 'image_uid', '=', "shell(['run',", 'image_name,', "'id',", "'-u'])", 'return', 'int(image_uid)', 'if', 'image_uid', 'else', '-1'] | 941,518 |
wandb/wandb | __init__.py | login | login | Login to a registry. | [
"Login",
"to",
"a",
"registry."
] | def login(username: str, password: str, registry: str) -> Optional[str]:
return shell(['login', '--username', username, '--password', password, registry]) | ['def', 'login(username:', 'str,', 'password:', 'str,', 'registry:', 'str)', '->', 'Optional[str]:', 'return', "shell(['login',", "'--username',", 'username,', "'--password',", 'password,', 'registry])'] | 941,520 |
wandb/wandb | __init__.py | WandbCallback.on_train_begin | on_train_begin | Call watch method to log model topology, gradients & weights. | [
"Call",
"watch",
"method",
"to",
"log",
"model",
"topology,",
"gradients",
"&",
"weights."
] | def on_train_begin(self, **kwargs: Any) -> None:
super().on_train_begin()
if not WandbCallback._watch_called:
WandbCallback._watch_called = True
wandb.watch(self.learn.model, log=self.log) | ['def', 'on_train_begin(self,', '**kwargs:', 'Any)', '->', 'None:', 'super().on_train_begin()', 'if', 'not', 'WandbCallback._watch_called:', 'WandbCallback._watch_called', '=', 'True', 'wandb.watch(self.learn.model,', 'log=self.log)'] | 941,528 |
wandb/wandb | __init__.py | WandbCallback.on_epoch_end | on_epoch_end | Log training loss, validation loss and custom metrics & log prediction samples & save model. | [
"Log",
"training",
"loss,",
"validation",
"loss",
"and",
"custom",
"metrics",
"&",
"log",
"prediction",
"samples",
"&",
"save",
"model."
] | def on_epoch_end(self, epoch: int, smooth_loss: float, last_metrics: list, **kwargs: Any) -> None:
if self.save_model:
current = self.get_monitor_value()
if current is not None and self.operator(current, self.best):
print('Better model found at epoch {} with {} value: {}.'.format(epoch, ... | ['def', 'on_epoch_end(self,', 'epoch:', 'int,', 'smooth_loss:', 'float,', 'last_metrics:', 'list,', '**kwargs:', 'Any)', '->', 'None:', 'if', 'self.save_model:', 'current', '=', 'self.get_monitor_value()', 'if', 'current', 'is', 'not', 'None', 'and', 'self.operator(current,', 'self.best):', "print('Better", 'model', 'f... | 941,529 |
wandb/wandb | __init__.py | WandbCallback.on_train_end | on_train_end | Load the best model. | [
"Load",
"the",
"best",
"model."
] | def on_train_end(self, **kwargs: Any) -> None:
if self.save_model:
if self.model_path.is_file():
with self.model_path.open('rb') as model_file:
self.learn.load(model_file, purge=False)
print(f'Loaded best saved model from {self.model_path}') | ['def', 'on_train_end(self,', '**kwargs:', 'Any)', '->', 'None:', 'if', 'self.save_model:', 'if', 'self.model_path.is_file():', 'with', "self.model_path.open('rb')", 'as', 'model_file:', 'self.learn.load(model_file,', 'purge=False)', "print(f'Loaded", 'best', 'saved', 'model', 'from', "{self.model_path}')"] | 941,530 |
wandb/wandb | metrics_logger.py | WandbMetricsLogger.on_train_batch_end | on_train_batch_end | Called at the end of a training batch in `fit` methods. | [
"Called",
"at",
"the",
"end",
"of",
"a",
"training",
"batch",
"in",
"`fit`",
"methods."
] | def on_train_batch_end(self, batch: int, logs: Optional[Dict[str, Any]]=None) -> None:
self.on_batch_end(batch, logs if logs else {}) | ['def', 'on_train_batch_end(self,', 'batch:', 'int,', 'logs:', 'Optional[Dict[str,', 'Any]]=None)', '->', 'None:', 'self.on_batch_end(batch,', 'logs', 'if', 'logs', 'else', '{})'] | 941,534 |
wandb/wandb | wandb_logging.py | wandb_log | wandb_log | Wrap a standard python function and log to W&B. | [
"Wrap",
"a",
"standard",
"python",
"function",
"and",
"log",
"to",
"W&B."
] | def wandb_log(func=None, log_component_file=True):
import json
import os
from functools import wraps
from inspect import Parameter, signature
from kfp import components
from kfp.components import InputArtifact, InputBinaryFile, InputPath, InputTextFile, OutputArtifact, OutputBinaryFile, OutputPa... | ['def', 'wandb_log(func=None,', 'log_component_file=True):', 'import', 'json', 'import', 'os', 'from', 'functools', 'import', 'wraps', 'from', 'inspect', 'import', 'Parameter,', 'signature', 'from', 'kfp', 'import', 'components', 'from', 'kfp.components', 'import', 'InputArtifact,', 'InputBinaryFile,', 'InputPath,', 'I... | 941,545 |
wandb/wandb | prodigy.py | get_schema | get_schema | Get a schema of the dataset's structure and data types. | [
"Get",
"a",
"schema",
"of",
"the",
"dataset's",
"structure",
"and",
"data",
"types."
] | def get_schema(list_data_dict, struct, array_dict_types):
for (_i, item) in enumerate(list_data_dict):
for (k, v) in item.items():
if k not in struct.keys():
if isinstance(v, list):
if len(v) > 0 and isinstance(v[0], list):
struct[k] = ... | ['def', 'get_schema(list_data_dict,', 'struct,', 'array_dict_types):', 'for', '(_i,', 'item)', 'in', 'enumerate(list_data_dict):', 'for', '(k,', 'v)', 'in', 'item.items():', 'if', 'k', 'not', 'in', 'struct.keys():', 'if', 'isinstance(v,', 'list):', 'if', 'len(v)', '>', '0', 'and', 'isinstance(v[0],', 'list):', 'struct[... | 941,551 |
wandb/wandb | callback.py | WandBUltralyticsCallback.callbacks | callbacks | Property contains all the relevant callbacks to add to the YOLO model for the Weights & Biases logging. | [
"Property",
"contains",
"all",
"the",
"relevant",
"callbacks",
"to",
"add",
"to",
"the",
"YOLO",
"model",
"for",
"the",
"Weights",
"&",
"Biases",
"logging."
] | def callbacks(self) -> Dict[str, Callable]:
return {'on_train_start': self.on_train_start, 'on_fit_epoch_end': self.on_fit_epoch_end, 'on_train_end': self.on_train_end, 'on_val_end': self.on_val_end, 'on_predict_end': self.on_predict_end} | ['def', 'callbacks(self)', '->', 'Dict[str,', 'Callable]:', 'return', "{'on_train_start':", 'self.on_train_start,', "'on_fit_epoch_end':", 'self.on_fit_epoch_end,', "'on_train_end':", 'self.on_train_end,', "'on_val_end':", 'self.on_val_end,', "'on_predict_end':", 'self.on_predict_end}'] | 941,567 |
wandb/wandb | xgboost.py | WandbCallback.before_training | before_training | Run before training is finished. | [
"Run",
"before",
"training",
"is",
"finished."
] | def before_training(self, model: Booster) -> Booster:
config = model.save_config()
wandb.config.update(json.loads(config))
return model | ['def', 'before_training(self,', 'model:', 'Booster)', '->', 'Booster:', 'config', '=', 'model.save_config()', 'wandb.config.update(json.loads(config))', 'return', 'model'] | 941,571 |
wandb/wandb | yolov8.py | WandbCallback.on_pretrain_routine_start | on_pretrain_routine_start | Starts a new wandb run to track the training process and log to Weights & Biases. | [
"Starts",
"a",
"new",
"wandb",
"run",
"to",
"track",
"the",
"training",
"process",
"and",
"log",
"to",
"Weights",
"&",
"Biases."
] | def on_pretrain_routine_start(self, trainer: BaseTrainer) -> None:
if wandb.run is None:
self.run = wandb.init(name=self.run_name if self.run_name else trainer.args.name, project=self.project if self.project else trainer.args.project or 'YOLOv8', tags=self.tags if self.tags else ['YOLOv8'], config=vars(trai... | ['def', 'on_pretrain_routine_start(self,', 'trainer:', 'BaseTrainer)', '->', 'None:', 'if', 'wandb.run', 'is', 'None:', 'self.run', '=', 'wandb.init(name=self.run_name', 'if', 'self.run_name', 'else', 'trainer.args.name,', 'project=self.project', 'if', 'self.project', 'else', 'trainer.args.project', 'or', "'YOLOv8',", ... | 941,575 |
wandb/wandb | yolov8.py | WandbCallback.on_train_epoch_start | on_train_epoch_start | On train epoch start we only log epoch number to the Weights & Biases run. | [
"On",
"train",
"epoch",
"start",
"we",
"only",
"log",
"epoch",
"number",
"to",
"the",
"Weights",
"&",
"Biases",
"run."
] | def on_train_epoch_start(self, trainer: BaseTrainer) -> None:
self.run.log({'epoch': trainer.epoch + 1}) | ['def', 'on_train_epoch_start(self,', 'trainer:', 'BaseTrainer)', '->', 'None:', "self.run.log({'epoch':", 'trainer.epoch', '+', '1})'] | 941,576 |
wandb/wandb | yolov8.py | WandbCallback.on_fit_epoch_end | on_fit_epoch_end | On fit epoch end we log all the best metrics and model detail to Weights & Biases run summary. | [
"On",
"fit",
"epoch",
"end",
"we",
"log",
"all",
"the",
"best",
"metrics",
"and",
"model",
"detail",
"to",
"Weights",
"&",
"Biases",
"run",
"summary."
] | def on_fit_epoch_end(self, trainer: BaseTrainer) -> None:
if trainer.epoch == 0:
speeds = [trainer.validator.speed.get(key) for key in (1, 'inference')]
speed = speeds[0] if speeds[0] else speeds[1]
if speed:
self.run.summary.update({'model/speed(ms/img)': round(speed, 3)})
i... | ['def', 'on_fit_epoch_end(self,', 'trainer:', 'BaseTrainer)', '->', 'None:', 'if', 'trainer.epoch', '==', '0:', 'speeds', '=', '[trainer.validator.speed.get(key)', 'for', 'key', 'in', '(1,', "'inference')]", 'speed', '=', 'speeds[0]', 'if', 'speeds[0]', 'else', 'speeds[1]', 'if', 'speed:', "self.run.summary.update({'mo... | 941,578 |
wandb/wandb | wandb_settings.py | Property.value | value | Apply the runtime modifier(s) (if any) and return the value. | [
"Apply",
"the",
"runtime",
"modifier(s)",
"(if",
"any)",
"and",
"return",
"the",
"value."
] | def value(self) -> Any:
_value = self._value
if (_value is not None or self._auto_hook) and self._hook is not None:
_hook = [self._hook] if callable(self._hook) else self._hook
for h in _hook:
_value = h(_value)
return _value | ['def', 'value(self)', '->', 'Any:', '_value', '=', 'self._value', 'if', '(_value', 'is', 'not', 'None', 'or', 'self._auto_hook)', 'and', 'self._hook', 'is', 'not', 'None:', '_hook', '=', '[self._hook]', 'if', 'callable(self._hook)', 'else', 'self._hook', 'for', 'h', 'in', '_hook:', '_value', '=', 'h(_value)', 'return'... | 941,602 |
wandb/wandb | wandb_settings.py | Settings.to_dict | to_dict | Return a dict representation of the settings. | [
"Return",
"a",
"dict",
"representation",
"of",
"the",
"settings."
] | def to_dict(self) -> Dict[str, Any]:
attributes = {k: v.value for (k, v) in self.__dict__.items() if isinstance(v, Property)}
return attributes | ['def', 'to_dict(self)', '->', 'Dict[str,', 'Any]:', 'attributes', '=', '{k:', 'v.value', 'for', '(k,', 'v)', 'in', 'self.__dict__.items()', 'if', 'isinstance(v,', 'Property)}', 'return', 'attributes'] | 941,604 |
wandb/wandb | wandb_settings.py | Settings.to_proto | to_proto | Generate a protobuf representation of the settings. | [
"Generate",
"a",
"protobuf",
"representation",
"of",
"the",
"settings."
] | def to_proto(self) -> wandb_settings_pb2.Settings:
from dataclasses import fields
settings = wandb_settings_pb2.Settings()
for field in fields(SettingsData):
k = field.name
v = getattr(self, k)
if k == '_stats_open_metrics_filters':
if isinstance(v, (list, set, tuple)):
... | ['def', 'to_proto(self)', '->', 'wandb_settings_pb2.Settings:', 'from', 'dataclasses', 'import', 'fields', 'settings', '=', 'wandb_settings_pb2.Settings()', 'for', 'field', 'in', 'fields(SettingsData):', 'k', '=', 'field.name', 'v', '=', 'getattr(self,', 'k)', 'if', 'k', '==', "'_stats_open_metrics_filters':", 'if', 'i... | 941,605 |
wandb/wandb | artifact.py | Artifact.qualified_name | qualified_name | The entity/project/name of the secondary (portfolio) collection. | [
"The",
"entity/project/name",
"of",
"the",
"secondary",
"(portfolio)",
"collection."
] | def qualified_name(self) -> str:
return f'{self.entity}/{self.project}/{self.name}' | ['def', 'qualified_name(self)', '->', 'str:', 'return', "f'{self.entity}/{self.project}/{self.name}'"] | 941,612 |
wandb/wandb | artifact.py | Artifact.version | version | The artifact's version in its secondary (portfolio) collection. | [
"The",
"artifact's",
"version",
"in",
"its",
"secondary",
"(portfolio)",
"collection."
] | def version(self) -> str:
self._ensure_logged('version')
assert self._version is not None
return self._version | ['def', 'version(self)', '->', 'str:', "self._ensure_logged('version')", 'assert', 'self._version', 'is', 'not', 'None', 'return', 'self._version'] | 941,613 |
wandb/wandb | artifact.py | Artifact.source_collection | source_collection | The artifact's primary (sequence) collection. | [
"The",
"artifact's",
"primary",
"(sequence)",
"collection."
] | def source_collection(self) -> ArtifactCollection:
self._ensure_logged('source_collection')
base_name = self.source_name.split(':')[0]
return ArtifactCollection(self._client, self.source_entity, self.source_project, base_name, self.type) | ['def', 'source_collection(self)', '->', 'ArtifactCollection:', "self._ensure_logged('source_collection')", 'base_name', '=', "self.source_name.split(':')[0]", 'return', 'ArtifactCollection(self._client,', 'self.source_entity,', 'self.source_project,', 'base_name,', 'self.type)'] | 941,620 |
wandb/wandb | artifact.py | Artifact.aliases | aliases | Set the aliases associated with this artifact. | [
"Set",
"the",
"aliases",
"associated",
"with",
"this",
"artifact."
] | def aliases(self, aliases: List[str]) -> None:
self._ensure_logged('aliases')
if any((char in alias for alias in aliases for char in ['/', ':'])):
raise ValueError('Aliases must not contain any of the following characters: /, :')
self._aliases = aliases | ['def', 'aliases(self,', 'aliases:', 'List[str])', '->', 'None:', "self._ensure_logged('aliases')", 'if', 'any((char', 'in', 'alias', 'for', 'alias', 'in', 'aliases', 'for', 'char', 'in', "['/',", "':'])):", 'raise', "ValueError('Aliases", 'must', 'not', 'contain', 'any', 'of', 'the', 'following', 'characters:', '/,', ... | 941,628 |
wandb/wandb | artifact.py | Artifact.commit_hash | commit_hash | The hash returned when this artifact was committed. | [
"The",
"hash",
"returned",
"when",
"this",
"artifact",
"was",
"committed."
] | def commit_hash(self) -> str:
self._ensure_logged('commit_hash')
assert self._commit_hash is not None
return self._commit_hash | ['def', 'commit_hash(self)', '->', 'str:', "self._ensure_logged('commit_hash')", 'assert', 'self._commit_hash', 'is', 'not', 'None', 'return', 'self._commit_hash'] | 941,633 |
wandb/wandb | artifact.py | Artifact.created_at | created_at | The time at which the artifact was created. | [
"The",
"time",
"at",
"which",
"the",
"artifact",
"was",
"created."
] | def created_at(self) -> str:
self._ensure_logged('created_at')
assert self._created_at is not None
return self._created_at | ['def', 'created_at(self)', '->', 'str:', "self._ensure_logged('created_at')", 'assert', 'self._created_at', 'is', 'not', 'None', 'return', 'self._created_at'] | 941,635 |
wandb/wandb | storage_handler.py | StorageHandler.store_path | store_path | Store the file or directory at the given path to the specified artifact. | [
"Store",
"the",
"file",
"or",
"directory",
"at",
"the",
"given",
"path",
"to",
"the",
"specified",
"artifact."
] | def store_path(self, artifact: 'Artifact', path: Union[URIStr, FilePathStr], name: Optional[str]=None, checksum: bool=True, max_objects: Optional[int]=None) -> Sequence['ArtifactManifestEntry']:
raise NotImplementedError | ['def', 'store_path(self,', 'artifact:', "'Artifact',", 'path:', 'Union[URIStr,', 'FilePathStr],', 'name:', 'Optional[str]=None,', 'checksum:', 'bool=True,', 'max_objects:', 'Optional[int]=None)', '->', "Sequence['ArtifactManifestEntry']:", 'raise', 'NotImplementedError'] | 941,665 |
wandb/wandb | wandb_storage_policy.py | WandbStoragePolicy.default_file_upload | default_file_upload | Upload a file to the artifact store and write to cache. | [
"Upload",
"a",
"file",
"to",
"the",
"artifact",
"store",
"and",
"write",
"to",
"cache."
] | def default_file_upload(self, upload_url: str, file_path: str, extra_headers: Dict[str, Any], progress_callback: Optional['progress.ProgressFn']=None) -> None:
with open(file_path, 'rb') as file:
self._api.upload_file_retry(upload_url, file, progress_callback, extra_headers=extra_headers) | ['def', 'default_file_upload(self,', 'upload_url:', 'str,', 'file_path:', 'str,', 'extra_headers:', 'Dict[str,', 'Any],', 'progress_callback:', "Optional['progress.ProgressFn']=None)", '->', 'None:', 'with', 'open(file_path,', "'rb')", 'as', 'file:', 'self._api.upload_file_retry(upload_url,', 'file,', 'progress_callbac... | 941,670 |
wandb/wandb | trace_tree.py | Trace.add_inputs_and_outputs | add_inputs_and_outputs | Add a result to the span of the current trace. | [
"Add",
"a",
"result",
"to",
"the",
"span",
"of",
"the",
"current",
"trace."
] | def add_inputs_and_outputs(self, inputs: dict, outputs: dict) -> 'Trace':
if self._span.results is None:
result = Result(inputs=inputs, outputs=outputs)
self._span.results = [result]
else:
result = Result(inputs=inputs, outputs=outputs)
self._span.results.append(result)
retur... | ['def', 'add_inputs_and_outputs(self,', 'inputs:', 'dict,', 'outputs:', 'dict)', '->', "'Trace':", 'if', 'self._span.results', 'is', 'None:', 'result', '=', 'Result(inputs=inputs,', 'outputs=outputs)', 'self._span.results', '=', '[result]', 'else:', 'result', '=', 'Result(inputs=inputs,', 'outputs=outputs)', 'self._spa... | 941,680 |
wandb/wandb | trace_tree.py | Trace.add_metadata | add_metadata | Add metadata to the span of the current trace. | [
"Add",
"metadata",
"to",
"the",
"span",
"of",
"the",
"current",
"trace."
] | def add_metadata(self, metadata: dict) -> 'Trace':
if self._span.attributes is None:
self._span.attributes = metadata
else:
self._span.attributes.update(metadata)
return self | ['def', 'add_metadata(self,', 'metadata:', 'dict)', '->', "'Trace':", 'if', 'self._span.attributes', 'is', 'None:', 'self._span.attributes', '=', 'metadata', 'else:', 'self._span.attributes.update(metadata)', 'return', 'self'] | 941,681 |
wandb/wandb | trace_tree.py | Trace.inputs | inputs | Set the inputs of the trace. | [
"Set",
"the",
"inputs",
"of",
"the",
"trace."
] | def inputs(self, value: Dict[str, str]) -> None:
if self._span.results is None:
result = Result(inputs=value, outputs={})
self._span.results = [result]
else:
result = Result(inputs=value, outputs=self._span.results[-1].outputs)
self._span.results.append(result) | ['def', 'inputs(self,', 'value:', 'Dict[str,', 'str])', '->', 'None:', 'if', 'self._span.results', 'is', 'None:', 'result', '=', 'Result(inputs=value,', 'outputs={})', 'self._span.results', '=', '[result]', 'else:', 'result', '=', 'Result(inputs=value,', 'outputs=self._span.results[-1].outputs)', 'self._span.results.ap... | 941,685 |
wandb/wandb | trace_tree.py | Trace.outputs | outputs | Set the outputs of the trace. | [
"Set",
"the",
"outputs",
"of",
"the",
"trace."
] | def outputs(self, value: Dict[str, str]) -> None:
if self._span.results is None:
result = Result(inputs={}, outputs=value)
self._span.results = [result]
else:
result = Result(inputs=self._span.results[-1].inputs, outputs=value)
self._span.results.append(result) | ['def', 'outputs(self,', 'value:', 'Dict[str,', 'str])', '->', 'None:', 'if', 'self._span.results', 'is', 'None:', 'result', '=', 'Result(inputs={},', 'outputs=value)', 'self._span.results', '=', '[result]', 'else:', 'result', '=', 'Result(inputs=self._span.results[-1].inputs,', 'outputs=value)', 'self._span.results.ap... | 941,687 |
wandb/wandb | trace_tree.py | Trace.kind | kind | Set the kind of the trace. | [
"Set",
"the",
"kind",
"of",
"the",
"trace."
] | def kind(self, value: str) -> None:
assert value.upper() in SpanKind.__members__, "Invalid span kind, can be one of 'LLM', 'AGENT', 'CHAIN', 'TOOL'"
self._span.span_kind = SpanKind(value.upper()) | ['def', 'kind(self,', 'value:', 'str)', '->', 'None:', 'assert', 'value.upper()', 'in', 'SpanKind.__members__,', '"Invalid', 'span', 'kind,', 'can', 'be', 'one', 'of', "'LLM',", "'AGENT',", "'CHAIN',", '\'TOOL\'"', 'self._span.span_kind', '=', 'SpanKind(value.upper())'] | 941,689 |
wandb/wandb | auto_logging.py | PatchAPI.set_api | set_api | Returns the API module. | [
"Returns",
"the",
"API",
"module."
] | def set_api(self) -> Any:
lib_name = self.name.lower()
if self._api is None:
self._api = wandb.util.get_module(name=lib_name, required=f'To use the W&B {self.name} Autolog, you need to have the `{lib_name}` python package installed. Please install it with `pip install {lib_name}`.', lazy=False)
retu... | ['def', 'set_api(self)', '->', 'Any:', 'lib_name', '=', 'self.name.lower()', 'if', 'self._api', 'is', 'None:', 'self._api', '=', 'wandb.util.get_module(name=lib_name,', "required=f'To", 'use', 'the', 'W&B', '{self.name}', 'Autolog,', 'you', 'need', 'to', 'have', 'the', '`{lib_name}`', 'python', 'package', 'installed.',... | 941,705 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.