code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def metric(self, metric):
"""Sets the metric of this V2ObjectMetricSource.
:param metric: The metric of this V2ObjectMetricSource. # noqa: E501
:type: V2MetricIdentifier
"""
if self.local_vars_configuration.client_side_validation and metric is None: # noqa: E501
r... | Sets the metric of this V2ObjectMetricSource.
:param metric: The metric of this V2ObjectMetricSource. # noqa: E501
:type: V2MetricIdentifier
| metric | python | kubernetes-client/python | kubernetes/client/models/v2_object_metric_source.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/client/models/v2_object_metric_source.py | Apache-2.0 |
def target(self, target):
"""Sets the target of this V2ObjectMetricSource.
:param target: The target of this V2ObjectMetricSource. # noqa: E501
:type: V2MetricTarget
"""
if self.local_vars_configuration.client_side_validation and target is None: # noqa: E501
raise... | Sets the target of this V2ObjectMetricSource.
:param target: The target of this V2ObjectMetricSource. # noqa: E501
:type: V2MetricTarget
| target | python | kubernetes-client/python | kubernetes/client/models/v2_object_metric_source.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/client/models/v2_object_metric_source.py | Apache-2.0 |
def current(self, current):
"""Sets the current of this V2ObjectMetricStatus.
:param current: The current of this V2ObjectMetricStatus. # noqa: E501
:type: V2MetricValueStatus
"""
if self.local_vars_configuration.client_side_validation and current is None: # noqa: E501
... | Sets the current of this V2ObjectMetricStatus.
:param current: The current of this V2ObjectMetricStatus. # noqa: E501
:type: V2MetricValueStatus
| current | python | kubernetes-client/python | kubernetes/client/models/v2_object_metric_status.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/client/models/v2_object_metric_status.py | Apache-2.0 |
def described_object(self, described_object):
"""Sets the described_object of this V2ObjectMetricStatus.
:param described_object: The described_object of this V2ObjectMetricStatus. # noqa: E501
:type: V2CrossVersionObjectReference
"""
if self.local_vars_configuration.client_si... | Sets the described_object of this V2ObjectMetricStatus.
:param described_object: The described_object of this V2ObjectMetricStatus. # noqa: E501
:type: V2CrossVersionObjectReference
| described_object | python | kubernetes-client/python | kubernetes/client/models/v2_object_metric_status.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/client/models/v2_object_metric_status.py | Apache-2.0 |
def metric(self, metric):
"""Sets the metric of this V2ObjectMetricStatus.
:param metric: The metric of this V2ObjectMetricStatus. # noqa: E501
:type: V2MetricIdentifier
"""
if self.local_vars_configuration.client_side_validation and metric is None: # noqa: E501
r... | Sets the metric of this V2ObjectMetricStatus.
:param metric: The metric of this V2ObjectMetricStatus. # noqa: E501
:type: V2MetricIdentifier
| metric | python | kubernetes-client/python | kubernetes/client/models/v2_object_metric_status.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/client/models/v2_object_metric_status.py | Apache-2.0 |
def metric(self, metric):
"""Sets the metric of this V2PodsMetricSource.
:param metric: The metric of this V2PodsMetricSource. # noqa: E501
:type: V2MetricIdentifier
"""
if self.local_vars_configuration.client_side_validation and metric is None: # noqa: E501
raise... | Sets the metric of this V2PodsMetricSource.
:param metric: The metric of this V2PodsMetricSource. # noqa: E501
:type: V2MetricIdentifier
| metric | python | kubernetes-client/python | kubernetes/client/models/v2_pods_metric_source.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/client/models/v2_pods_metric_source.py | Apache-2.0 |
def target(self, target):
"""Sets the target of this V2PodsMetricSource.
:param target: The target of this V2PodsMetricSource. # noqa: E501
:type: V2MetricTarget
"""
if self.local_vars_configuration.client_side_validation and target is None: # noqa: E501
raise Val... | Sets the target of this V2PodsMetricSource.
:param target: The target of this V2PodsMetricSource. # noqa: E501
:type: V2MetricTarget
| target | python | kubernetes-client/python | kubernetes/client/models/v2_pods_metric_source.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/client/models/v2_pods_metric_source.py | Apache-2.0 |
def current(self, current):
"""Sets the current of this V2PodsMetricStatus.
:param current: The current of this V2PodsMetricStatus. # noqa: E501
:type: V2MetricValueStatus
"""
if self.local_vars_configuration.client_side_validation and current is None: # noqa: E501
... | Sets the current of this V2PodsMetricStatus.
:param current: The current of this V2PodsMetricStatus. # noqa: E501
:type: V2MetricValueStatus
| current | python | kubernetes-client/python | kubernetes/client/models/v2_pods_metric_status.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/client/models/v2_pods_metric_status.py | Apache-2.0 |
def metric(self, metric):
"""Sets the metric of this V2PodsMetricStatus.
:param metric: The metric of this V2PodsMetricStatus. # noqa: E501
:type: V2MetricIdentifier
"""
if self.local_vars_configuration.client_side_validation and metric is None: # noqa: E501
raise... | Sets the metric of this V2PodsMetricStatus.
:param metric: The metric of this V2PodsMetricStatus. # noqa: E501
:type: V2MetricIdentifier
| metric | python | kubernetes-client/python | kubernetes/client/models/v2_pods_metric_status.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/client/models/v2_pods_metric_status.py | Apache-2.0 |
def name(self, name):
"""Sets the name of this V2ResourceMetricSource.
name is the name of the resource in question. # noqa: E501
:param name: The name of this V2ResourceMetricSource. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation ... | Sets the name of this V2ResourceMetricSource.
name is the name of the resource in question. # noqa: E501
:param name: The name of this V2ResourceMetricSource. # noqa: E501
:type: str
| name | python | kubernetes-client/python | kubernetes/client/models/v2_resource_metric_source.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/client/models/v2_resource_metric_source.py | Apache-2.0 |
def target(self, target):
"""Sets the target of this V2ResourceMetricSource.
:param target: The target of this V2ResourceMetricSource. # noqa: E501
:type: V2MetricTarget
"""
if self.local_vars_configuration.client_side_validation and target is None: # noqa: E501
r... | Sets the target of this V2ResourceMetricSource.
:param target: The target of this V2ResourceMetricSource. # noqa: E501
:type: V2MetricTarget
| target | python | kubernetes-client/python | kubernetes/client/models/v2_resource_metric_source.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/client/models/v2_resource_metric_source.py | Apache-2.0 |
def current(self, current):
"""Sets the current of this V2ResourceMetricStatus.
:param current: The current of this V2ResourceMetricStatus. # noqa: E501
:type: V2MetricValueStatus
"""
if self.local_vars_configuration.client_side_validation and current is None: # noqa: E501
... | Sets the current of this V2ResourceMetricStatus.
:param current: The current of this V2ResourceMetricStatus. # noqa: E501
:type: V2MetricValueStatus
| current | python | kubernetes-client/python | kubernetes/client/models/v2_resource_metric_status.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/client/models/v2_resource_metric_status.py | Apache-2.0 |
def name(self, name):
"""Sets the name of this V2ResourceMetricStatus.
name is the name of the resource in question. # noqa: E501
:param name: The name of this V2ResourceMetricStatus. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation ... | Sets the name of this V2ResourceMetricStatus.
name is the name of the resource in question. # noqa: E501
:param name: The name of this V2ResourceMetricStatus. # noqa: E501
:type: str
| name | python | kubernetes-client/python | kubernetes/client/models/v2_resource_metric_status.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/client/models/v2_resource_metric_status.py | Apache-2.0 |
def build_date(self, build_date):
"""Sets the build_date of this VersionInfo.
:param build_date: The build_date of this VersionInfo. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and build_date is None: # noqa: E501
raise Valu... | Sets the build_date of this VersionInfo.
:param build_date: The build_date of this VersionInfo. # noqa: E501
:type: str
| build_date | python | kubernetes-client/python | kubernetes/client/models/version_info.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/client/models/version_info.py | Apache-2.0 |
def compiler(self, compiler):
"""Sets the compiler of this VersionInfo.
:param compiler: The compiler of this VersionInfo. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and compiler is None: # noqa: E501
raise ValueError("Inva... | Sets the compiler of this VersionInfo.
:param compiler: The compiler of this VersionInfo. # noqa: E501
:type: str
| compiler | python | kubernetes-client/python | kubernetes/client/models/version_info.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/client/models/version_info.py | Apache-2.0 |
def git_tree_state(self, git_tree_state):
"""Sets the git_tree_state of this VersionInfo.
:param git_tree_state: The git_tree_state of this VersionInfo. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and git_tree_state is None: # noqa: E50... | Sets the git_tree_state of this VersionInfo.
:param git_tree_state: The git_tree_state of this VersionInfo. # noqa: E501
:type: str
| git_tree_state | python | kubernetes-client/python | kubernetes/client/models/version_info.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/client/models/version_info.py | Apache-2.0 |
def git_version(self, git_version):
"""Sets the git_version of this VersionInfo.
:param git_version: The git_version of this VersionInfo. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and git_version is None: # noqa: E501
rais... | Sets the git_version of this VersionInfo.
:param git_version: The git_version of this VersionInfo. # noqa: E501
:type: str
| git_version | python | kubernetes-client/python | kubernetes/client/models/version_info.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/client/models/version_info.py | Apache-2.0 |
def go_version(self, go_version):
"""Sets the go_version of this VersionInfo.
:param go_version: The go_version of this VersionInfo. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and go_version is None: # noqa: E501
raise Valu... | Sets the go_version of this VersionInfo.
:param go_version: The go_version of this VersionInfo. # noqa: E501
:type: str
| go_version | python | kubernetes-client/python | kubernetes/client/models/version_info.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/client/models/version_info.py | Apache-2.0 |
def major(self, major):
"""Sets the major of this VersionInfo.
Major is the major version of the binary version # noqa: E501
:param major: The major of this VersionInfo. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and major is N... | Sets the major of this VersionInfo.
Major is the major version of the binary version # noqa: E501
:param major: The major of this VersionInfo. # noqa: E501
:type: str
| major | python | kubernetes-client/python | kubernetes/client/models/version_info.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/client/models/version_info.py | Apache-2.0 |
def minor(self, minor):
"""Sets the minor of this VersionInfo.
Minor is the minor version of the binary version # noqa: E501
:param minor: The minor of this VersionInfo. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and minor is N... | Sets the minor of this VersionInfo.
Minor is the minor version of the binary version # noqa: E501
:param minor: The minor of this VersionInfo. # noqa: E501
:type: str
| minor | python | kubernetes-client/python | kubernetes/client/models/version_info.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/client/models/version_info.py | Apache-2.0 |
def platform(self, platform):
"""Sets the platform of this VersionInfo.
:param platform: The platform of this VersionInfo. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and platform is None: # noqa: E501
raise ValueError("Inva... | Sets the platform of this VersionInfo.
:param platform: The platform of this VersionInfo. # noqa: E501
:type: str
| platform | python | kubernetes-client/python | kubernetes/client/models/version_info.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/client/models/version_info.py | Apache-2.0 |
def test_create_apps_deployment_from_yaml(self):
"""
Should be able to create an apps/v1 deployment.
"""
k8s_client = client.api_client.ApiClient(configuration=self.config)
utils.create_from_yaml(
k8s_client, self.path_prefix + "apps-deployment.yaml")
app_api ... |
Should be able to create an apps/v1 deployment.
| test_create_apps_deployment_from_yaml | python | kubernetes-client/python | kubernetes/e2e_test/test_utils.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/e2e_test/test_utils.py | Apache-2.0 |
def test_create_apps_deployment_from_yaml_object(self):
"""
Should be able to pass YAML objects directly to helper function.
"""
k8s_client = client.api_client.ApiClient(configuration=self.config)
_path = self.path_prefix + "apps-deployment.yaml"
with open(path.abspath(_p... |
Should be able to pass YAML objects directly to helper function.
| test_create_apps_deployment_from_yaml_object | python | kubernetes-client/python | kubernetes/e2e_test/test_utils.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/e2e_test/test_utils.py | Apache-2.0 |
def test_create_pod_from_yaml(self):
"""
Should be able to create a pod.
"""
k8s_client = client.api_client.ApiClient(configuration=self.config)
utils.create_from_yaml(
k8s_client, self.path_prefix + "core-pod.yaml")
core_api = client.CoreV1Api(k8s_client)
... |
Should be able to create a pod.
| test_create_pod_from_yaml | python | kubernetes-client/python | kubernetes/e2e_test/test_utils.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/e2e_test/test_utils.py | Apache-2.0 |
def test_create_service_from_yaml(self):
"""
Should be able to create a service.
"""
k8s_client = client.api_client.ApiClient(configuration=self.config)
utils.create_from_yaml(
k8s_client, self.path_prefix + "core-service.yaml")
core_api = client.CoreV1Api(k8s... |
Should be able to create a service.
| test_create_service_from_yaml | python | kubernetes-client/python | kubernetes/e2e_test/test_utils.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/e2e_test/test_utils.py | Apache-2.0 |
def test_create_namespace_from_yaml(self):
"""
Should be able to create a namespace.
"""
k8s_client = client.api_client.ApiClient(configuration=self.config)
utils.create_from_yaml(
k8s_client, self.path_prefix + "core-namespace.yaml")
core_api = client.CoreV1A... |
Should be able to create a namespace.
| test_create_namespace_from_yaml | python | kubernetes-client/python | kubernetes/e2e_test/test_utils.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/e2e_test/test_utils.py | Apache-2.0 |
def test_create_rbac_role_from_yaml(self):
"""
Should be able to create a rbac role.
"""
k8s_client = client.api_client.ApiClient(configuration=self.config)
utils.create_from_yaml(
k8s_client, self.path_prefix + "rbac-role.yaml")
rbac_api = client.RbacAuthoriz... |
Should be able to create a rbac role.
| test_create_rbac_role_from_yaml | python | kubernetes-client/python | kubernetes/e2e_test/test_utils.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/e2e_test/test_utils.py | Apache-2.0 |
def test_create_rbac_role_from_yaml_with_verbose_enabled(self):
"""
Should be able to create a rbac role with verbose enabled.
"""
k8s_client = client.api_client.ApiClient(configuration=self.config)
utils.create_from_yaml(
k8s_client, self.path_prefix + "rbac-role.yam... |
Should be able to create a rbac role with verbose enabled.
| test_create_rbac_role_from_yaml_with_verbose_enabled | python | kubernetes-client/python | kubernetes/e2e_test/test_utils.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/e2e_test/test_utils.py | Apache-2.0 |
def test_create_deployment_non_default_namespace_from_yaml(self):
"""
Should be able to create a namespace "dep",
and then create a deployment in the just-created namespace.
"""
k8s_client = client.ApiClient(configuration=self.config)
utils.create_from_yaml(
k... |
Should be able to create a namespace "dep",
and then create a deployment in the just-created namespace.
| test_create_deployment_non_default_namespace_from_yaml | python | kubernetes-client/python | kubernetes/e2e_test/test_utils.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/e2e_test/test_utils.py | Apache-2.0 |
def test_create_apiservice_from_yaml_with_conflict(self):
"""
Should be able to create an API service.
Should verify that creating the same API service should
fail due to conflict.
"""
k8s_client = client.api_client.ApiClient(configuration=self.config)
utils.creat... |
Should be able to create an API service.
Should verify that creating the same API service should
fail due to conflict.
| test_create_apiservice_from_yaml_with_conflict | python | kubernetes-client/python | kubernetes/e2e_test/test_utils.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/e2e_test/test_utils.py | Apache-2.0 |
def test_create_general_list_from_yaml(self):
"""
Should be able to create a service and a deployment
from a kind: List yaml file
"""
k8s_client = client.api_client.ApiClient(configuration=self.config)
utils.create_from_yaml(
k8s_client, self.path_prefix + "li... |
Should be able to create a service and a deployment
from a kind: List yaml file
| test_create_general_list_from_yaml | python | kubernetes-client/python | kubernetes/e2e_test/test_utils.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/e2e_test/test_utils.py | Apache-2.0 |
def test_create_namespace_list_from_yaml(self):
"""
Should be able to create two namespaces
from a kind: NamespaceList yaml file
"""
k8s_client = client.api_client.ApiClient(configuration=self.config)
utils.create_from_yaml(
k8s_client, self.path_prefix + "nam... |
Should be able to create two namespaces
from a kind: NamespaceList yaml file
| test_create_namespace_list_from_yaml | python | kubernetes-client/python | kubernetes/e2e_test/test_utils.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/e2e_test/test_utils.py | Apache-2.0 |
def test_create_implicit_service_list_from_yaml_with_conflict(self):
"""
Should be able to create two services from a kind: ServiceList
json file that implicitly indicates the kind of individual objects
"""
k8s_client = client.api_client.ApiClient(configuration=self.config)
... |
Should be able to create two services from a kind: ServiceList
json file that implicitly indicates the kind of individual objects
| test_create_implicit_service_list_from_yaml_with_conflict | python | kubernetes-client/python | kubernetes/e2e_test/test_utils.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/e2e_test/test_utils.py | Apache-2.0 |
def test_create_multi_resource_from_directory(self):
"""
Should be able to create a service and a replication controller
from a directory
"""
k8s_client = client.api_client.ApiClient(configuration=self.config)
utils.create_from_directory(
k8s_client, self.path... |
Should be able to create a service and a replication controller
from a directory
| test_create_multi_resource_from_directory | python | kubernetes-client/python | kubernetes/e2e_test/test_utils.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/e2e_test/test_utils.py | Apache-2.0 |
def test_create_from_multi_resource_yaml(self):
"""
Should be able to create a service and a replication controller
from a multi-resource yaml file
"""
k8s_client = client.api_client.ApiClient(configuration=self.config)
utils.create_from_yaml(
k8s_client, self... |
Should be able to create a service and a replication controller
from a multi-resource yaml file
| test_create_from_multi_resource_yaml | python | kubernetes-client/python | kubernetes/e2e_test/test_utils.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/e2e_test/test_utils.py | Apache-2.0 |
def test_create_from_list_in_multi_resource_yaml(self):
"""
Should be able to create the items in the PodList and a deployment
specified in the multi-resource file
"""
k8s_client = client.api_client.ApiClient(configuration=self.config)
utils.create_from_yaml(
... |
Should be able to create the items in the PodList and a deployment
specified in the multi-resource file
| test_create_from_list_in_multi_resource_yaml | python | kubernetes-client/python | kubernetes/e2e_test/test_utils.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/e2e_test/test_utils.py | Apache-2.0 |
def test_create_from_multi_resource_yaml_with_conflict(self):
"""
Should be able to create a service from the first yaml file.
Should fail to create the same service from the second yaml file
and create a replication controller.
Should raise an exception for failure to create the... |
Should be able to create a service from the first yaml file.
Should fail to create the same service from the second yaml file
and create a replication controller.
Should raise an exception for failure to create the same service twice.
| test_create_from_multi_resource_yaml_with_conflict | python | kubernetes-client/python | kubernetes/e2e_test/test_utils.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/e2e_test/test_utils.py | Apache-2.0 |
def test_create_from_multi_resource_yaml_with_multi_conflicts(self):
"""
Should create an apps/v1 deployment
and fail to create the same deployment twice.
Should raise an exception that contains two error messages.
"""
k8s_client = client.api_client.ApiClient(configuratio... |
Should create an apps/v1 deployment
and fail to create the same deployment twice.
Should raise an exception that contains two error messages.
| test_create_from_multi_resource_yaml_with_multi_conflicts | python | kubernetes-client/python | kubernetes/e2e_test/test_utils.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/e2e_test/test_utils.py | Apache-2.0 |
def test_create_namespaced_apps_deployment_from_yaml(self):
"""
Should be able to create an apps/v1beta1 deployment
in a test namespace.
"""
k8s_client = client.api_client.ApiClient(configuration=self.config)
utils.create_from_yaml(
k8s_client, self.pa... |
Should be able to create an apps/v1beta1 deployment
in a test namespace.
| test_create_namespaced_apps_deployment_from_yaml | python | kubernetes-client/python | kubernetes/e2e_test/test_utils.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/e2e_test/test_utils.py | Apache-2.0 |
def test_create_from_list_in_multi_resource_yaml_namespaced(self):
"""
Should be able to create the items in the PodList and a deployment
specified in the multi-resource file in a test namespace
"""
k8s_client = client.api_client.ApiClient(configuration=self.config)
utils... |
Should be able to create the items in the PodList and a deployment
specified in the multi-resource file in a test namespace
| test_create_from_list_in_multi_resource_yaml_namespaced | python | kubernetes-client/python | kubernetes/e2e_test/test_utils.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/e2e_test/test_utils.py | Apache-2.0 |
def test_format_quantity(self):
"""Unit test for quantity.format_quantity. Testing the different SI suffixes and
function should return the expected string"""
# == unknown suffixes ==
self.assertRaises(
ValueError, lambda: quantity.format_quantity(Decimal(1_000), "kb")
... | Unit test for quantity.format_quantity. Testing the different SI suffixes and
function should return the expected string | test_format_quantity | python | kubernetes-client/python | kubernetes/e2e_test/test_utils.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/e2e_test/test_utils.py | Apache-2.0 |
def create_from_directory(
k8s_client, yaml_dir=None, verbose=False, namespace="default", apply=False, **kwargs
):
"""
Perform an action from files from a directory. Pass True for verbose to
print confirmation information.
Input:
k8s_client: an ApiClient object, initialized with the client args... |
Perform an action from files from a directory. Pass True for verbose to
print confirmation information.
Input:
k8s_client: an ApiClient object, initialized with the client args.
yaml_dir: string. Contains the path to directory.
verbose: If True, print confirmation from the create action.
... | create_from_directory | python | kubernetes-client/python | kubernetes/utils/create_from_yaml.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/utils/create_from_yaml.py | Apache-2.0 |
def create_from_yaml(
k8s_client,
yaml_file=None,
yaml_objects=None,
verbose=False,
namespace="default",
apply=False,
**kwargs,
):
"""
Perform an action from a yaml file. Pass True for verbose to
print confirmation information.
Input:
yaml_file: string. Contains the path ... |
Perform an action from a yaml file. Pass True for verbose to
print confirmation information.
Input:
yaml_file: string. Contains the path to yaml file.
k8s_client: an ApiClient object, initialized with the client args.
yaml_objects: List[dict]. Optional list of YAML objects; used instead
... | create_from_yaml | python | kubernetes-client/python | kubernetes/utils/create_from_yaml.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/utils/create_from_yaml.py | Apache-2.0 |
def create_from_dict(
k8s_client, data, verbose=False, namespace="default", apply=False, **kwargs
):
"""
Perform an action from a dictionary containing valid kubernetes
API object (i.e. List, Service, etc).
Input:
k8s_client: an ApiClient object, initialized with the client args.
data: a di... |
Perform an action from a dictionary containing valid kubernetes
API object (i.e. List, Service, etc).
Input:
k8s_client: an ApiClient object, initialized with the client args.
data: a dictionary holding valid kubernetes objects
verbose: If True, print confirmation from the create action.
... | create_from_dict | python | kubernetes-client/python | kubernetes/utils/create_from_yaml.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/utils/create_from_yaml.py | Apache-2.0 |
def parse_duration(duration) -> datetime.timedelta:
"""
Parse GEP-2257 Duration format to a datetime.timedelta object.
The GEP-2257 Duration format is a restricted form of the input to the Go
time.ParseDuration function; specifically, it must match the regex
"^([0-9]{1,5}(h|m|s|ms)){1,4}$".
Se... |
Parse GEP-2257 Duration format to a datetime.timedelta object.
The GEP-2257 Duration format is a restricted form of the input to the Go
time.ParseDuration function; specifically, it must match the regex
"^([0-9]{1,5}(h|m|s|ms)){1,4}$".
See https://gateway-api.sigs.k8s.io/geps/gep-2257/ for more d... | parse_duration | python | kubernetes-client/python | kubernetes/utils/duration.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/utils/duration.py | Apache-2.0 |
def format_duration(delta: datetime.timedelta) -> str:
"""
Format a datetime.timedelta object to GEP-2257 Duration format.
The GEP-2257 Duration format is a restricted form of the input to the Go
time.ParseDuration function; specifically, it must match the regex
"^([0-9]{1,5}(h|m|s|ms)){1,4}$".
... |
Format a datetime.timedelta object to GEP-2257 Duration format.
The GEP-2257 Duration format is a restricted form of the input to the Go
time.ParseDuration function; specifically, it must match the regex
"^([0-9]{1,5}(h|m|s|ms)){1,4}$".
See https://gateway-api.sigs.k8s.io/geps/gep-2257/ for more ... | format_duration | python | kubernetes-client/python | kubernetes/utils/duration.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/utils/duration.py | Apache-2.0 |
def parse_quantity(quantity):
"""
Parse kubernetes canonical form quantity like 200Mi to a decimal number.
Supported SI suffixes:
base1024: Ki | Mi | Gi | Ti | Pi | Ei
base1000: n | u | m | "" | k | M | G | T | P | E
See https://github.com/kubernetes/apimachinery/blob/master/pkg/api/resource/qu... |
Parse kubernetes canonical form quantity like 200Mi to a decimal number.
Supported SI suffixes:
base1024: Ki | Mi | Gi | Ti | Pi | Ei
base1000: n | u | m | "" | k | M | G | T | P | E
See https://github.com/kubernetes/apimachinery/blob/master/pkg/api/resource/quantity.go
Input:
quantity: s... | parse_quantity | python | kubernetes-client/python | kubernetes/utils/quantity.py | https://github.com/kubernetes-client/python/blob/master/kubernetes/utils/quantity.py | Apache-2.0 |
def get_frame_from_vcap_with_fps(vidcap, num_frames=10, max_fps=0.0, fps=None, frame_count=None, video_file_name=None):
"""
num_frames is the max number of frames the model can support.
frame_count is the number of frames in the input video.
max_fps is the max FPS of the model can support.
fps is th... |
num_frames is the max number of frames the model can support.
frame_count is the number of frames in the input video.
max_fps is the max FPS of the model can support.
fps is the fps of the input video.
| get_frame_from_vcap_with_fps | python | NVlabs/VILA | llava/mm_utils.py | https://github.com/NVlabs/VILA/blob/master/llava/mm_utils.py | Apache-2.0 |
def opencv_extract_frames(vpath_or_bytesio, frames=6, max_fps=0.0, fps=None, frame_count=None):
"""
Extract frames from a video using OpenCV.
Args:
vpath_or_bytesio (str or BytesIO): Path to the video file or BytesIO object containing the video.
frames (int): Number of frames to extract fro... |
Extract frames from a video using OpenCV.
Args:
vpath_or_bytesio (str or BytesIO): Path to the video file or BytesIO object containing the video.
frames (int): Number of frames to extract from the video.
fps (float): Frames per second of the video. If 0.0, the function will extract fra... | opencv_extract_frames | python | NVlabs/VILA | llava/mm_utils.py | https://github.com/NVlabs/VILA/blob/master/llava/mm_utils.py | Apache-2.0 |
def expand2square(pil_img, background_color):
"""
Expand the given PIL image to a square shape by adding padding.
Parameters:
- pil_img: The PIL image to be expanded.
- background_color: The color of the padding to be added.
Returns:
- The expanded PIL image.
If the image is already s... |
Expand the given PIL image to a square shape by adding padding.
Parameters:
- pil_img: The PIL image to be expanded.
- background_color: The color of the padding to be added.
Returns:
- The expanded PIL image.
If the image is already square, it is returned as is.
If the image is wide... | expand2square | python | NVlabs/VILA | llava/mm_utils.py | https://github.com/NVlabs/VILA/blob/master/llava/mm_utils.py | Apache-2.0 |
def decode_time_token(text: str, *, duration: float, num_time_tokens: int, time_token_format: str) -> str:
"""Replace time tokens in text with actual timestamps."""
for t in range(num_time_tokens):
time_token = time_token_format.format(t=t)
timestamp = round(t * duration / (num_time_tokens - 1),... | Replace time tokens in text with actual timestamps. | decode_time_token | python | NVlabs/VILA | llava/cli/infer.py | https://github.com/NVlabs/VILA/blob/master/llava/cli/infer.py | Apache-2.0 |
def configure_ps3_and_context_length(model):
"""Configure PS3 settings and adjust context length based on those settings."""
# get PS3 configs from environment variables
num_look_close = os.environ.get("NUM_LOOK_CLOSE", None)
num_token_look_close = os.environ.get("NUM_TOKEN_LOOK_CLOSE", None)
selec... | Configure PS3 settings and adjust context length based on those settings. | configure_ps3_and_context_length | python | NVlabs/VILA | llava/cli/infer.py | https://github.com/NVlabs/VILA/blob/master/llava/cli/infer.py | Apache-2.0 |
def local_load_or_hf_load(data_path: str) -> List:
"""
Load data from either a local file or from Hugging Face Hub.
Args:
data_path (str): Path to the data file. Can be a local path or a Hugging Face path.
For Hugging Face paths, use the following formats:
- hf://repo_owner/... |
Load data from either a local file or from Hugging Face Hub.
Args:
data_path (str): Path to the data file. Can be a local path or a Hugging Face path.
For Hugging Face paths, use the following formats:
- hf://repo_owner/repo_name/path/to/file.json (for model repositories)
... | local_load_or_hf_load | python | NVlabs/VILA | llava/data/base.py | https://github.com/NVlabs/VILA/blob/master/llava/data/base.py | Apache-2.0 |
def make_supervised_data_module(
tokenizer: PreTrainedTokenizer,
data_args: DataArguments,
training_args: TrainingArguments,
) -> Dict:
"""Make dataset and collator for supervised fine-tuning.
This function is originally implemented by the LLaVA team and
modified by Jason Lu, Haotian Tang and Li... | Make dataset and collator for supervised fine-tuning.
This function is originally implemented by the LLaVA team and
modified by Jason Lu, Haotian Tang and Ligeng Zhu. | make_supervised_data_module | python | NVlabs/VILA | llava/data/dataset.py | https://github.com/NVlabs/VILA/blob/master/llava/data/dataset.py | Apache-2.0 |
def hf_download_data(
repo_id="Efficient-Large-Model/VILA-inference-demos",
filename="imagenet_cat.jpg",
cache_dir=None,
repo_type="dataset",
):
"""
Download dummy data from a Hugging Face repository.
Args:
repo_id (str): The ID of the Hugging Face repository.
filename (str): The na... |
Download dummy data from a Hugging Face repository.
Args:
repo_id (str): The ID of the Hugging Face repository.
filename (str): The name of the file to download.
cache_dir (str, optional): The directory to cache the downloaded file.
Returns:
str: The path to the downloaded file.
| hf_download_data | python | NVlabs/VILA | llava/data/dataset_impl/dummy.py | https://github.com/NVlabs/VILA/blob/master/llava/data/dataset_impl/dummy.py | Apache-2.0 |
def get_category(vid_id, mapping):
"""Find the corresponding category based on vid_id prefix."""
for key in mapping:
key_base = os.path.splitext(key)[0] # Remove extension from key
if vid_id.startswith(key_base):
return mapping[key]
return "Other" | Find the corresponding category based on vid_id prefix. | get_category | python | NVlabs/VILA | llava/eval/domain.py | https://github.com/NVlabs/VILA/blob/master/llava/eval/domain.py | Apache-2.0 |
def extract_count_zero_shot(text):
"""
Extract count for cars or lanes from a given text.
Args:
text (str): The input text to parse.
entity (str): The entity to extract the count for ("car" or "lane").
Returns:
int or None: The extracted count, or None if not found.
"""
... |
Extract count for cars or lanes from a given text.
Args:
text (str): The input text to parse.
entity (str): The entity to extract the count for ("car" or "lane").
Returns:
int or None: The extracted count, or None if not found.
| extract_count_zero_shot | python | NVlabs/VILA | llava/eval/its.py | https://github.com/NVlabs/VILA/blob/master/llava/eval/its.py | Apache-2.0 |
def load_dataset(args):
"""Load dataset and distribute instances across ranks."""
data_path = DATASETS[args.dataset]["data_path"]
image_dir = DATASETS[args.dataset]["image_dir"]
instances = io.load(data_path)[dist.rank() :: dist.size()]
return instances, image_dir | Load dataset and distribute instances across ranks. | load_dataset | python | NVlabs/VILA | llava/eval/its.py | https://github.com/NVlabs/VILA/blob/master/llava/eval/its.py | Apache-2.0 |
def process_instance(instance, image_dir, model, generation_config, task, task_ques, is_zero_shot=False):
"""Process a single instance for a given task."""
results = []
prompt = []
if "image" in instance.keys() and task in ["car_count", "lane_count"]:
image = instance["image"]
question =... | Process a single instance for a given task. | process_instance | python | NVlabs/VILA | llava/eval/its.py | https://github.com/NVlabs/VILA/blob/master/llava/eval/its.py | Apache-2.0 |
def _compute_answer_scores(self, raw_answers):
"""
compute the accuracy (soft score) of human answers
"""
answers = [self.answer_processor(a) for a in raw_answers]
assert len(answers) == 10
gt_answers = list(enumerate(answers))
unique_answers = set(answers)
... |
compute the accuracy (soft score) of human answers
| _compute_answer_scores | python | NVlabs/VILA | llava/eval/m4c_evaluator.py | https://github.com/NVlabs/VILA/blob/master/llava/eval/m4c_evaluator.py | Apache-2.0 |
def compute_metrics(outputs, output_dir, metric_func):
"""
Computes and prints evaluation metrics in a structured format and saves results to a JSON file.
Args:
outputs (list): List of dictionaries containing evaluation results.
output_dir (str): Directory where the metrics JSON file will b... |
Computes and prints evaluation metrics in a structured format and saves results to a JSON file.
Args:
outputs (list): List of dictionaries containing evaluation results.
output_dir (str): Directory where the metrics JSON file will be saved.
metric_func (dict): Dictionary of metric func... | compute_metrics | python | NVlabs/VILA | llava/eval/rtl_nv_lita.py | https://github.com/NVlabs/VILA/blob/master/llava/eval/rtl_nv_lita.py | Apache-2.0 |
def load_and_merge_jsons(directory):
"""Load and merge all JSON files in a directory."""
merged_data = []
for file in glob.glob(os.path.join(directory, "*.json")):
with open(file) as f:
try:
data = json.load(f)
if isinstance(data, list):
... | Load and merge all JSON files in a directory. | load_and_merge_jsons | python | NVlabs/VILA | llava/eval/rtl_nv_lita.py | https://github.com/NVlabs/VILA/blob/master/llava/eval/rtl_nv_lita.py | Apache-2.0 |
def load_mapping_json(directory):
"""Load and merge all mapping JSON files into a single dictionary."""
merged_mapping = {}
for file in glob.glob(os.path.join(directory, "*.json")):
with open(file) as f:
try:
data = json.load(f)
if isinstance(data, dict):
... | Load and merge all mapping JSON files into a single dictionary. | load_mapping_json | python | NVlabs/VILA | llava/eval/rtl_nv_lita.py | https://github.com/NVlabs/VILA/blob/master/llava/eval/rtl_nv_lita.py | Apache-2.0 |
def get_category(vid_id, mapping):
"""Find the corresponding category based on vid_id prefix after removing extensions."""
for key in mapping:
key_base = os.path.splitext(key)[0] # Remove extension from key
if vid_id.startswith(key_base):
return mapping[key]
return "Other" | Find the corresponding category based on vid_id prefix after removing extensions. | get_category | python | NVlabs/VILA | llava/eval/rtl_nv_lita.py | https://github.com/NVlabs/VILA/blob/master/llava/eval/rtl_nv_lita.py | Apache-2.0 |
def iou(s1: Tuple[float, float], s2: Tuple[float, float]) -> float:
"""Compute Intersection over Union (IoU) for timestamps."""
i = max(min(s1[1], s2[1]) - max(s1[0], s2[0]), 0)
u = max(s1[1] - s1[0], 0) + max(s2[1] - s2[0], 0) - i
return i / u if u > 0 else 0 | Compute Intersection over Union (IoU) for timestamps. | iou | python | NVlabs/VILA | llava/eval/rtl_nv_lita.py | https://github.com/NVlabs/VILA/blob/master/llava/eval/rtl_nv_lita.py | Apache-2.0 |
def precision(threshold: float):
"""Return precision function based on IoU threshold."""
def precision_func(s1: Tuple[float, float], s2: Tuple[float, float]) -> float:
return float(iou(s1, s2) >= threshold)
return precision_func | Return precision function based on IoU threshold. | precision | python | NVlabs/VILA | llava/eval/rtl_nv_lita.py | https://github.com/NVlabs/VILA/blob/master/llava/eval/rtl_nv_lita.py | Apache-2.0 |
def get_most_similar(prediction, choices):
"""
Use the Levenshtein distance (or edit distance) to determine which of the choices is most similar to the given prediction
"""
distances = [distance(prediction, choice) for choice in choices]
ind = distances.index(min(distances))
return choices[ind]
... |
Use the Levenshtein distance (or edit distance) to determine which of the choices is most similar to the given prediction
| get_most_similar | python | NVlabs/VILA | llava/eval/mathvista_utils/calculate_score.py | https://github.com/NVlabs/VILA/blob/master/llava/eval/mathvista_utils/calculate_score.py | Apache-2.0 |
def normalize_extracted_answer(extraction, choices, question_type, answer_type, precision):
"""
Normalize the extracted answer to match the answer type
"""
if question_type == "multi_choice":
# make sure the extraction is a string
if isinstance(extraction, str):
extraction = ... |
Normalize the extracted answer to match the answer type
| normalize_extracted_answer | python | NVlabs/VILA | llava/eval/mathvista_utils/calculate_score.py | https://github.com/NVlabs/VILA/blob/master/llava/eval/mathvista_utils/calculate_score.py | Apache-2.0 |
def safe_equal(prediction, answer):
"""
Check if the prediction is equal to the answer, even if they are of different types
"""
try:
if prediction == answer:
return True
return False
except Exception as e:
print(e)
return False |
Check if the prediction is equal to the answer, even if they are of different types
| safe_equal | python | NVlabs/VILA | llava/eval/mathvista_utils/calculate_score.py | https://github.com/NVlabs/VILA/blob/master/llava/eval/mathvista_utils/calculate_score.py | Apache-2.0 |
def parse_choice(response, all_choices, index2ans=None):
"""
Parse the prediction from the generated response.
Return the predicted index e.g., A, B, C, D.
"""
for char in [",", ".", "!", "?", ";", ":", "'"]:
response = response.strip(char)
response = " " + response + " " # add space to... |
Parse the prediction from the generated response.
Return the predicted index e.g., A, B, C, D.
| parse_choice | python | NVlabs/VILA | llava/eval/mmmu_utils/eval_utils.py | https://github.com/NVlabs/VILA/blob/master/llava/eval/mmmu_utils/eval_utils.py | Apache-2.0 |
def annotate(prediction_set, caption_files, output_dir, args):
"""
Evaluates question and answer pairs using GPT-3.5/GPT-4
Returns a score for correctness.
"""
try:
client = AzureOpenAI(
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
api_version="2024-02-01",
... |
Evaluates question and answer pairs using GPT-3.5/GPT-4
Returns a score for correctness.
| annotate | python | NVlabs/VILA | llava/eval/video/eval_video_qa.py | https://github.com/NVlabs/VILA/blob/master/llava/eval/video/eval_video_qa.py | Apache-2.0 |
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_value: Optional[Tuple[torch.Tensor]] = None,
output_attentions: Optional[bool] = False,
use_cache: Optional[boo... |
Args:
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
`(batch, sequence_length)` where padding elements are indicated by 0.
output_attentio... | forward | python | NVlabs/VILA | llava/eval/vision_niah_vila/zigzag_ring_attn/modeling_qwen2.py | https://github.com/NVlabs/VILA/blob/master/llava/eval/vision_niah_vila/zigzag_ring_attn/modeling_qwen2.py | Apache-2.0 |
def forward(
self,
input_ids: torch.LongTensor = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[List[torch.FloatTensor]] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
lab... |
Args:
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `... | forward | python | NVlabs/VILA | llava/eval/vision_niah_vila/zigzag_ring_attn/modeling_qwen2.py | https://github.com/NVlabs/VILA/blob/master/llava/eval/vision_niah_vila/zigzag_ring_attn/modeling_qwen2.py | Apache-2.0 |
def freezed_module_patch(self):
"""
Huggingface will call model.train() at each training_step. To ensure the expected behaviors for modules like dropout, batchnorm, etc., we need to call model.eval() for the freezed modules.
"""
if self.training:
if self.get_llm() and not get... |
Huggingface will call model.train() at each training_step. To ensure the expected behaviors for modules like dropout, batchnorm, etc., we need to call model.eval() for the freezed modules.
| freezed_module_patch | python | NVlabs/VILA | llava/model/llava_arch.py | https://github.com/NVlabs/VILA/blob/master/llava/model/llava_arch.py | Apache-2.0 |
def merge_chessboard(x, num_split_h, num_split_w):
"""
x: b * n * c or b * h * w * c
out: b * c * h * w
Assuming x contains num_split**2 sub-squares concatenated along batch dimension, merge the sub-squares back to the original whole square.
"""
B = x.shape[0]
if ... |
x: b * n * c or b * h * w * c
out: b * c * h * w
Assuming x contains num_split**2 sub-squares concatenated along batch dimension, merge the sub-squares back to the original whole square.
| merge_chessboard | python | NVlabs/VILA | llava/model/llava_arch.py | https://github.com/NVlabs/VILA/blob/master/llava/model/llava_arch.py | Apache-2.0 |
def split_chessboard(x, num_split_h, num_split_w):
"""
x: b * c * h * w
out: b * c * h * w
Deividing x into num_split**2 sub-squares, and concatenate all the sub-squares on the batch dimension
"""
B, C, H, W = x.shape
assert H % num_split_h == 0 and W % num_split_... |
x: b * c * h * w
out: b * c * h * w
Deividing x into num_split**2 sub-squares, and concatenate all the sub-squares on the batch dimension
| split_chessboard | python | NVlabs/VILA | llava/model/llava_arch.py | https://github.com/NVlabs/VILA/blob/master/llava/model/llava_arch.py | Apache-2.0 |
def forward(
self,
hidden_states: torch.Tensor,
quant_hidden_states: torch.Tensor,
scale_hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_value: Optional[Cache] = None,
ou... |
Args:
hidden_states (`torch.FloatTensor`): BF16 input to the layer of shape `(batch, seq_len, embed_dim)`
quant_hidden_states (`torch.float8_e4m3fn`): FP8 input to the layer of shape `(batch, seq_len, embed_dim)`
scale_hidden_states (`torch.bfloat16`): BF16 scaling factor to... | forward | python | NVlabs/VILA | llava/model/coat/activation/models/coat_llama.py | https://github.com/NVlabs/VILA/blob/master/llava/model/coat/activation/models/coat_llama.py | Apache-2.0 |
def download_and_convert_llama(convert_args: ConvertArguments, quantization_args: QuantizationConfig):
"""
Downloads a LLaMA model, converts its weights using `make_state_dict_compatible`,
and saves the converted model.
Args:
model_name (str): The model name or path to download the LLaMA model.... |
Downloads a LLaMA model, converts its weights using `make_state_dict_compatible`,
and saves the converted model.
Args:
model_name (str): The model name or path to download the LLaMA model.
save_path (str): The path where the converted model weights will be saved.
cache_dir (Optiona... | download_and_convert_llama | python | NVlabs/VILA | llava/model/coat/activation/models/coat_llama_convert_from_hf.py | https://github.com/NVlabs/VILA/blob/master/llava/model/coat/activation/models/coat_llama_convert_from_hf.py | Apache-2.0 |
def _scaled_dot_product_attention(
self,
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
attn_mask: torch.Tensor | None = None,
dropout_p: float = 0.0,
is_causal: bool = False,
max_doc_len: int | None = None,
cu_doc_lens: torch.Tensor | None = N... |
Computes scaled dot product attention on query, key and value tensors, using an optional
attention mask if passed, and applying dropout if a probability greater than 0.0 is specified.
| _scaled_dot_product_attention | python | NVlabs/VILA | llava/model/coat/activation/models/coat_olmo.py | https://github.com/NVlabs/VILA/blob/master/llava/model/coat/activation/models/coat_olmo.py | Apache-2.0 |
def forward(
self,
input_ids: torch.LongTensor,
input_embeddings: torch.FloatTensor | None = None,
attention_mask: torch.Tensor | None = None,
attention_bias: torch.Tensor | None = None,
past_key_values: Sequence[tuple[torch.Tensor, torch.Tensor]] | None = None,
u... |
:param input_ids: A tensor of shape `(batch_size, seq_len)`.
:param input_embeddings: A tensor of shape `(batch_size, seq_len, d_model)` with input
embeddings. When provided, it is treated as the output of the input embedding layer.
:param attention_mask: A tensor of shape `(batch_s... | forward | python | NVlabs/VILA | llava/model/coat/activation/models/coat_olmo.py | https://github.com/NVlabs/VILA/blob/master/llava/model/coat/activation/models/coat_olmo.py | Apache-2.0 |
def from_checkpoint(
cls, checkpoint_dir: PathOrStr, device: str = "cpu", checkpoint_type: CheckpointType | None = None
) -> CoatOLMo:
"""
Load an OLMo model from a checkpoint.
"""
from olmo.util import resource_path
# Guess checkpoint type.
if checkpoint_typ... |
Load an OLMo model from a checkpoint.
| from_checkpoint | python | NVlabs/VILA | llava/model/coat/activation/models/coat_olmo.py | https://github.com/NVlabs/VILA/blob/master/llava/model/coat/activation/models/coat_olmo.py | Apache-2.0 |
def _make_state_dict_compatible(
self, state_dict: dict[str, torch.Tensor]
) -> tuple[dict[str, torch.Tensor], dict[str, set[str]]]:
"""
Handles some cases where the state dict is valid yet may need to be transformed in order to
be loaded.
This modifies the state dict in-pla... |
Handles some cases where the state dict is valid yet may need to be transformed in order to
be loaded.
This modifies the state dict in-place and also returns it, along with a mapping of original key
names to new key names in cases where the keys were simply renamed. That mapping can be... | _make_state_dict_compatible | python | NVlabs/VILA | llava/model/coat/activation/models/coat_olmo.py | https://github.com/NVlabs/VILA/blob/master/llava/model/coat/activation/models/coat_olmo.py | Apache-2.0 |
def load_state_dict(self, state_dict: StateDict) -> None:
r"""Loads the optimizer state.
Args:
state_dict (dict): optimizer state. Should be an object returned
from a call to :meth:`state_dict`.
"""
# shallow copy, to be consistent with module API
sta... | Loads the optimizer state.
Args:
state_dict (dict): optimizer state. Should be an object returned
from a call to :meth:`state_dict`.
| load_state_dict | python | NVlabs/VILA | llava/model/coat/optimizer/fp8_adamw.py | https://github.com/NVlabs/VILA/blob/master/llava/model/coat/optimizer/fp8_adamw.py | Apache-2.0 |
def _cast(param, value, param_id=None, param_groups=None, key=None):
r"""Make a deep copy of value, casting all tensors to device of param."""
if isinstance(value, torch.Tensor):
return CoatAdamW._process_value_according_to_param_policy(param, value, param_id, param_groups, key)
... | Make a deep copy of value, casting all tensors to device of param. | _cast | python | NVlabs/VILA | llava/model/coat/optimizer/fp8_adamw.py | https://github.com/NVlabs/VILA/blob/master/llava/model/coat/optimizer/fp8_adamw.py | Apache-2.0 |
def step(self, closure=None):
"""Perform a single optimization step.
Args:
closure (Callable, optional): A closure that reevaluates the model
and returns the loss.
"""
self._cuda_graph_capture_health_check()
loss = None
if closure is not None... | Perform a single optimization step.
Args:
closure (Callable, optional): A closure that reevaluates the model
and returns the loss.
| step | python | NVlabs/VILA | llava/model/coat/optimizer/fp8_adamw.py | https://github.com/NVlabs/VILA/blob/master/llava/model/coat/optimizer/fp8_adamw.py | Apache-2.0 |
def Coatadamw(
qargs,
params: List[Tensor],
grads: List[Tensor],
exp_avgs: List[Tensor],
scale_exp_avgs: List[Tensor],
expand_exp_avgs: List[Tensor],
sqrt_minmax_exp_avgs: List[Tensor],
exp_avg_sqs: List[Tensor],
scale_exp_avg_sqs: List[Tensor],
expand_exp_avg_sqs: List[Tensor],
... | Functional API that performs AdamW algorithm computation.
See :class:`~torch.optim.AdamW` for details.
| Coatadamw | python | NVlabs/VILA | llava/model/coat/optimizer/fp8_adamw.py | https://github.com/NVlabs/VILA/blob/master/llava/model/coat/optimizer/fp8_adamw.py | Apache-2.0 |
def forward(
self,
hidden_states: torch.Tensor,
quant_hidden_states: torch.Tensor,
scale_hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_value: Optional[Tuple[torch.Tensor]] = No... |
Args:
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
`(batch, sequence_length)` where padding elements are indicated by 0.
output_attentio... | forward | python | NVlabs/VILA | llava/model/language_model/fp8activationqwen2.py | https://github.com/NVlabs/VILA/blob/master/llava/model/language_model/fp8activationqwen2.py | Apache-2.0 |
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_value: Optional[Cache] = None,
output_attentions: Optional[bool] = False,
use_cache: Optional[bool] = False,
... |
Args:
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
attention_mask (`torch.FloatTensor`, *optional*):
attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
qu... | forward | python | NVlabs/VILA | llava/model/language_model/qmemllama.py | https://github.com/NVlabs/VILA/blob/master/llava/model/language_model/qmemllama.py | Apache-2.0 |
def forward(
ctx,
_input: torch.Tensor,
target: torch.Tensor,
ignore_index: int = -100,
lse_square_scale: float = 0.0,
label_smoothing: float = 0.0,
reduction: str = "mean",
softcap: Optional[float] = None,
return_z_loss: bool = False,
):
... |
The forward pass of the Liger Cross Entropy loss.
Parameters:
ctx : The context object.
_input (tensor): The input tensor of shape (BT, V) where B is batch size, T is sequence length, V is vocab size.
target (tensor): The target tensor of shape (BT) where each value is in [0, V... | forward | python | NVlabs/VILA | llava/model/liger/cross_entropy.py | https://github.com/NVlabs/VILA/blob/master/llava/model/liger/cross_entropy.py | Apache-2.0 |
def backward(ctx, grad_output, grad_ouput2):
"""
The backward pass of the Liger Cross Entropy loss.
Parameters:
ctx : The context object with saved tensors.
grad_output (tensor): The tensor containing the gradient of the loss with respect to the output.
grad_output2 (ten... |
The backward pass of the Liger Cross Entropy loss.
Parameters:
ctx : The context object with saved tensors.
grad_output (tensor): The tensor containing the gradient of the loss with respect to the output.
grad_output2 (tenosr): No use.
Returns:
tuple: A tuple wi... | backward | python | NVlabs/VILA | llava/model/liger/cross_entropy.py | https://github.com/NVlabs/VILA/blob/master/llava/model/liger/cross_entropy.py | Apache-2.0 |
def element_mul_kernel(
X_ptr,
X_stride,
grad_output_ptr,
n_cols,
BLOCK_SIZE: tl.constexpr,
):
"""
This function multiplies each element of the tensor pointed by X_ptr with the value pointed by grad_output_ptr.
The multiplication is performed in-place on the tensor pointed by X_ptr.
... |
This function multiplies each element of the tensor pointed by X_ptr with the value pointed by grad_output_ptr.
The multiplication is performed in-place on the tensor pointed by X_ptr.
Parameters:
X_ptr: Pointer to the input tensor.
X_stride (int): The stride of the input tensor.
grad_output_p... | element_mul_kernel | python | NVlabs/VILA | llava/model/liger/utils.py | https://github.com/NVlabs/VILA/blob/master/llava/model/liger/utils.py | Apache-2.0 |
def pad_image(
self,
image: np.ndarray,
pad_size: Dict[str, int],
data_format: Optional[Union[str, ChannelDimension]] = None,
input_data_format: Optional[Union[str, ChannelDimension]] = None,
**kwargs,
) -> np.ndarray:
"""
Pad an image to `(pad_size["h... |
Pad an image to `(pad_size["height"], pad_size["width"])` to the right and bottom.
Args:
image (`np.ndarray`):
Image to pad.
pad_size (`Dict[str, int]`):
Size of the output image after padding.
data_format (`str` or `ChannelDimension`... | pad_image | python | NVlabs/VILA | llava/model/multimodal_encoder/image_processor.py | https://github.com/NVlabs/VILA/blob/master/llava/model/multimodal_encoder/image_processor.py | Apache-2.0 |
def _get_preprocess_shape(self, old_shape: Tuple[int, int], longest_edge: int):
"""
Compute the output size given input size and target long side length.
"""
oldh, oldw = old_shape
scale = longest_edge * 1.0 / max(oldh, oldw)
newh, neww = oldh * scale, oldw * scale
... |
Compute the output size given input size and target long side length.
| _get_preprocess_shape | python | NVlabs/VILA | llava/model/multimodal_encoder/image_processor.py | https://github.com/NVlabs/VILA/blob/master/llava/model/multimodal_encoder/image_processor.py | Apache-2.0 |
def resize(
self,
image: np.ndarray,
size: Dict[str, int],
resample: PILImageResampling = PILImageResampling.BICUBIC,
data_format: Optional[Union[str, ChannelDimension]] = None,
input_data_format: Optional[Union[str, ChannelDimension]] = None,
**kwargs,
) -> n... |
Resize an image to `(size["height"], size["width"])`.
Args:
image (`np.ndarray`):
Image to resize.
size (`Dict[str, int]`):
Dictionary in the format `{"longest_edge": int}` or `{"width": int, "height": int}` specifying the size
of... | resize | python | NVlabs/VILA | llava/model/multimodal_encoder/image_processor.py | https://github.com/NVlabs/VILA/blob/master/llava/model/multimodal_encoder/image_processor.py | Apache-2.0 |
def preprocess(
self,
images: ImageInput,
do_resize: Optional[bool] = None,
size: Optional[Dict[str, int]] = None,
resample: Optional["PILImageResampling"] = None,
do_rescale: Optional[bool] = None,
rescale_factor: Optional[Union[int, float]] = None,
do_no... |
Preprocess an image or batch of images.
Args:
images (`ImageInput`):
Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
passing in images with pixel values between 0 and 1, set `do_rescale=False`.
... | preprocess | python | NVlabs/VILA | llava/model/multimodal_encoder/image_processor.py | https://github.com/NVlabs/VILA/blob/master/llava/model/multimodal_encoder/image_processor.py | Apache-2.0 |
def main(rank: int = 0, world_size: int = 1):
"""
Computes the RankMe (http://arxiv.org/abs/2210.02885) and LiDAR (http://arxiv.org/abs/2312.04000)
estimates of the rank of the produced embeddings. While RADIO doesn't train in a multi-view setting
which is an assumption of LiDAR, the metric does integra... |
Computes the RankMe (http://arxiv.org/abs/2210.02885) and LiDAR (http://arxiv.org/abs/2312.04000)
estimates of the rank of the produced embeddings. While RADIO doesn't train in a multi-view setting
which is an assumption of LiDAR, the metric does integrate an important concept of the invariance of the
... | main | python | NVlabs/VILA | llava/model/multimodal_encoder/visualize_features.py | https://github.com/NVlabs/VILA/blob/master/llava/model/multimodal_encoder/visualize_features.py | Apache-2.0 |
def get_pca_map(
feature_map: torch.Tensor,
img_size,
interpolation="bicubic",
return_pca_stats=False,
pca_stats=None,
):
"""
feature_map: (1, h, w, C) is the feature map of a single image.
"""
feature_map = feature_map.float()
if feature_map.shape[0] != 1:
# make it (1, ... |
feature_map: (1, h, w, C) is the feature map of a single image.
| get_pca_map | python | NVlabs/VILA | llava/model/multimodal_encoder/visualize_features.py | https://github.com/NVlabs/VILA/blob/master/llava/model/multimodal_encoder/visualize_features.py | Apache-2.0 |
def get_scale_map(
scalar_map: torch.Tensor,
img_size,
interpolation="nearest",
):
"""
scalar_map: (1, h, w, C) is the feature map of a single image.
"""
if scalar_map.shape[0] != 1:
scalar_map = scalar_map[None]
scalar_map = (scalar_map - scalar_map.min()) / (scalar_map.max() - ... |
scalar_map: (1, h, w, C) is the feature map of a single image.
| get_scale_map | python | NVlabs/VILA | llava/model/multimodal_encoder/visualize_features.py | https://github.com/NVlabs/VILA/blob/master/llava/model/multimodal_encoder/visualize_features.py | Apache-2.0 |
def get_similarity_map(features: torch.Tensor, img_size=(224, 224)):
"""
compute the similarity map of the central patch to the rest of the image
"""
assert len(features.shape) == 4, "features should be (1, C, H, W)"
H, W, C = features.shape[1:]
center_patch_feature = features[0, H // 2, W // 2,... |
compute the similarity map of the central patch to the rest of the image
| get_similarity_map | python | NVlabs/VILA | llava/model/multimodal_encoder/visualize_features.py | https://github.com/NVlabs/VILA/blob/master/llava/model/multimodal_encoder/visualize_features.py | Apache-2.0 |
def forward(self, qkv, key_padding_mask=None, causal=False, cu_seqlens=None, max_s=None, need_weights=False):
"""Implements the multihead softmax attention.
Arguments
---------
qkv: The tensor containing the query, key, and value. (B, S, 3, H, D) if key_padding_mask is None
... | Implements the multihead softmax attention.
Arguments
---------
qkv: The tensor containing the query, key, and value. (B, S, 3, H, D) if key_padding_mask is None
if unpadded: (nnz, 3, h, d)
key_padding_mask: a bool tensor of shape (B, S)
| forward | python | NVlabs/VILA | llava/model/multimodal_encoder/intern/flash_attention.py | https://github.com/NVlabs/VILA/blob/master/llava/model/multimodal_encoder/intern/flash_attention.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.