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 make_instance(self, include_optional):
"""Test V1beta1MetricTarget
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included"""
# model = kserve.models.v1beta1_metric_target.V1beta1MetricTarget() # noq... | Test V1beta1MetricTarget
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | make_instance | python | kserve/kserve | python/kserve/test/test_v1beta1_metric_target.py | https://github.com/kserve/kserve/blob/master/python/kserve/test/test_v1beta1_metric_target.py | Apache-2.0 |
def make_instance(self, include_optional):
"""Test V1beta1ModelCopies
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included"""
# model = kserve.models.v1beta1_model_copies.V1beta1ModelCopies() # noqa: ... | Test V1beta1ModelCopies
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | make_instance | python | kserve/kserve | python/kserve/test/test_v1beta1_model_copies.py | https://github.com/kserve/kserve/blob/master/python/kserve/test/test_v1beta1_model_copies.py | Apache-2.0 |
def make_instance(self, include_optional):
"""Test V1beta1ModelFormat
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included"""
# model = kserve.models.v1beta1_model_format.V1beta1ModelFormat() # noqa: ... | Test V1beta1ModelFormat
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | make_instance | python | kserve/kserve | python/kserve/test/test_v1beta1_model_format.py | https://github.com/kserve/kserve/blob/master/python/kserve/test/test_v1beta1_model_format.py | Apache-2.0 |
def make_instance(self, include_optional):
"""Test V1beta1ModelRevisionStates
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included"""
# model = kserve.models.v1beta1_model_revision_states.V1beta1ModelR... | Test V1beta1ModelRevisionStates
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | make_instance | python | kserve/kserve | python/kserve/test/test_v1beta1_model_revision_states.py | https://github.com/kserve/kserve/blob/master/python/kserve/test/test_v1beta1_model_revision_states.py | Apache-2.0 |
def make_instance(self, include_optional):
"""Test V1beta1ModelSpec
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included"""
# model = kserve.models.v1beta1_model_spec.V1beta1ModelSpec() # noqa: E501
... | Test V1beta1ModelSpec
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | make_instance | python | kserve/kserve | python/kserve/test/test_v1beta1_model_spec.py | https://github.com/kserve/kserve/blob/master/python/kserve/test/test_v1beta1_model_spec.py | Apache-2.0 |
def make_instance(self, include_optional):
"""Test V1beta1ModelStatus
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included"""
# model = kserve.models.v1beta1_model_status.V1beta1ModelStatus() # noqa: ... | Test V1beta1ModelStatus
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | make_instance | python | kserve/kserve | python/kserve/test/test_v1beta1_model_status.py | https://github.com/kserve/kserve/blob/master/python/kserve/test/test_v1beta1_model_status.py | Apache-2.0 |
def make_instance(self, include_optional):
"""Test V1beta1MultiNodeConfig
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included"""
# model = kserve.models.v1beta1_multi_node_config.V1beta1MultiNodeConfi... | Test V1beta1MultiNodeConfig
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | make_instance | python | kserve/kserve | python/kserve/test/test_v1beta1_multi_node_config.py | https://github.com/kserve/kserve/blob/master/python/kserve/test/test_v1beta1_multi_node_config.py | Apache-2.0 |
def make_instance(self, include_optional):
"""Test V1beta1ONNXRuntimeSpec
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included"""
# model = kserve.models.v1beta1_onnx_runtime_spec.V1beta1ONNXRuntimeSpe... | Test V1beta1ONNXRuntimeSpec
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | make_instance | python | kserve/kserve | python/kserve/test/test_v1beta1_onnx_runtime_spec.py | https://github.com/kserve/kserve/blob/master/python/kserve/test/test_v1beta1_onnx_runtime_spec.py | Apache-2.0 |
def make_instance(self, include_optional):
"""Test V1beta1OtelCollectorConfig
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included"""
# model = kserve.models.v1beta1_otel_collector_config.V1beta1OtelCo... | Test V1beta1OtelCollectorConfig
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | make_instance | python | kserve/kserve | python/kserve/test/test_v1beta1_otel_collector_config.py | https://github.com/kserve/kserve/blob/master/python/kserve/test/test_v1beta1_otel_collector_config.py | Apache-2.0 |
def make_instance(self, include_optional):
"""Test V1beta1PaddleServerSpec
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included"""
# model = kserve.models.v1beta1_paddle_server_spec.V1beta1PaddleServer... | Test V1beta1PaddleServerSpec
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | make_instance | python | kserve/kserve | python/kserve/test/test_v1beta1_paddle_server_spec.py | https://github.com/kserve/kserve/blob/master/python/kserve/test/test_v1beta1_paddle_server_spec.py | Apache-2.0 |
def make_instance(self, include_optional):
"""Test V1beta1PMMLSpec
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included"""
# model = kserve.models.v1beta1_pmml_spec.V1beta1PMMLSpec() # noqa: E501
... | Test V1beta1PMMLSpec
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | make_instance | python | kserve/kserve | python/kserve/test/test_v1beta1_pmml_spec.py | https://github.com/kserve/kserve/blob/master/python/kserve/test/test_v1beta1_pmml_spec.py | Apache-2.0 |
def make_instance(self, include_optional):
"""Test V1beta1PodMetrics
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included"""
# model = kserve.models.v1beta1_pod_metrics.V1beta1PodMetrics() # noqa: E50... | Test V1beta1PodMetrics
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | make_instance | python | kserve/kserve | python/kserve/test/test_v1beta1_pod_metrics.py | https://github.com/kserve/kserve/blob/master/python/kserve/test/test_v1beta1_pod_metrics.py | Apache-2.0 |
def make_instance(self, include_optional):
"""Test V1beta1PodMetricSource
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included"""
# model = kserve.models.v1beta1_pod_metric_source.V1beta1PodMetricSourc... | Test V1beta1PodMetricSource
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | make_instance | python | kserve/kserve | python/kserve/test/test_v1beta1_pod_metric_source.py | https://github.com/kserve/kserve/blob/master/python/kserve/test/test_v1beta1_pod_metric_source.py | Apache-2.0 |
def make_instance(self, include_optional):
"""Test V1beta1PodSpec
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included"""
# model = kserve.models.v1beta1_pod_spec.V1beta1PodSpec() # noqa: E501
... | Test V1beta1PodSpec
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | make_instance | python | kserve/kserve | python/kserve/test/test_v1beta1_pod_spec.py | https://github.com/kserve/kserve/blob/master/python/kserve/test/test_v1beta1_pod_spec.py | Apache-2.0 |
def make_instance(self, include_optional):
"""Test V1beta1PredictorsConfig
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included"""
# model = kserve.models.v1beta1_predictors_config.V1beta1PredictorsCon... | Test V1beta1PredictorsConfig
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | make_instance | python | kserve/kserve | python/kserve/test/test_v1beta1_predictors_config.py | https://github.com/kserve/kserve/blob/master/python/kserve/test/test_v1beta1_predictors_config.py | Apache-2.0 |
def make_instance(self, include_optional):
"""Test V1beta1PredictorConfig
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included"""
# model = kserve.models.v1beta1_predictor_config.V1beta1PredictorConfig... | Test V1beta1PredictorConfig
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | make_instance | python | kserve/kserve | python/kserve/test/test_v1beta1_predictor_config.py | https://github.com/kserve/kserve/blob/master/python/kserve/test/test_v1beta1_predictor_config.py | Apache-2.0 |
def make_instance(self, include_optional):
"""Test V1beta1PredictorExtensionSpec
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included"""
# model = kserve.models.v1beta1_predictor_extension_spec.V1beta1... | Test V1beta1PredictorExtensionSpec
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | make_instance | python | kserve/kserve | python/kserve/test/test_v1beta1_predictor_extension_spec.py | https://github.com/kserve/kserve/blob/master/python/kserve/test/test_v1beta1_predictor_extension_spec.py | Apache-2.0 |
def make_instance(self, include_optional):
"""Test V1beta1PredictorProtocols
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included"""
# model = kserve.models.v1beta1_predictor_protocols.V1beta1Predictor... | Test V1beta1PredictorProtocols
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | make_instance | python | kserve/kserve | python/kserve/test/test_v1beta1_predictor_protocols.py | https://github.com/kserve/kserve/blob/master/python/kserve/test/test_v1beta1_predictor_protocols.py | Apache-2.0 |
def make_instance(self, include_optional):
"""Test V1beta1PredictorSpec
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included"""
# model = kserve.models.v1beta1_predictor_spec.V1beta1PredictorSpec() # ... | Test V1beta1PredictorSpec
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | make_instance | python | kserve/kserve | python/kserve/test/test_v1beta1_predictor_spec.py | https://github.com/kserve/kserve/blob/master/python/kserve/test/test_v1beta1_predictor_spec.py | Apache-2.0 |
def make_instance(self, include_optional):
"""Test V1beta1ResourceConfig
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included"""
# model = kserve.models.v1beta1_resource_config.V1beta1ResourceConfig() ... | Test V1beta1ResourceConfig
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | make_instance | python | kserve/kserve | python/kserve/test/test_v1beta1_resource_config.py | https://github.com/kserve/kserve/blob/master/python/kserve/test/test_v1beta1_resource_config.py | Apache-2.0 |
def make_instance(self, include_optional):
"""Test V1beta1ResourceMetricSource
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included"""
# model = kserve.models.v1beta1_resource_metric_source.V1beta1Reso... | Test V1beta1ResourceMetricSource
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | make_instance | python | kserve/kserve | python/kserve/test/test_v1beta1_resource_metric_source.py | https://github.com/kserve/kserve/blob/master/python/kserve/test/test_v1beta1_resource_metric_source.py | Apache-2.0 |
def make_instance(self, include_optional):
"""Test V1beta1ScalerSpec
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included"""
# model = kserve.models.v1beta1_scaler_spec.V1beta1ScalerSpec() # noqa: E50... | Test V1beta1ScalerSpec
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | make_instance | python | kserve/kserve | python/kserve/test/test_v1beta1_scaler_spec.py | https://github.com/kserve/kserve/blob/master/python/kserve/test/test_v1beta1_scaler_spec.py | Apache-2.0 |
def make_instance(self, include_optional):
"""Test V1beta1SecurityConfig
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included"""
# model = kserve.models.v1beta1_security_config.V1beta1SecurityConfig() ... | Test V1beta1SecurityConfig
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | make_instance | python | kserve/kserve | python/kserve/test/test_v1beta1_security_config.py | https://github.com/kserve/kserve/blob/master/python/kserve/test/test_v1beta1_security_config.py | Apache-2.0 |
def make_instance(self, include_optional):
"""Test V1beta1ServiceConfig
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included"""
# model = kserve.models.v1beta1_service_config.V1beta1ServiceConfig() # ... | Test V1beta1ServiceConfig
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | make_instance | python | kserve/kserve | python/kserve/test/test_v1beta1_service_config.py | https://github.com/kserve/kserve/blob/master/python/kserve/test/test_v1beta1_service_config.py | Apache-2.0 |
def make_instance(self, include_optional):
"""Test V1beta1SKLearnSpec
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included"""
# model = kserve.models.v1beta1_sk_learn_spec.V1beta1SKLearnSpec() # noqa:... | Test V1beta1SKLearnSpec
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | make_instance | python | kserve/kserve | python/kserve/test/test_v1beta1_sk_learn_spec.py | https://github.com/kserve/kserve/blob/master/python/kserve/test/test_v1beta1_sk_learn_spec.py | Apache-2.0 |
def make_instance(self, include_optional):
"""Test V1beta1StorageSpec
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included"""
# model = kserve.models.v1beta1_storage_spec.V1beta1StorageSpec() # noqa: ... | Test V1beta1StorageSpec
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | make_instance | python | kserve/kserve | python/kserve/test/test_v1beta1_storage_spec.py | https://github.com/kserve/kserve/blob/master/python/kserve/test/test_v1beta1_storage_spec.py | Apache-2.0 |
def make_instance(self, include_optional):
"""Test V1beta1TFServingSpec
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included"""
# model = kserve.models.v1beta1_tf_serving_spec.V1beta1TFServingSpec() #... | Test V1beta1TFServingSpec
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | make_instance | python | kserve/kserve | python/kserve/test/test_v1beta1_tf_serving_spec.py | https://github.com/kserve/kserve/blob/master/python/kserve/test/test_v1beta1_tf_serving_spec.py | Apache-2.0 |
def make_instance(self, include_optional):
"""Test V1beta1TorchServeSpec
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included"""
# model = kserve.models.v1beta1_torch_serve_spec.V1beta1TorchServeSpec()... | Test V1beta1TorchServeSpec
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | make_instance | python | kserve/kserve | python/kserve/test/test_v1beta1_torch_serve_spec.py | https://github.com/kserve/kserve/blob/master/python/kserve/test/test_v1beta1_torch_serve_spec.py | Apache-2.0 |
def make_instance(self, include_optional):
"""Test V1beta1TransformersConfig
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included"""
# model = kserve.models.v1beta1_transformers_config.V1beta1Transform... | Test V1beta1TransformersConfig
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | make_instance | python | kserve/kserve | python/kserve/test/test_v1beta1_transformers_config.py | https://github.com/kserve/kserve/blob/master/python/kserve/test/test_v1beta1_transformers_config.py | Apache-2.0 |
def make_instance(self, include_optional):
"""Test V1beta1TransformerConfig
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included"""
# model = kserve.models.v1beta1_transformer_config.V1beta1Transformer... | Test V1beta1TransformerConfig
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | make_instance | python | kserve/kserve | python/kserve/test/test_v1beta1_transformer_config.py | https://github.com/kserve/kserve/blob/master/python/kserve/test/test_v1beta1_transformer_config.py | Apache-2.0 |
def make_instance(self, include_optional):
"""Test V1beta1TransformerSpec
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included"""
# model = kserve.models.v1beta1_transformer_spec.V1beta1TransformerSpec... | Test V1beta1TransformerSpec
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | make_instance | python | kserve/kserve | python/kserve/test/test_v1beta1_transformer_spec.py | https://github.com/kserve/kserve/blob/master/python/kserve/test/test_v1beta1_transformer_spec.py | Apache-2.0 |
def make_instance(self, include_optional):
"""Test V1beta1TritonSpec
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included"""
# model = kserve.models.v1beta1_triton_spec.V1beta1TritonSpec() # noqa: E50... | Test V1beta1TritonSpec
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | make_instance | python | kserve/kserve | python/kserve/test/test_v1beta1_triton_spec.py | https://github.com/kserve/kserve/blob/master/python/kserve/test/test_v1beta1_triton_spec.py | Apache-2.0 |
def make_instance(self, include_optional):
"""Test V1beta1WorkerSpec
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included"""
# model = kserve.models.v1beta1_worker_spec.V1beta1WorkerSpec() # noqa: E50... | Test V1beta1WorkerSpec
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | make_instance | python | kserve/kserve | python/kserve/test/test_v1beta1_worker_spec.py | https://github.com/kserve/kserve/blob/master/python/kserve/test/test_v1beta1_worker_spec.py | Apache-2.0 |
def make_instance(self, include_optional):
"""Test V1beta1XGBoostSpec
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included"""
# model = kserve.models.v1beta1_xg_boost_spec.V1beta1XGBoostSpec() # noqa:... | Test V1beta1XGBoostSpec
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | make_instance | python | kserve/kserve | python/kserve/test/test_v1beta1_xg_boost_spec.py | https://github.com/kserve/kserve/blob/master/python/kserve/test/test_v1beta1_xg_boost_spec.py | Apache-2.0 |
def configure_logging(log_config: Optional[Union[Dict, str]] = None):
"""
Configures Storage Initializer
This function should be called before loading the model / starting the model
server for consistent logging format.
:param log_config: (Optional) File path or dict containing log config. If not p... |
Configures Storage Initializer
This function should be called before loading the model / starting the model
server for consistent logging format.
:param log_config: (Optional) File path or dict containing log config. If not provided default configuration
will be used. If explici... | configure_logging | python | kserve/kserve | python/storage/kserve_storage/logging.py | https://github.com/kserve/kserve/blob/master/python/storage/kserve_storage/logging.py | Apache-2.0 |
def Ping(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | Missing associated documentation comment in .proto file. | Ping | python | kserve/kserve | test/e2e/common/inference_pb2_grpc.py | https://github.com/kserve/kserve/blob/master/test/e2e/common/inference_pb2_grpc.py | Apache-2.0 |
def Predictions(self, request, context):
"""Predictions entry point to get inference using default model version.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | Predictions entry point to get inference using default model version.
| Predictions | python | kserve/kserve | test/e2e/common/inference_pb2_grpc.py | https://github.com/kserve/kserve/blob/master/test/e2e/common/inference_pb2_grpc.py | Apache-2.0 |
def _get_openai_endpoint_and_host(
service_name, url_suffix, version=constants.KSERVE_V1BETA1_VERSION
):
"""
Get the OpenAI endpoint for the given service name.
Args:
service_name: The name of the inference service
url_suffix: The suffix for the OpenAI endpoint (e.g., "v1/chat/completion... |
Get the OpenAI endpoint for the given service name.
Args:
service_name: The name of the inference service
url_suffix: The suffix for the OpenAI endpoint (e.g., "v1/chat/completions")
version: The version of the inference service. Defaults to v1beta1
Returns:
A tuple containi... | _get_openai_endpoint_and_host | python | kserve/kserve | test/e2e/common/utils.py | https://github.com/kserve/kserve/blob/master/test/e2e/common/utils.py | Apache-2.0 |
def chat_completion_stream(
service_name,
input_json,
version=constants.KSERVE_V1BETA1_VERSION,
):
"""
Make a chat completion streaming request to the inference service and collect all chunks.
Returns a tuple containing full response text and all chunks received.
"""
res = _openai_reques... |
Make a chat completion streaming request to the inference service and collect all chunks.
Returns a tuple containing full response text and all chunks received.
| chat_completion_stream | python | kserve/kserve | test/e2e/common/utils.py | https://github.com/kserve/kserve/blob/master/test/e2e/common/utils.py | Apache-2.0 |
def completion_stream(
service_name,
input_json,
version=constants.KSERVE_V1BETA1_VERSION,
):
"""
Make a streaming request to the text completion inference service and collect all chunks.
Returns a tuple containing full response text and all chunks received.
"""
res = _openai_request(
... |
Make a streaming request to the text completion inference service and collect all chunks.
Returns a tuple containing full response text and all chunks received.
| completion_stream | python | kserve/kserve | test/e2e/common/utils.py | https://github.com/kserve/kserve/blob/master/test/e2e/common/utils.py | Apache-2.0 |
def check_sa_exists(service_account):
"""Check if the specified service account existing."""
sa_list = client.CoreV1Api().list_namespaced_service_account(
namespace=KSERVE_TEST_NAMESPACE
)
sa_name_list = []
for item in range(0, len(sa_list.items) - 1):
sa_name_list.append(sa_list.ite... | Check if the specified service account existing. | check_sa_exists | python | kserve/kserve | test/e2e/credentials/test_set_creds.py | https://github.com/kserve/kserve/blob/master/test/e2e/credentials/test_set_creds.py | Apache-2.0 |
async def test_ig_scenario1(rest_v1_client):
"""
Scenario: Sequence graph with 2 steps that are both soft dependencies.
success_isvc(soft) -> error_isvc (soft)
We are not marking steps as soft or hard explicitly so this will test that default behavior of steps being soft
is as expected.
Expect... |
Scenario: Sequence graph with 2 steps that are both soft dependencies.
success_isvc(soft) -> error_isvc (soft)
We are not marking steps as soft or hard explicitly so this will test that default behavior of steps being soft
is as expected.
Expectation: IG will return response of error_isvc and pre... | test_ig_scenario1 | python | kserve/kserve | test/e2e/graph/test_inference_graph.py | https://github.com/kserve/kserve/blob/master/test/e2e/graph/test_inference_graph.py | Apache-2.0 |
async def test_ig_scenario2(rest_v1_client):
"""
Scenario: Sequence graph with 2 steps that are both soft dependencies.
error_isvc (soft) -> success_isvc(soft)
Expectation: IG will return response of success_isvc and predict_ig will not raise any exception
:return:
"""
logger.info("Star... |
Scenario: Sequence graph with 2 steps that are both soft dependencies.
error_isvc (soft) -> success_isvc(soft)
Expectation: IG will return response of success_isvc and predict_ig will not raise any exception
:return:
| test_ig_scenario2 | python | kserve/kserve | test/e2e/graph/test_inference_graph.py | https://github.com/kserve/kserve/blob/master/test/e2e/graph/test_inference_graph.py | Apache-2.0 |
async def test_ig_scenario3(rest_v1_client):
"""
Scenario: Sequence graph with 2 steps - first is hard (and returns non-200) and second is soft dependency.
error_isvc(hard) -> success_isvc (soft)
Expectation: IG will return response of error_isvc and predict_ig will raise exception
"""
logger... |
Scenario: Sequence graph with 2 steps - first is hard (and returns non-200) and second is soft dependency.
error_isvc(hard) -> success_isvc (soft)
Expectation: IG will return response of error_isvc and predict_ig will raise exception
| test_ig_scenario3 | python | kserve/kserve | test/e2e/graph/test_inference_graph.py | https://github.com/kserve/kserve/blob/master/test/e2e/graph/test_inference_graph.py | Apache-2.0 |
async def test_ig_scenario4(rest_v1_client):
"""
Scenario: Switch graph with 1 step as hard dependency and other one as soft dependency.
Will be testing 3 cases in this test case:
Expectation:
Case 1. IG will return response of error_isvc when condition for that step matches
Case 2. IG will retu... |
Scenario: Switch graph with 1 step as hard dependency and other one as soft dependency.
Will be testing 3 cases in this test case:
Expectation:
Case 1. IG will return response of error_isvc when condition for that step matches
Case 2. IG will return response of success_isvc when condition for that ... | test_ig_scenario4 | python | kserve/kserve | test/e2e/graph/test_inference_graph.py | https://github.com/kserve/kserve/blob/master/test/e2e/graph/test_inference_graph.py | Apache-2.0 |
async def test_ig_scenario5(rest_v1_client):
"""
Scenario: Switch graph where a match would happen for error node and then error would return but IG will continue
execution and call the next step in the flow as error step will be a soft dependency.
Expectation: IG will return response of success_isvc.
... |
Scenario: Switch graph where a match would happen for error node and then error would return but IG will continue
execution and call the next step in the flow as error step will be a soft dependency.
Expectation: IG will return response of success_isvc.
| test_ig_scenario5 | python | kserve/kserve | test/e2e/graph/test_inference_graph.py | https://github.com/kserve/kserve/blob/master/test/e2e/graph/test_inference_graph.py | Apache-2.0 |
async def test_ig_scenario6(rest_v1_client):
"""
Scenario: Switch graph where a match would happen for error node and then error would return and IG will NOT
continue execution and call the next step in the flow as error step will be a HARD dependency.
Expectation: IG will return response of success_isv... |
Scenario: Switch graph where a match would happen for error node and then error would return and IG will NOT
continue execution and call the next step in the flow as error step will be a HARD dependency.
Expectation: IG will return response of success_isvc.
| test_ig_scenario6 | python | kserve/kserve | test/e2e/graph/test_inference_graph.py | https://github.com/kserve/kserve/blob/master/test/e2e/graph/test_inference_graph.py | Apache-2.0 |
async def test_ig_scenario7(rest_v1_client):
"""
Scenario: Ensemble graph with 2 steps, where both the steps are soft deps.
Expectation: IG will return combined response of both the steps.
"""
logger.info("Starting test test_ig_scenario7")
suffix = str(uuid.uuid4())[1:6]
success_isvc_name, ... |
Scenario: Ensemble graph with 2 steps, where both the steps are soft deps.
Expectation: IG will return combined response of both the steps.
| test_ig_scenario7 | python | kserve/kserve | test/e2e/graph/test_inference_graph.py | https://github.com/kserve/kserve/blob/master/test/e2e/graph/test_inference_graph.py | Apache-2.0 |
async def test_ig_scenario8(rest_v1_client):
"""
Scenario: Ensemble graph with 3 steps, where 2 steps are soft and 1 step is hard and returns non-200
Expectation: Since HARD step will return non-200, so IG will return that step's output as IG's output
"""
logger.info("Starting test test_ig_scenario... |
Scenario: Ensemble graph with 3 steps, where 2 steps are soft and 1 step is hard and returns non-200
Expectation: Since HARD step will return non-200, so IG will return that step's output as IG's output
| test_ig_scenario8 | python | kserve/kserve | test/e2e/graph/test_inference_graph.py | https://github.com/kserve/kserve/blob/master/test/e2e/graph/test_inference_graph.py | Apache-2.0 |
async def test_ig_scenario9(rest_v1_client):
"""
Scenario: Splitter graph where a match would happen for error node and then error would return but IG will continue
execution and call the next step in the flow as error step will be a soft dependency.
Expectation: IG will return response of success_isvc.... |
Scenario: Splitter graph where a match would happen for error node and then error would return but IG will continue
execution and call the next step in the flow as error step will be a soft dependency.
Expectation: IG will return response of success_isvc.
| test_ig_scenario9 | python | kserve/kserve | test/e2e/graph/test_inference_graph.py | https://github.com/kserve/kserve/blob/master/test/e2e/graph/test_inference_graph.py | Apache-2.0 |
async def test_ig_scenario10(rest_v1_client):
"""
Scenario: Splitter graph where a match would happen for error node and then error would return and IG will NOT
continue execution and call the next step in the flow as error step will be a HARD dependency.
Expectation: IG will return response of success_... |
Scenario: Splitter graph where a match would happen for error node and then error would return and IG will NOT
continue execution and call the next step in the flow as error step will be a HARD dependency.
Expectation: IG will return response of success_isvc.
| test_ig_scenario10 | python | kserve/kserve | test/e2e/graph/test_inference_graph.py | https://github.com/kserve/kserve/blob/master/test/e2e/graph/test_inference_graph.py | Apache-2.0 |
async def test_sklearn_keda_scale_resource_memory(rest_v1_client, network_layer):
"""
Test KEDA autoscaling with new InferenceService (auto_scaling) spec
"""
service_name = "isvc-sklearn-keda-scale-new-spec"
predictor = V1beta1PredictorSpec(
min_replicas=1,
max_replicas=5,
au... |
Test KEDA autoscaling with new InferenceService (auto_scaling) spec
| test_sklearn_keda_scale_resource_memory | python | kserve/kserve | test/e2e/predictor/test_autoscaling.py | https://github.com/kserve/kserve/blob/master/test/e2e/predictor/test_autoscaling.py | Apache-2.0 |
async def test_scaling_sklearn_with_keda_otel_add_on(rest_v1_client, network_layer):
"""
Test KEDA-Otel-Add-On autoscaling with InferenceService (auto_scaling) spec
"""
service_name = "isvc-sklearn-keda-otel-add-on"
predictor = V1beta1PredictorSpec(
min_replicas=1,
max_replicas=5,
... |
Test KEDA-Otel-Add-On autoscaling with InferenceService (auto_scaling) spec
| test_scaling_sklearn_with_keda_otel_add_on | python | kserve/kserve | test/e2e/predictor/test_autoscaling.py | https://github.com/kserve/kserve/blob/master/test/e2e/predictor/test_autoscaling.py | Apache-2.0 |
def get_test_packages():
"""Returns list of packages needed when testing."""
test_packages = [
'mock >= 2.0.0',
'opencv-python >= 3.4.1.15',
'pybullet',
'scipy >= 1.1.0',
]
return test_packages | Returns list of packages needed when testing. | get_test_packages | python | tensorflow/agents | setup.py | https://github.com/tensorflow/agents/blob/master/setup.py | Apache-2.0 |
def get_reverb_packages():
"""Returns list of required packages if using reverb."""
reverb_packages = []
if FLAGS.release:
tf_version = TENSORFLOW_VERSION
reverb_version = REVERB_VERSION
rlds_version = RLDS_VERSION
else:
tf_version = TENSORFLOW_NIGHTLY
reverb_version = REVERB_NIGHTLY
rld... | Returns list of required packages if using reverb. | get_reverb_packages | python | tensorflow/agents | setup.py | https://github.com/tensorflow/agents/blob/master/setup.py | Apache-2.0 |
def get_version():
"""Returns the version and project name to associate with the build."""
__dev_version__ = tf_agents_version.__dev_version__ # pylint: disable=invalid-name
__rel_version__ = tf_agents_version.__rel_version__ # pylint: disable=invalid-name
if FLAGS.release:
version = __rel_version__
... | Returns the version and project name to associate with the build. | get_version | python | tensorflow/agents | setup.py | https://github.com/tensorflow/agents/blob/master/setup.py | Apache-2.0 |
def run_setup():
"""Triggers build, install, and other features of `setuptools.setup`."""
# Builds the long description from the README.
root_path = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(root_path, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
versi... | Triggers build, install, and other features of `setuptools.setup`. | run_setup | python | tensorflow/agents | setup.py | https://github.com/tensorflow/agents/blob/master/setup.py | Apache-2.0 |
def SetDisplayFromWebTest():
"""Set up display from web test.
Colab test sets up display using xvfb for front end web test suite. We just
ensure that DISPLAY environment variable is properly set for colab kernel
(backend) which can be used for open gym environment rendering.
"""
res = WaitForFilePath("/tm... | Set up display from web test.
Colab test sets up display using xvfb for front end web test suite. We just
ensure that DISPLAY environment variable is properly set for colab kernel
(backend) which can be used for open gym environment rendering.
| SetDisplayFromWebTest | python | tensorflow/agents | docs/tutorials/colab_kernel_init.py | https://github.com/tensorflow/agents/blob/master/docs/tutorials/colab_kernel_init.py | Apache-2.0 |
def _ensure_tf_install(): # pylint: disable=g-statement-before-imports
"""Attempt to import tensorflow, and ensure its version is sufficient.
Raises:
ImportError: if either tensorflow is not importable or its version is
inadequate.
"""
try:
import tensorflow as tf
except (ImportError, ModuleNotF... | Attempt to import tensorflow, and ensure its version is sufficient.
Raises:
ImportError: if either tensorflow is not importable or its version is
inadequate.
| _ensure_tf_install | python | tensorflow/agents | tf_agents/__init__.py | https://github.com/tensorflow/agents/blob/master/tf_agents/__init__.py | Apache-2.0 |
def _is_transition_like(value):
"""Helper to identify values that are transition like."""
if isinstance(value, trajectory.Transition):
return True
fields = getattr(value, '_fields', None)
if fields and trajectory.Transition._fields == fields:
return True
return False | Helper to identify values that are transition like. | _is_transition_like | python | tensorflow/agents | tf_agents/agents/data_converter.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/data_converter.py | Apache-2.0 |
def _is_trajectory_like(value):
"""Helper to identify values that are trajectory like."""
if isinstance(value, trajectory.Trajectory):
return True
fields = getattr(value, '_fields', None)
if fields and trajectory.Trajectory._fields == fields:
return True
return False | Helper to identify values that are trajectory like. | _is_trajectory_like | python | tensorflow/agents | tf_agents/agents/data_converter.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/data_converter.py | Apache-2.0 |
def _as_tfa_transition(value: typing.Tuple[typing.Any, typing.Any, typing.Any]):
"""Makes sure the transition and its values are TFA types."""
time_step, action_step, next_time_step = value
time_step = ts.TimeStep(*time_step)
action_step = policy_step.PolicyStep(*action_step)
next_time_step = ts.TimeStep(*nex... | Makes sure the transition and its values are TFA types. | _as_tfa_transition | python | tensorflow/agents | tf_agents/agents/data_converter.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/data_converter.py | Apache-2.0 |
def _validate_trajectory(
value: trajectory.Trajectory,
trajectory_spec: trajectory.Trajectory,
sequence_length: typing.Optional[int],
num_outer_dims: te.Literal[1, 2] = 2, # pylint: disable=bad-whitespace
):
"""Validate a Trajectory given its spec and a sequence length."""
if not nest_utils.is_bat... | Validate a Trajectory given its spec and a sequence length. | _validate_trajectory | python | tensorflow/agents | tf_agents/agents/data_converter.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/data_converter.py | Apache-2.0 |
def _validate_transition(
value: trajectory.Transition,
transition_spec: trajectory.Transition,
num_outer_dims: int,
):
"""Checks the given Transition for batch and time outer dimensions."""
if value.action_step.state:
# When state is not (), it does not have time dimension, therefore it needs
... | Checks the given Transition for batch and time outer dimensions. | _validate_transition | python | tensorflow/agents | tf_agents/agents/data_converter.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/data_converter.py | Apache-2.0 |
def __init__(
self,
data_context: DataContext,
sequence_length: typing.Optional[int] = None,
num_outer_dims: te.Literal[1, 2] = 2, # pylint: disable=bad-whitespace
):
"""Create the AsTrajectory converter.
Args:
data_context: An instance of `DataContext`, typically accessed from... | Create the AsTrajectory converter.
Args:
data_context: An instance of `DataContext`, typically accessed from the
`TFAgent.data_context` property.
sequence_length: The required time dimension value (if any), typically
determined by the subclass of `TFAgent`.
num_outer_dims: Expecte... | __init__ | python | tensorflow/agents | tf_agents/agents/data_converter.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/data_converter.py | Apache-2.0 |
def __call__(self, value: typing.Any) -> trajectory.Trajectory:
"""Convers `value` to a Trajectory. Performs data validation and pruning.
- If `value` is already a `Trajectory`, only validation is performed.
- If `value` is a `Transition` with tensors containing two (`[B, T]`)
outer dims, then it is ... | Convers `value` to a Trajectory. Performs data validation and pruning.
- If `value` is already a `Trajectory`, only validation is performed.
- If `value` is a `Transition` with tensors containing two (`[B, T]`)
outer dims, then it is simply repackaged to a `Trajectory` and then
validated.
- If ... | __call__ | python | tensorflow/agents | tf_agents/agents/data_converter.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/data_converter.py | Apache-2.0 |
def __call__(self, value: typing.Any) -> trajectory.Transition:
"""Converts `value` to a Transition. Performs data validation and pruning.
- If `value` is already a `Transition`, only validation is performed.
- If `value` is a `Trajectory` and `squeeze_time_dim = True` then
`value` it must have tenso... | Converts `value` to a Transition. Performs data validation and pruning.
- If `value` is already a `Transition`, only validation is performed.
- If `value` is a `Trajectory` and `squeeze_time_dim = True` then
`value` it must have tensors with shape `[B, T=2]` outer dims.
This is converted to a `Tran... | __call__ | python | tensorflow/agents | tf_agents/agents/data_converter.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/data_converter.py | Apache-2.0 |
def __call__(self, value: typing.Any) -> trajectory.Transition:
"""Convert `value` to an N-step Transition; validate data & prune.
- If `value` is already a `Transition`, only validation is performed.
- If `value` is a `Trajectory` with tensors containing a time dimension
having `T != n + 1`, a `Valu... | Convert `value` to an N-step Transition; validate data & prune.
- If `value` is already a `Transition`, only validation is performed.
- If `value` is a `Trajectory` with tensors containing a time dimension
having `T != n + 1`, a `ValueError` is raised.
Args:
value: A `Trajectory` or `Transitio... | __call__ | python | tensorflow/agents | tf_agents/agents/data_converter.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/data_converter.py | Apache-2.0 |
def __init__(
self,
data_context: DataContext,
gamma: types.Float,
n: typing.Optional[int] = None,
):
"""Create the AsNStepTransition converter.
For more details on how `Trajectory` objects are converted to N-step
`Transition` objects, see
`tf_agents.trajectories.trajectory.to... | Create the AsNStepTransition converter.
For more details on how `Trajectory` objects are converted to N-step
`Transition` objects, see
`tf_agents.trajectories.trajectory.to_n_step_transition`.
Args:
data_context: An instance of `DataContext`, typically accessed from the
`TFAgent.data_con... | __init__ | python | tensorflow/agents | tf_agents/agents/data_converter.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/data_converter.py | Apache-2.0 |
def test_loss_and_train_output(
test: test_utils.TestCase,
expect_equal_loss_values: bool,
agent: tf_agent.TFAgent,
experience: types.NestedTensor,
weights: Optional[types.Tensor] = None,
**kwargs
):
"""Tests that loss() and train() outputs are equivalent.
Checks that the outputs have the s... | Tests that loss() and train() outputs are equivalent.
Checks that the outputs have the same structures and shapes, and compares
loss values based on `expect_equal_loss_values`.
Args:
test: An instance of `test_utils.TestCase`.
expect_equal_loss_values: Whether to expect `LossInfo.loss` to have the same
... | test_loss_and_train_output | python | tensorflow/agents | tf_agents/agents/test_util.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/test_util.py | Apache-2.0 |
def __init__(
self,
time_step_spec: ts.TimeStep,
action_spec: types.NestedTensorSpec,
policy: tf_policy.TFPolicy,
collect_policy: tf_policy.TFPolicy,
train_sequence_length: Optional[int],
num_outer_dims: int = 2,
training_data_spec: Optional[types.NestedTensorSpec] = None... | Meant to be called by subclass constructors.
Args:
time_step_spec: A nest of tf.TypeSpec representing the time_steps.
Provided by the user.
action_spec: A nest of BoundedTensorSpec representing the actions.
Provided by the user.
policy: An instance of `tf_policy.TFPolicy` represen... | __init__ | python | tensorflow/agents | tf_agents/agents/tf_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/tf_agent.py | Apache-2.0 |
def initialize(self) -> Optional[tf.Operation]:
"""Initializes the agent.
Returns:
An operation that can be used to initialize the agent.
Raises:
RuntimeError: If the class was not initialized properly (`super.__init__`
was not called).
"""
if self._enable_functions and getattr... | Initializes the agent.
Returns:
An operation that can be used to initialize the agent.
Raises:
RuntimeError: If the class was not initialized properly (`super.__init__`
was not called).
| initialize | python | tensorflow/agents | tf_agents/agents/tf_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/tf_agent.py | Apache-2.0 |
def preprocess_sequence(
self, experience: types.NestedTensor
) -> types.NestedTensor:
"""Defines preprocess_sequence function to be fed into replay buffers.
This defines how we preprocess the collected data before training.
Defaults to pass through for most agents.
Structure of `experience` mu... | Defines preprocess_sequence function to be fed into replay buffers.
This defines how we preprocess the collected data before training.
Defaults to pass through for most agents.
Structure of `experience` must match that of `self.collect_data_spec`.
Args:
experience: a `Trajectory` shaped [batch, ... | preprocess_sequence | python | tensorflow/agents | tf_agents/agents/tf_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/tf_agent.py | Apache-2.0 |
def train(
self,
experience: types.NestedTensor,
weights: Optional[types.Tensor] = None,
**kwargs
) -> LossInfo:
"""Trains the agent.
Args:
experience: A batch of experience data in the form of a `Trajectory`. The
structure of `experience` must match that of `self.traini... | Trains the agent.
Args:
experience: A batch of experience data in the form of a `Trajectory`. The
structure of `experience` must match that of `self.training_data_spec`.
All tensors in `experience` must be shaped `[batch, time, ...]` where
`time` must be equal to `self.train_step_leng... | train | python | tensorflow/agents | tf_agents/agents/tf_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/tf_agent.py | Apache-2.0 |
def loss(
self,
experience: types.NestedTensor,
weights: Optional[types.Tensor] = None,
training: bool = False,
**kwargs
) -> LossInfo:
"""Gets loss from the agent.
If the user calls this from _train, it must be in a `tf.GradientTape` scope
in order to apply gradients to tra... | Gets loss from the agent.
If the user calls this from _train, it must be in a `tf.GradientTape` scope
in order to apply gradients to trainable variables.
If intermediate gradient steps are needed, _loss and _train will return
different values since _loss only supports updating all gradients at once
... | loss | python | tensorflow/agents | tf_agents/agents/tf_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/tf_agent.py | Apache-2.0 |
def training_data_spec(self) -> types.NestedTensorSpec:
"""Returns a trajectory spec, as expected by the train() function."""
if self._training_data_spec is not None:
return self._training_data_spec
else:
return self.collect_data_spec | Returns a trajectory spec, as expected by the train() function. | training_data_spec | python | tensorflow/agents | tf_agents/agents/tf_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/tf_agent.py | Apache-2.0 |
def _preprocess_sequence(
self, experience: types.NestedTensor
) -> types.NestedTensor:
"""Defines preprocess_sequence function to be fed into replay buffers.
This defines how we preprocess the collected data before training.
Defaults to pass through for most agents. Subclasses may override this.
... | Defines preprocess_sequence function to be fed into replay buffers.
This defines how we preprocess the collected data before training.
Defaults to pass through for most agents. Subclasses may override this.
Args:
experience: a `Trajectory` shaped [batch, time, ...] or [time, ...] which
repre... | _preprocess_sequence | python | tensorflow/agents | tf_agents/agents/tf_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/tf_agent.py | Apache-2.0 |
def _loss(
self,
experience: types.NestedTensor,
weights: types.Tensor,
training: bool,
**kwargs
) -> Optional[LossInfo]:
"""Computes loss.
This method does not increment self.train_step_counter or upgrade gradients.
By default, any networks are called with `training=False`.... | Computes loss.
This method does not increment self.train_step_counter or upgrade gradients.
By default, any networks are called with `training=False`.
Args:
experience: A batch of experience data in the form of a `Trajectory`. The
structure of `experience` must match that of `self.training_d... | _loss | python | tensorflow/agents | tf_agents/agents/tf_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/tf_agent.py | Apache-2.0 |
def _train(
self, experience: types.NestedTensor, weights: types.Tensor
) -> LossInfo:
"""Returns an op to train the agent.
This method *must* increment self.train_step_counter exactly once.
TODO(b/126271669): Consider automatically incrementing this.
Args:
experience: A batch of experie... | Returns an op to train the agent.
This method *must* increment self.train_step_counter exactly once.
TODO(b/126271669): Consider automatically incrementing this.
Args:
experience: A batch of experience data in the form of a `Trajectory`. The
structure of `experience` must match that of `self... | _train | python | tensorflow/agents | tf_agents/agents/tf_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/tf_agent.py | Apache-2.0 |
def __init__(
self,
time_step_spec: ts.TimeStep,
action_spec: types.NestedTensorSpec,
cloning_network: network.Network,
optimizer: types.Optimizer,
num_outer_dims: Literal[1, 2] = 1, # pylint: disable=bad-whitespace
epsilon_greedy: types.Float = 0.1,
loss_fn: Optional[
... | Creates an instance of a Behavioral Cloning agent.
Args:
time_step_spec: A `TimeStep` spec of the expected time_steps.
action_spec: A nest of BoundedTensorSpec representing the actions.
cloning_network: A `tf_agents.networks.Network` to be used by the agent.
The network will be called as ... | __init__ | python | tensorflow/agents | tf_agents/agents/behavioral_cloning/behavioral_cloning_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/behavioral_cloning/behavioral_cloning_agent.py | Apache-2.0 |
def create_arbitrary_trajectory():
"""Creates an arbitrary trajectory for unit testing BehavioralCloningAgent.
This trajectory contains Tensors shaped `[6, 1, ...]` where `6` is the number
of time steps and `1` is the batch.
Observations are unbounded but actions are bounded to take values within
`[1, 2]`. ... | Creates an arbitrary trajectory for unit testing BehavioralCloningAgent.
This trajectory contains Tensors shaped `[6, 1, ...]` where `6` is the number
of time steps and `1` is the batch.
Observations are unbounded but actions are bounded to take values within
`[1, 2]`. The action space is discrete.
Policy ... | create_arbitrary_trajectory | python | tensorflow/agents | tf_agents/agents/behavioral_cloning/behavioral_cloning_agent_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/behavioral_cloning/behavioral_cloning_agent_test.py | Apache-2.0 |
def verifyTrainAndRestore(
self, observation_spec, action_spec, actor_net, loss_fn=None
):
"""Helper function for testing correct variable updating and restoring."""
batch_size = 2
observations = tensor_spec.sample_spec_nest(
observation_spec, outer_dims=(batch_size,)
)
actions = ten... | Helper function for testing correct variable updating and restoring. | verifyTrainAndRestore | python | tensorflow/agents | tf_agents/agents/behavioral_cloning/behavioral_cloning_agent_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/behavioral_cloning/behavioral_cloning_agent_test.py | Apache-2.0 |
def __init__(
self,
time_step_spec: ts.TimeStep,
action_spec: types.NestedTensorSpec,
categorical_q_network: network.Network,
optimizer: types.Optimizer,
observation_and_action_constraint_splitter: Optional[
types.Splitter
] = None,
min_q_value: types.Float = -1... | Creates a Categorical DQN Agent.
Args:
time_step_spec: A `TimeStep` spec of the expected time_steps.
action_spec: A `BoundedTensorSpec` representing the actions.
categorical_q_network: A categorical_q_network.CategoricalQNetwork that
returns the q_distribution for each action.
optim... | __init__ | python | tensorflow/agents | tf_agents/agents/categorical_dqn/categorical_dqn_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/categorical_dqn/categorical_dqn_agent.py | Apache-2.0 |
def _loss(
self,
experience,
td_errors_loss_fn=tf.compat.v1.losses.huber_loss,
gamma=1.0,
reward_scale_factor=1.0,
weights=None,
training=False,
):
"""Computes critic loss for CategoricalDQN training.
See Algorithm 1 and the discussion immediately preceding it in pag... | Computes critic loss for CategoricalDQN training.
See Algorithm 1 and the discussion immediately preceding it in page 6 of
"A Distributional Perspective on Reinforcement Learning"
Bellemare et al., 2017
https://arxiv.org/abs/1707.06887
Args:
experience: A batch of experience data in the ... | _loss | python | tensorflow/agents | tf_agents/agents/categorical_dqn/categorical_dqn_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/categorical_dqn/categorical_dqn_agent.py | Apache-2.0 |
def _next_q_distribution(self, next_time_steps):
"""Compute the q distribution of the next state for TD error computation.
Args:
next_time_steps: A batch of next timesteps
Returns:
A [batch_size, num_atoms] tensor representing the Q-distribution for the
next state.
"""
network_ob... | Compute the q distribution of the next state for TD error computation.
Args:
next_time_steps: A batch of next timesteps
Returns:
A [batch_size, num_atoms] tensor representing the Q-distribution for the
next state.
| _next_q_distribution | python | tensorflow/agents | tf_agents/agents/categorical_dqn/categorical_dqn_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/categorical_dqn/categorical_dqn_agent.py | Apache-2.0 |
def project_distribution(
supports: types.Tensor,
weights: types.Tensor,
target_support: types.Tensor,
validate_args: bool = False,
) -> types.Tensor:
"""Projects a batch of (support, weights) onto target_support.
Based on equation (7) in (Bellemare et al., 2017):
https://arxiv.org/abs/1707.068... | Projects a batch of (support, weights) onto target_support.
Based on equation (7) in (Bellemare et al., 2017):
https://arxiv.org/abs/1707.06887
In the rest of the comments we will refer to this equation simply as Eq7.
This code is not easy to digest, so we will use a running example to clarify
what is goi... | project_distribution | python | tensorflow/agents | tf_agents/agents/categorical_dqn/categorical_dqn_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/categorical_dqn/categorical_dqn_agent.py | Apache-2.0 |
def __init__(
self,
root_dir,
env_name,
num_iterations=200,
max_episode_frames=108000, # ALE frames
terminal_on_life_loss=False,
conv_layer_params=((32, (8, 8), 4), (64, (4, 4), 2), (64, (3, 3), 1)),
fc_layer_params=(512,),
# Params for collect
initial_collec... | A simple Atari train and eval for DQN.
Args:
root_dir: Directory to write log files to.
env_name: Fully-qualified name of the Atari environment (i.e. Pong-v0).
num_iterations: Number of train/eval iterations to run.
max_episode_frames: Maximum length of a single episode, in ALE frames.
... | __init__ | python | tensorflow/agents | tf_agents/agents/categorical_dqn/examples/train_eval_atari.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/categorical_dqn/examples/train_eval_atari.py | Apache-2.0 |
def _initial_collect(self):
"""Collect initial experience before training begins."""
logging.info('Collecting initial experience...')
time_step_spec = ts.time_step_spec(self._env.observation_spec())
random_policy = random_py_policy.RandomPyPolicy(
time_step_spec, self._env.action_spec()
)
... | Collect initial experience before training begins. | _initial_collect | python | tensorflow/agents | tf_agents/agents/categorical_dqn/examples/train_eval_atari.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/categorical_dqn/examples/train_eval_atari.py | Apache-2.0 |
def _collect_step(self, time_step, metric_observers, train=False):
"""Run a single step (or 2 steps on life loss) in the environment."""
if train:
policy = self._collect_policy
else:
policy = self._eval_policy
with self._action_timer:
action_step = policy.action(time_step)
with se... | Run a single step (or 2 steps on life loss) in the environment. | _collect_step | python | tensorflow/agents | tf_agents/agents/categorical_dqn/examples/train_eval_atari.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/categorical_dqn/examples/train_eval_atari.py | Apache-2.0 |
def _maybe_log(self, sess, global_step_val, total_loss):
"""Log some stats if global_step_val is a multiple of log_interval."""
if global_step_val % self._log_interval == 0:
logging.info('step = %d, loss = %f', global_step_val, total_loss.loss)
logging.info('%s', 'action_time = {}'.format(self._acti... | Log some stats if global_step_val is a multiple of log_interval. | _maybe_log | python | tensorflow/agents | tf_agents/agents/categorical_dqn/examples/train_eval_atari.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/categorical_dqn/examples/train_eval_atari.py | Apache-2.0 |
def get_run_args():
"""Builds a dict of run arguments from flags."""
run_args = {}
if FLAGS.num_iterations:
run_args['num_iterations'] = FLAGS.num_iterations
if FLAGS.initial_collect_steps:
run_args['initial_collect_steps'] = FLAGS.initial_collect_steps
if FLAGS.replay_buffer_capacity:
run_args['r... | Builds a dict of run arguments from flags. | get_run_args | python | tensorflow/agents | tf_agents/agents/categorical_dqn/examples/train_eval_atari.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/categorical_dqn/examples/train_eval_atari.py | Apache-2.0 |
def __init__(
self,
time_step_spec: ts.TimeStep,
action_spec: types.NestedTensorSpec,
critic_network: network.Network,
actor_network: network.Network,
actor_optimizer: types.Optimizer,
critic_optimizer: types.Optimizer,
alpha_optimizer: types.Optimizer,
cql_alpha: U... | Creates a CQL-SAC Agent.
Args:
time_step_spec: A `TimeStep` spec of the expected time_steps.
action_spec: A nest of BoundedTensorSpec representing the actions.
critic_network: A function critic_network((observations, actions)) that
returns the q_values for each observation and action.
... | __init__ | python | tensorflow/agents | tf_agents/agents/cql/cql_sac_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/cql/cql_sac_agent.py | Apache-2.0 |
def _train(self, experience, weights):
"""Returns a train op to update the agent's networks.
This method trains with the provided batched experience.
Args:
experience: A time-stacked trajectory object.
weights: Optional scalar or elementwise (per-batch-entry) importance
weights.
R... | Returns a train op to update the agent's networks.
This method trains with the provided batched experience.
Args:
experience: A time-stacked trajectory object.
weights: Optional scalar or elementwise (per-batch-entry) importance
weights.
Returns:
A train_op.
Raises:
V... | _train | python | tensorflow/agents | tf_agents/agents/cql/cql_sac_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/cql/cql_sac_agent.py | Apache-2.0 |
def _transpose_tile_and_batch_dims(
self, original_tensor: types.Tensor
) -> types.Tensor:
"""Transposes [tile, batch, ...] to [batch, tile, ...]."""
return tf.transpose(
original_tensor, [1, 0] + list(range(2, len(original_tensor.shape)))
) | Transposes [tile, batch, ...] to [batch, tile, ...]. | _transpose_tile_and_batch_dims | python | tensorflow/agents | tf_agents/agents/cql/cql_sac_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/cql/cql_sac_agent.py | Apache-2.0 |
def _actions_and_log_probs(
self, time_steps: ts.TimeStep, training: Optional[bool] = False
) -> Tuple[types.Tensor, types.Tensor]:
"""Get actions and corresponding log probabilities from policy."""
# Get raw action distribution from policy, and initialize bijectors list.
batch_size = nest_utils.get... | Get actions and corresponding log probabilities from policy. | _actions_and_log_probs | python | tensorflow/agents | tf_agents/agents/cql/cql_sac_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/cql/cql_sac_agent.py | Apache-2.0 |
def _sample_and_transpose_actions_and_log_probs(
self,
time_steps: ts.TimeStep,
num_action_samples: int,
training: Optional[bool] = False,
) -> Tuple[types.Tensor, types.Tensor]:
"""Samples actions and corresponding log probabilities from policy."""
# Get raw action distribution from p... | Samples actions and corresponding log probabilities from policy. | _sample_and_transpose_actions_and_log_probs | python | tensorflow/agents | tf_agents/agents/cql/cql_sac_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/cql/cql_sac_agent.py | Apache-2.0 |
def _flattened_multibatch_tensor(
self, original_tensor: types.Tensor
) -> types.Tensor:
"""Flattens the batch and tile dimensions into a single dimension.
Args:
original_tensor: Input tensor of shape [batch_size, tile, dim].
Returns:
Flattened tensor with the outer dimension (batch_si... | Flattens the batch and tile dimensions into a single dimension.
Args:
original_tensor: Input tensor of shape [batch_size, tile, dim].
Returns:
Flattened tensor with the outer dimension (batch_size * tile).
| _flattened_multibatch_tensor | python | tensorflow/agents | tf_agents/agents/cql/cql_sac_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/cql/cql_sac_agent.py | Apache-2.0 |
def _get_q_values(
self,
target_input: Tuple[types.Tensor, types.Tensor],
step_type: types.Tensor,
reshape_batch_size: Optional[int],
training: Optional[bool] = False,
) -> Tuple[types.Tensor, types.Tensor]:
"""Gets the Q-values of target_input.
Uses the smaller of the critic ne... | Gets the Q-values of target_input.
Uses the smaller of the critic network outputs since learned Q functions
can overestimate Q-values.
Args:
target_input: Tuple of (observation, sampled actions) tensors.
step_type: `Tensor` of `StepType` enum values.
reshape_batch_size: Batch size to res... | _get_q_values | python | tensorflow/agents | tf_agents/agents/cql/cql_sac_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/cql/cql_sac_agent.py | Apache-2.0 |
def _cql_loss(
self,
time_steps: ts.TimeStep,
actions: types.Tensor,
training: Optional[bool] = False,
) -> types.Tensor:
"""Computes CQL loss for SAC training in continuous action spaces.
Extends the standard critic loss to minimize Q-values sampled from a policy
and maximize val... | Computes CQL loss for SAC training in continuous action spaces.
Extends the standard critic loss to minimize Q-values sampled from a policy
and maximize values of the dataset actions.
Based on the `CQL(H)` equation (4) in (Kumar et al., 2020):
```
log_sum_exp(Q(s, a')) - Q(s, a)
```
Othe... | _cql_loss | python | tensorflow/agents | tf_agents/agents/cql/cql_sac_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/cql/cql_sac_agent.py | Apache-2.0 |
def actor_loss(
self,
time_steps: ts.TimeStep,
actions: types.Tensor,
weights: Optional[types.Tensor] = None,
training: Optional[bool] = True,
) -> types.Tensor:
"""Computes actor_loss equivalent to the SAC actor_loss.
Uses behavioral cloning for the first `self._num_bc_steps` o... | Computes actor_loss equivalent to the SAC actor_loss.
Uses behavioral cloning for the first `self._num_bc_steps` of training.
Args:
time_steps: A batch of timesteps.
actions: A batch of actions.
weights: Optional scalar or elementwise (per-batch-entry) importance
weights.
train... | actor_loss | python | tensorflow/agents | tf_agents/agents/cql/cql_sac_agent.py | https://github.com/tensorflow/agents/blob/master/tf_agents/agents/cql/cql_sac_agent.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.