python_code
stringlengths
0
108k
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from bitsandbytes.optim.optimizer import Optimizer1State class SGD(Optimizer1State): def __init__(self, params, lr, momentum=0, dampe...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch from torch.optim import Optimizer from bitsandbytes.optim.optimizer import Optimizer1State class LARS(Optimizer1State): ...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from .adam import Adam, Adam8bit, Adam32bit from .adamw import AdamW, AdamW8bit, AdamW32bit from .sgd import SGD, SGD8bit, SGD32bit from ....
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch from bitsandbytes.optim.optimizer import Optimizer1State torch.optim.Adagrad class Adagrad(Optimizer1State): def __init...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch from bitsandbytes.optim.optimizer import Optimizer2State import bitsandbytes.functional as F class AdamW(Optimizer2State): ...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import math import os import torch import torch.distributed as dist from bitsandbytes.optim.optimizer import Optimizer2State import bits...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch import bitsandbytes.functional as F from copy import deepcopy from itertools import chain from collections import defaultdic...
import setuptools if __name__ == "__main__": setuptools.setup()
import os import pytest import bentoml from bentoml._internal.models import ModelStore from bentoml._internal.models import ModelContext TEST_MODEL_CONTEXT = ModelContext( framework_name="testing", framework_versions={"testing": "v1"} ) @pytest.fixture(scope="function", name="change_test_dir") def fixture_chan...
import os import random import string from sys import version_info as pyver from typing import TYPE_CHECKING try: import importlib.metadata as importlib_metadata except ModuleNotFoundError: import importlib_metadata import pytest import bentoml from bentoml.exceptions import NotFound from bentoml._internal.m...
from datetime import date from datetime import datetime from datetime import timedelta import numpy as np import pandas as pd import pytest from scipy.sparse import csr_matrix import bentoml._internal.utils as utils from bentoml._internal.types import MetadataDict def test_validate_labels(): inp = {"label1": "l...
import os import sys import typing as t from typing import TYPE_CHECKING from datetime import datetime import fs import attr import pytest from bentoml import Tag from bentoml.exceptions import NotFound from bentoml.exceptions import BentoMLException from bentoml._internal.store import Store from bentoml._internal.st...
import numpy as np import pandas as pd import pytest import bentoml._internal.runner.container as c @pytest.mark.parametrize("batch_dim_exc", [AssertionError]) @pytest.mark.parametrize("wrong_batch_dim", [1, 19]) def test_default_container(batch_dim_exc, wrong_batch_dim): l1 = [1, 2, 3] l2 = [3, 4, 5, 6] ...
import numpy as np from bentoml._internal.types import LazyType def test_typeref(): # assert __eq__ assert LazyType("numpy", "ndarray") == np.ndarray assert LazyType("numpy", "ndarray") == LazyType(type(np.array([2, 3]))) # evaluate assert LazyType("numpy", "ndarray").get_class() == np.ndarray
import typing as t import numpy as np import pytest import pydantic from bentoml.io import File from bentoml.io import JSON from bentoml.io import Text from bentoml.io import Image from bentoml.io import Multipart from bentoml.io import NumpyNdarray from bentoml.io import PandasDataFrame class _Schema(pydantic.Base...
import json import typing as t from dataclasses import dataclass import numpy as np import pytest import pydantic @dataclass class _ExampleSchema: name: str endpoints: t.List[str] class _Schema(pydantic.BaseModel): name: str endpoints: t.List[str] test_arr = t.cast("np.ndarray[t.Any, np.dtype[np....
from unittest.mock import patch from schema import Or from schema import And from schema import Schema import bentoml._internal.utils.analytics as analytics_lib SCHEMA = Schema( { "common_properties": { "timestamp": str, "bentoml_version": str, "client": {"creation_tim...
import os import typing as t import psutil import pytest WINDOWS_PATHS = [ r"C:\foo\bar", r"C:\foo\bar with space", r"C:\\foo\\中文", r"relative\path", # r"\\localhost\c$\WINDOWS\network", # r"\\networkstorage\homes\user", ] POSIX_PATHS = ["/foo/bar", "/foo/bar with space", "/foo/中文", "relative/...
from __future__ import annotations import os from sys import version_info as pyver from typing import TYPE_CHECKING from datetime import datetime from datetime import timezone import fs import attr import numpy as np import pytest import fs.errors from bentoml import Tag from bentoml.exceptions import BentoMLExcepti...
from __future__ import annotations import os from sys import version_info from typing import TYPE_CHECKING from datetime import datetime from datetime import timezone import fs import pytest from bentoml import Tag from bentoml._internal.bento import Bento from bentoml._internal.models import ModelStore from bentoml...
import bentoml # import bentoml.sklearn # from bentoml.io import NumpyNdarray # iris_model_runner = bentoml.sklearn.load_runner('iris_classifier:latest') svc = bentoml.Service( "test.simplebento", # runners=[iris_model_runner] ) # @svc.api(input=NumpyNdarray(), output=NumpyNdarray()) # def predict(request_da...
import bentoml svc = bentoml.Service("test.bentoa")
import bentoml svc = bentoml.Service("test.bentob")
import bentoml svc = bentoml.Service("test.bentoa")
import typing as t import tempfile from typing import TYPE_CHECKING import pytest from bentoml._internal.models import ModelStore if TYPE_CHECKING: from _pytest.nodes import Item from _pytest.config import Config from _pytest.config.argparsing import Parser def pytest_addoption(parser: "Parser") -> Non...
from __future__ import annotations import typing as t from typing import TYPE_CHECKING import numpy as np import pytest import bentoml from tests.utils.helpers import assert_have_file_extension from tests.utils.frameworks.tensorflow_utils import CustomLayer from tests.utils.frameworks.tensorflow_utils import custom_...
import pandas as pd import pytest import pyspark.ml from pyspark.sql import SparkSession from pyspark.ml.feature import VectorAssembler from pyspark.ml.classification import LogisticRegression from bentoml.pyspark import PySparkMLlibModel from bentoml.pyspark import SPARK_SESSION_NAMESPACE spark_session = SparkSessio...
from __future__ import annotations import os import pkgutil from types import ModuleType from importlib import import_module import pytest from .models import FrameworkTestModel def pytest_addoption(parser: pytest.Parser): parser.addoption("--framework", action="store", default=None) def pytest_generate_test...
from __future__ import annotations import types import typing as t import pytest import bentoml from bentoml.exceptions import NotFound from bentoml._internal.models.model import ModelContext from bentoml._internal.models.model import ModelSignature from bentoml._internal.runner.runner import Runner from bentoml._in...
import typing as t from typing import TYPE_CHECKING import pytest import requests import transformers import transformers.pipelines from PIL import Image from transformers.trainer_utils import set_seed import bentoml if TYPE_CHECKING: from bentoml._internal.external_typing import transformers as ext set_seed(1...
import os import typing as t import tempfile import contextlib import fasttext from bentoml.fasttext import FastTextModel test_json: t.Dict[str, str] = {"text": "foo"} @contextlib.contextmanager def _temp_filename_with_content(contents: t.Any) -> t.Generator[str, None, None]: temp_file = tempfile.NamedTemporar...
import typing as t from typing import TYPE_CHECKING import numpy as np import pytest import bentoml import bentoml.models if TYPE_CHECKING: from bentoml._internal.store import Tag class MyCoolModel: def predict(self, some_integer: int): return some_integer**2 def batch_predict(self, some_integ...
import typing as t from typing import TYPE_CHECKING import numpy as np import pytest from sklearn.ensemble import RandomForestClassifier import bentoml import bentoml.models from tests.utils.helpers import assert_have_file_extension from tests.utils.frameworks.sklearn_utils import sklearn_model_data # fmt: off res_a...
import numpy as np import pandas as pd from fastai.learner import Learner from fastai.data.block import DataBlock from fastai.torch_core import Module from bentoml.fastai import FastAIModel from tests.utils.helpers import assert_have_file_extension from tests.utils.frameworks.pytorch_utils import test_df from tests.ut...
# import math import numpy as np import torch import pytest import torch.nn as nn import bentoml from tests.utils.helpers import assert_have_file_extension from bentoml._internal.runner.container import AutoContainer from bentoml._internal.frameworks.pytorch import PyTorchTensorContainer # from tests.utils.framework...
import os import numpy as np import torch import pytest import torch.nn as nn import bentoml from tests.utils.helpers import assert_have_file_extension from tests.utils.frameworks.pytorch_utils import test_df from tests.utils.frameworks.pytorch_utils import predict_df from tests.utils.frameworks.pytorch_utils import ...
from __future__ import annotations from typing import TYPE_CHECKING import numpy as np import pytest import tensorflow as tf import bentoml from tests.utils.helpers import assert_have_file_extension from tests.utils.frameworks.tensorflow_utils import NativeModel from tests.utils.frameworks.tensorflow_utils import Mu...
import evalml import pandas as pd import pytest from bentoml.evalml import EvalMLModel from tests.utils.helpers import assert_have_file_extension test_df = pd.DataFrame([[42, "b"]]) @pytest.fixture(scope="session") def binary_pipeline() -> "evalml.pipelines.BinaryClassificationPipeline": X = pd.DataFrame([[0, "...
import os from pathlib import Path import numpy as np import psutil import pytest import mlflow.sklearn import bentoml from bentoml.exceptions import BentoMLException from tests.utils.helpers import assert_have_file_extension from tests.utils.frameworks.sklearn_utils import sklearn_model_data current_file = Path(__f...
# # Trains an SimpleMNIST digit recognizer using PyTorch Lightning, # and uses Mlflow to log metrics, params and artifacts # NOTE: This example requires you to first install # pytorch-lightning (using pip install pytorch-lightning) # and mlflow (using pip install mlflow). # # pylint: disable=arguments-differ # py...
# # Trains an SimpleMNIST digit recognizer using PyTorch Lightning, # and uses Mlflow to log metrics, params and artifacts # NOTE: This example requires you to first install # pytorch-lightning (using pip install pytorch-lightning) # and mlflow (using pip install mlflow). # # pylint: disable=arguments-differ # py...
from __future__ import annotations import numpy as np import pandas as pd import lightgbm as lgb from sklearn.datasets import load_breast_cancer import bentoml from . import FrameworkTestModel from . import FrameworkTestModelInput as Input from . import FrameworkTestModelConfiguration as Config framework = bentoml....
from __future__ import annotations import typing as t import attr from bentoml._internal.runner.resource import Resource @attr.define class FrameworkTestModel: name: str model: t.Any configurations: list[FrameworkTestModelConfiguration] save_kwargs: dict[str, t.Any] = attr.Factory(dict) @attr.de...
from __future__ import annotations import json import numpy as np import pandas as pd import xgboost as xgb from sklearn.datasets import load_breast_cancer import bentoml from bentoml._internal.runner.resource import Resource from . import FrameworkTestModel from . import FrameworkTestModelInput as Input from . imp...
from pathlib import Path def assert_have_file_extension(directory: str, ext: str): _dir = Path(directory) assert _dir.is_dir(), f"{directory} is not a directory" assert any(f.suffix == ext for f in _dir.iterdir())
import numpy as np import torch import pandas as pd import torch.nn as nn test_df = pd.DataFrame([[1] * 5]) class LinearModel(nn.Module): def __init__(self): super().__init__() self.linear = nn.Linear(5, 1, bias=False) torch.nn.init.ones_(self.linear.weight) def forward(self, x): ...
# ============================================================================== # Copyright (c) 2021 Atalaya Tech. Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # ...
import re import string import numpy as np import tensorflow as tf import tensorflow.keras as keras def custom_activation(x): return tf.nn.tanh(x) ** 2 class CustomLayer(keras.layers.Layer): def __init__(self, units=32, **kwargs): super(CustomLayer, self).__init__(**kwargs) self.units = tf....
from collections import namedtuple import pandas as pd from sklearn.datasets import load_iris from sklearn.neighbors import KNeighborsClassifier test_data = { "mean radius": 10.80, "mean texture": 21.98, "mean perimeter": 68.79, "mean area": 359.9, "mean smoothness": 0.08801, "mean compactness...
import paddle import pandas as pd import paddle.nn as nn from paddle.static import InputSpec IN_FEATURES = 13 OUT_FEATURES = 1 test_df = pd.DataFrame( [ [ -0.0405441, 0.06636364, -0.32356227, -0.06916996, -0.03435197, 0.05563625, ...
import typing as t import numpy as np import pandas as pd import pydantic from PIL.Image import Image as PILImage from PIL.Image import fromarray import bentoml import bentoml.picklable_model from bentoml.io import File from bentoml.io import JSON from bentoml.io import Image from bentoml.io import Multipart from ben...
from pickle_model import PickleModel import bentoml.picklable_model def train(): bentoml.picklable_model.save_model( "py_model.case-1.e2e", PickleModel(), signatures={ "predict_file": {"batchable": True}, "echo_json": {"batchable": True}, "echo_obj": {"...
import typing as t import numpy as np import pandas as pd from bentoml._internal.types import FileLike from bentoml._internal.types import JSONSerializable class PickleModel: def predict_file(self, input_files: t.List[FileLike[bytes]]) -> t.List[bytes]: return [f.read() for f in input_files] @class...
# type: ignore[no-untyped-def] import os import typing as t import contextlib import numpy as np import psutil import pytest @pytest.fixture() def img_file(tmpdir) -> str: import PIL.Image img_file_ = tmpdir.join("test_img.bmp") img = PIL.Image.fromarray(np.random.randint(255, size=(10, 10, 3)).astype(...
# pylint: disable=redefined-outer-name # type: ignore[no-untyped-def] import io import sys import json import numpy as np import pytest import aiohttp from bentoml.io import PandasDataFrame from bentoml.testing.utils import async_request from bentoml.testing.utils import parse_multipart_form @pytest.fixture() def ...
# import asyncio # import time # import psutil # import pytest DEFAULT_MAX_LATENCY = 10 * 1000 """ @pytest.mark.skipif(not psutil.POSIX, reason="production server only works on POSIX") @pytest.mark.asyncio async def test_slow_server(host): A, B = 0.2, 1 data = '{"a": %s, "b": %s}' % (A, B) time_star...
# pylint: disable=redefined-outer-name # type: ignore[no-untyped-def] import pytest from bentoml.testing.utils import async_request @pytest.mark.asyncio async def test_api_server_meta(host: str) -> None: status, _, _ = await async_request("GET", f"http://{host}/") assert status == 200 status, _, _ = awa...
from datetime import datetime # Adding BentoML source directory for accessing BentoML version import bentoml # -- Project information ----------------------------------------------------- project = "BentoML" copyright = f"2022-{datetime.now().year}, bentoml.com" author = "bentoml.com" version = bentoml.__version__ ...
raise NotImplementedError( f"""\ Support for "{__name__}" is temporarily unavailable as BentoML transition to the new \ design in version 1.0.0 release. Before this module is officially implemented in \ BentoML, users may use Custom Runner as a workaround. Learn more at http://docs.bentoml.org """ )
import logging from ._internal.frameworks.lightgbm import get from ._internal.frameworks.lightgbm import load_model from ._internal.frameworks.lightgbm import save_model from ._internal.frameworks.lightgbm import get_runnable logger = logging.getLogger(__name__) def save(tag, *args, **kwargs): logger.warning( ...
from __future__ import annotations import typing as t from typing import TYPE_CHECKING from contextlib import contextmanager from simple_di import inject from simple_di import Provide from ._internal.tag import Tag from ._internal.utils import calc_dir_size from ._internal.models import Model from ._internal.models ...
raise NotImplementedError( f"""\ Support for "{__name__}" is temporarily unavailable as BentoML transition to the new \ design in version 1.0.0 release. Before this module is officially implemented in \ BentoML, users may use Custom Runner as a workaround. Learn more at http://docs.bentoml.org """ )
import logging from ._internal.frameworks.transformers import get from ._internal.frameworks.transformers import load_model from ._internal.frameworks.transformers import save_model from ._internal.frameworks.transformers import get_runnable from ._internal.frameworks.transformers import TransformersOptions as ModelOp...
raise NotImplementedError( f"""\ Support for "{__name__}" is temporarily unavailable as BentoML transition to the new \ design in version 1.0.0 release. Before this module is officially implemented in \ BentoML, users may use Custom Runner as a workaround. Learn more at http://docs.bentoml.org """ )
import logging from ._internal.frameworks.keras import get from ._internal.frameworks.keras import load_model from ._internal.frameworks.keras import save_model from ._internal.frameworks.keras import get_runnable from ._internal.frameworks.keras import KerasOptions as ModelOptions # type: ignore # noqa logger = log...
raise NotImplementedError( f"""\ Support for "{__name__}" is temporarily unavailable as BentoML transition to the new \ design in version 1.0.0 release. Before this module is officially implemented in \ BentoML, users may use Custom Runner as a workaround. Learn more at http://docs.bentoml.org """ )
raise NotImplementedError( f"""\ Support for "{__name__}" is temporarily unavailable as BentoML transition to the new \ design in version 1.0.0 release. Before this module is officially implemented in \ BentoML, users may use Custom Runner as a workaround. Learn more at http://docs.bentoml.org """ )
raise NotImplementedError( f"""\ Support for "{__name__}" is temporarily unavailable as BentoML transition to the new \ design in version 1.0.0 release. Before this module is officially implemented in \ BentoML, users may use Custom Runner as a workaround. Learn more at http://docs.bentoml.org """ )
raise NotImplementedError( f"""\ Support for "{__name__}" is temporarily unavailable as BentoML transition to the new \ design in version 1.0.0 release. Before this module is officially implemented in \ BentoML, users may use Custom Runner as a workaround. Learn more at http://docs.bentoml.org """ )
from ._internal.io_descriptors.base import IODescriptor from ._internal.io_descriptors.file import File from ._internal.io_descriptors.json import JSON from ._internal.io_descriptors.text import Text from ._internal.io_descriptors.image import Image from ._internal.io_descriptors.numpy import NumpyNdarray from ._intern...
raise NotImplementedError( f"""\ Support for "{__name__}" is temporarily unavailable as BentoML transition to the new \ design in version 1.0.0 release. Before this module is officially implemented in \ BentoML, users may use Custom Runner as a workaround. Learn more at http://docs.bentoml.org """ )
from typing import TYPE_CHECKING from ._internal.configuration import BENTOML_VERSION as __version__ from ._internal.configuration import load_global_config # Inject dependencies and configurations load_global_config() # Model management APIs from . import models # Bento management APIs from .bentos import get from...
from typing import TYPE_CHECKING if TYPE_CHECKING: from ._internal.models.model import ModelSignature from ._internal.models.model import ModelSignatureDict __all__ = ["ModelSignature", "ModelSignatureDict"]
import logging from ._internal.frameworks.tensorflow_v2 import get from ._internal.frameworks.tensorflow_v2 import load_model from ._internal.frameworks.tensorflow_v2 import save_model from ._internal.frameworks.tensorflow_v2 import get_runnable from ._internal.frameworks.tensorflow_v2 import TensorflowOptions as Mode...
raise NotImplementedError( f"""\ Support for "{__name__}" is temporarily unavailable as BentoML transition to the new \ design in version 1.0.0 release. Before this module is officially implemented in \ BentoML, users may use Custom Runner as a workaround. Learn more at http://docs.bentoml.org """ )
""" User facing python APIs for managing local bentos and build new bentos """ from __future__ import annotations import os import typing as t import logging import subprocess from typing import TYPE_CHECKING from simple_di import inject from simple_di import Provide from bentoml.exceptions import InvalidArgument ...
import logging from ._internal.frameworks.pytorch_lightning import get from ._internal.frameworks.pytorch_lightning import load_model from ._internal.frameworks.pytorch_lightning import save_model from ._internal.frameworks.pytorch_lightning import get_runnable logger = logging.getLogger(__name__) def save(tag, *ar...
import logging from ._internal.frameworks.pytorch import get from ._internal.frameworks.pytorch import load_model from ._internal.frameworks.pytorch import save_model from ._internal.frameworks.pytorch import get_runnable logger = logging.getLogger(__name__) def save(tag, *args, **kwargs): logger.warning( ...
raise NotImplementedError( f"""\ Support for "{__name__}" is temporarily unavailable as BentoML transition to the new \ design in version 1.0.0 release. Before this module is officially implemented in \ BentoML, users may use Custom Runner as a workaround. Learn more at http://docs.bentoml.org """ )
raise NotImplementedError( f"""\ Support for "{__name__}" is temporarily unavailable as BentoML transition to the new \ design in version 1.0.0 release. Before this module is officially implemented in \ BentoML, users may use Custom Runner as a workaround. Learn more at http://docs.bentoml.org """ )
from __future__ import annotations from http import HTTPStatus class BentoMLException(Exception): """ Base class for all BentoML's errors. Each custom exception should be derived from this class """ error_code = HTTPStatus.INTERNAL_SERVER_ERROR def __init__(self, message: str): self...
raise NotImplementedError( f"""\ Support for "{__name__}" is temporarily unavailable as BentoML transition to the new \ design in version 1.0.0 release. Before this module is officially implemented in \ BentoML, users may use Custom Runner as a workaround. Learn more at http://docs.bentoml.org """ )
import logging from ._internal.frameworks.torchscript import get from ._internal.frameworks.torchscript import load_model from ._internal.frameworks.torchscript import save_model from ._internal.frameworks.torchscript import get_runnable logger = logging.getLogger(__name__) def save(tag, *args, **kwargs): logge...
import logging from ._internal.frameworks.xgboost import get from ._internal.frameworks.xgboost import load_model from ._internal.frameworks.xgboost import save_model from ._internal.frameworks.xgboost import get_runnable logger = logging.getLogger(__name__) def save(tag, *args, **kwargs): logger.warning( ...
import logging from ._internal.frameworks.sklearn import get from ._internal.frameworks.sklearn import load_model from ._internal.frameworks.sklearn import save_model from ._internal.frameworks.sklearn import get_runnable logger = logging.getLogger(__name__) def save(tag, *args, **kwargs): logger.warning( ...
raise NotImplementedError( f"""\ Support for "{__name__}" is temporarily unavailable as BentoML transition to the new \ design in version 1.0.0 release. Before this module is officially implemented in \ BentoML, users may use Custom Runner as a workaround. Learn more at http://docs.bentoml.org """ )
raise NotImplementedError( f"""\ Support for "{__name__}" is temporarily unavailable as BentoML transition to the new \ design in version 1.0.0 release. Before this module is officially implemented in \ BentoML, users may use Custom Runner as a workaround. Learn more at http://docs.bentoml.org """ )
raise NotImplementedError( f"""\ Support for "{__name__}" is temporarily unavailable as BentoML transition to the new \ design in version 1.0.0 release. Before this module is officially implemented in \ BentoML, users may use Custom Runner as a workaround. Learn more at http://docs.bentoml.org """ )
from ._internal.frameworks.picklable import get from ._internal.frameworks.picklable import load_model from ._internal.frameworks.picklable import save_model from ._internal.frameworks.picklable import get_runnable __all__ = ["load_model", "get_runnable", "save_model", "get"]
if __name__ == "__main__": from bentoml._internal.cli import create_bentoml_cli create_bentoml_cli()()