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, dampening=0, weight_decay=0, nesterov=False, optim_bits=32, args=None, min_8bit_size=4096, percentile_clipping=100, block_wise=True): if momentum == 0: raise NotImplementError(f'SGD without momentum is not supported!') super(SGD, self).__init__('momentum', params, lr, (momentum, dampening), 0.0, weight_decay, optim_bits, args, min_8bit_size, percentile_clipping, block_wise) class SGD8bit(Optimizer1State): def __init__(self, params, lr, momentum=0, dampening=0, weight_decay=0, nesterov=False, args=None, min_8bit_size=4096, percentile_clipping=100, block_wise=True): if momentum == 0: raise NotImplementError(f'SGD without momentum is not supported!') super(SGD8bit, self).__init__('momentum', params, lr, (momentum, dampening), 0.0, weight_decay, 8, args, min_8bit_size, percentile_clipping, block_wise) class SGD32bit(Optimizer1State): def __init__(self, params, lr, momentum=0, dampening=0, weight_decay=0, nesterov=False, args=None, min_8bit_size=4096, percentile_clipping=100, block_wise=True): if momentum == 0: raise NotImplementError(f'SGD without momentum is not supported!') super(SGD32bit, self).__init__('momentum', params, lr, (momentum, dampening), 0.0, weight_decay, 32, args, min_8bit_size, percentile_clipping, block_wise)
# 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): def __init__(self, params, lr, momentum=0, dampening=0, weight_decay=0, nesterov=False, optim_bits=32, args=None, min_8bit_size=4096, percentile_clipping=100, max_unorm=0.02): if momentum == 0: raise NotImplementError(f'LARS without momentum is not supported!') super(LARS, self).__init__('lars', params, lr, (momentum, dampening), 0.0, weight_decay, optim_bits, args, min_8bit_size, percentile_clipping, max_unorm=max_unorm, block_wise=False) class LARS8bit(Optimizer1State): def __init__(self, params, lr, momentum=0, dampening=0, weight_decay=0, nesterov=False, args=None, min_8bit_size=4096, percentile_clipping=100, max_unorm=0.02): if momentum == 0: raise NotImplementError(f'LARS without momentum is not supported!') super(LARS8bit, self).__init__('lars', params, lr, (momentum, dampening), 0.0, weight_decay, 8, args, min_8bit_size, percentile_clipping, max_unorm=max_unorm, block_wise=False) class LARS32bit(Optimizer1State): def __init__(self, params, lr, momentum=0, dampening=0, weight_decay=0, nesterov=False, args=None, min_8bit_size=4096, percentile_clipping=100, max_unorm=0.02): if momentum == 0: raise NotImplementError(f'LARS without momentum is not supported!') super(LARS32bit, self).__init__('lars', params, lr, (momentum, dampening), 0.0, weight_decay, 32, args, min_8bit_size, percentile_clipping, max_unorm=max_unorm, block_wise=False) class PytorchLARS(Optimizer): def __init__(self, params, lr=0.01, momentum=0, dampening=0, weight_decay=0, nesterov=False, max_unorm=0.02): if lr < 0.0: raise ValueError("Invalid learning rate: {}".format(lr)) if momentum < 0.0: raise ValueError("Invalid momentum value: {}".format(momentum)) if weight_decay < 0.0: raise ValueError("Invalid weight_decay value: {}".format(weight_decay)) defaults = dict(lr=lr, momentum=momentum, dampening=dampening, weight_decay=weight_decay, nesterov=nesterov, max_unorm=max_unorm) if nesterov and (momentum <= 0 or dampening != 0): raise ValueError("Nesterov momentum requires a momentum and zero dampening") super(PytorchLARS, self).__init__(params, defaults) def __setstate__(self, state): super(PytorchLARS, self).__setstate__(state) for group in self.param_groups: group.setdefault('nesterov', False) @torch.no_grad() def step(self, closure=None): """Performs a single optimization step. Args: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: with torch.enable_grad(): loss = closure() for group in self.param_groups: params_with_grad = [] d_p_list = [] momentum_buffer_list = [] weight_decay = group['weight_decay'] momentum = group['momentum'] dampening = group['dampening'] nesterov = group['nesterov'] max_unorm = group['max_unorm'] lr = group['lr'] for p in group['params']: if p.grad is None: continue state = self.state[p] d_p = p.grad if weight_decay != 0: d_p = d_p.add(param, alpha=weight_decay) if momentum != 0: buf = state.get('momentum_buffer', None) if buf is None: buf = torch.clone(d_p).detach() state['momentum_buffer']= buf else: buf.mul_(momentum).add_(d_p, alpha=1 - dampening) if nesterov: update = d_p + buf*momentum else: update = buf update_scale = 1.0 if max_unorm > 0.0: assert p.dtype == torch.float32 pnorm = torch.norm(p.detach()) unorm = torch.norm(update) if unorm > max_unorm*pnorm: update_scale = max_unorm*pnorm/unorm p.add_(update, alpha=-lr*update_scale) return loss
# 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 .lars import LARS, LARS8bit, LARS32bit, PytorchLARS from .lamb import LAMB, LAMB8bit, LAMB32bit from .rmsprop import RMSprop, RMSprop8bit, RMSprop32bit from .adagrad import Adagrad, Adagrad8bit, Adagrad32bit from .optimizer import GlobalOptimManager
# 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__(self, params, lr=1e-2, lr_decay=0, weight_decay=0, initial_accumulator_value=0, eps=1e-10, optim_bits=32, args=None, min_8bit_size=4096, percentile_clipping=100, block_wise=True): if not 0.0 <= lr: raise ValueError("Invalid learning rate: {}".format(lr)) if not 0.0 <= weight_decay: raise ValueError("Invalid weight_decay value: {}".format(weight_decay)) if not 0.0 <= eps: raise ValueError("Invalid epsilon value: {}".format(eps)) if initial_accumulator_value != 0.0: raise ValueError('Initial accumulator value != 0.0 not supported!') if lr_decay != 0.0: raise ValueError('Lr Decay != 0.0 not supported!') super(Adagrad, self).__init__('adagrad', params, lr, (0.0, 0.0), eps, weight_decay, optim_bits, args, min_8bit_size, percentile_clipping, block_wise) class Adagrad8bit(Optimizer1State): def __init__(self, params, lr=1e-2, lr_decay=0, weight_decay=0, initial_accumulator_value=0, eps=1e-10, optim_bits=8, args=None, min_8bit_size=4096, percentile_clipping=100, block_wise=True): if not 0.0 <= lr: raise ValueError("Invalid learning rate: {}".format(lr)) if not 0.0 <= weight_decay: raise ValueError("Invalid weight_decay value: {}".format(weight_decay)) if not 0.0 <= eps: raise ValueError("Invalid epsilon value: {}".format(eps)) if initial_accumulator_value != 0.0: raise ValueError('Initial accumulator value != 0.0 not supported!') if lr_decay != 0.0: raise ValueError('Lr Decay != 0.0 not supported!') assert block_wise super(Adagrad8bit, self).__init__('adagrad', params, lr, (0.0, 0.0), eps, weight_decay, 8, args, min_8bit_size, percentile_clipping, block_wise) class Adagrad32bit(Optimizer1State): def __init__(self, params, lr=1e-2, lr_decay=0, weight_decay=0, initial_accumulator_value=0, eps=1e-10, optim_bits=32, args=None, min_8bit_size=4096, percentile_clipping=100, block_wise=True): if not 0.0 <= lr: raise ValueError("Invalid learning rate: {}".format(lr)) if not 0.0 <= weight_decay: raise ValueError("Invalid weight_decay value: {}".format(weight_decay)) if not 0.0 <= eps: raise ValueError("Invalid epsilon value: {}".format(eps)) if initial_accumulator_value != 0.0: raise ValueError('Initial accumulator value != 0.0 not supported!') if lr_decay != 0.0: raise ValueError('Lr Decay != 0.0 not supported!') super(Adagrad32bit, self).__init__('adagrad', params, lr, (0.0, 0.0), eps, weight_decay, 32, args, min_8bit_size, percentile_clipping, block_wise)
# 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): def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=1e-2, amsgrad=False, optim_bits=32, args=None, min_8bit_size=4096, percentile_clipping=100, block_wise=True): super(AdamW, self).__init__('adam', params, lr, betas, eps, weight_decay, optim_bits, args, min_8bit_size, percentile_clipping, block_wise) class AdamW8bit(Optimizer2State): def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=1e-2, amsgrad=False, args=None, min_8bit_size=4096, percentile_clipping=100, block_wise=True): super(AdamW8bit, self).__init__('adam', params, lr, betas, eps, weight_decay, 8, args, min_8bit_size, percentile_clipping, block_wise) class AdamW32bit(Optimizer2State): def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=1e-2, amsgrad=False, args=None, min_8bit_size=4096, percentile_clipping=100, block_wise=True): super(AdamW32bit, self).__init__('adam', params, lr, betas, eps, weight_decay, 32, args, min_8bit_size, percentile_clipping, block_wise)
# 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 bitsandbytes.functional as F class Adam(Optimizer2State): def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0, amsgrad=False, optim_bits=32, args=None, min_8bit_size=4096, percentile_clipping=100, block_wise=True): super(Adam, self).__init__('adam', params, lr, betas, eps, weight_decay, optim_bits, args, min_8bit_size, percentile_clipping, block_wise) class Adam8bit(Optimizer2State): def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0, amsgrad=False, args=None, min_8bit_size=4096, percentile_clipping=100, block_wise=True): super(Adam8bit, self).__init__('adam', params, lr, betas, eps, weight_decay, 8, args, min_8bit_size, percentile_clipping, block_wise) class Adam32bit(Optimizer2State): def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0, amsgrad=False, args=None, min_8bit_size=4096, percentile_clipping=100, block_wise=True): super(Adam32bit, self).__init__('adam', params, lr, betas, eps, weight_decay, 32, args, min_8bit_size, percentile_clipping, block_wise) class AnalysisAdam(torch.optim.Optimizer): """Adam that performs 8-bit vs 32-bit error analysis. This implementation is modified from torch.optim.Adam based on: `Fixed Weight Decay Regularization in Adam` (see https://arxiv.org/abs/1711.05101) It has been proposed in `Adam: A Method for Stochastic Optimization`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups lr (float, optional): learning rate (default: 1e-3) betas (Tuple[float, float], optional): coefficients used for computing running averages of gradient and its square (default: (0.9, 0.999)) eps (float, optional): term added to the denominator to improve numerical stability (default: 1e-8) weight_decay (float, optional): weight decay (L2 penalty) (default: 0) amsgrad (boolean, optional): whether to use the AMSGrad variant of this algorithm from the paper `On the Convergence of Adam and Beyond`_ .. _Adam: A Method for Stochastic Optimization: https://arxiv.org/abs/1412.6980 .. _On the Convergence of Adam and Beyond: https://openreview.net/forum?id=ryQu7f-RZ """ def __init__( self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0, amsgrad=False, bnb_analysis='dynamic-blockwise', savedir=None ): defaults = dict( lr=lr, betas=betas, eps=eps, weight_decay=weight_decay, amsgrad=amsgrad ) super(AnalysisAdam, self).__init__(params, defaults) self.analysis = bnb_analysis self.savedir = savedir @property def supports_memory_efficient_fp16(self): return True @property def supports_flat_params(self): return True def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() for group in self.param_groups: for p_id, p in enumerate(group["params"]): if p.grad is None: continue grad = p.grad.data if grad.dtype in {torch.float16, torch.bfloat16}: grad = grad.float() if grad.is_sparse: raise RuntimeError( "Adam does not support sparse gradients, please consider SparseAdam instead" ) amsgrad = group.get("amsgrad", False) assert not amsgrad p_data_fp32 = p.data if p.data.dtype in {torch.float16, torch.bfloat16}: p_data_fp32 = p_data_fp32.float() state = self.state[p] # State initialization if len(state) == 0: state["step"] = 0 # Exponential moving average of gradient values state["exp_avg"] = torch.zeros_like(p_data_fp32) # Exponential moving average of squared gradient values state["exp_avg_sq"] = torch.zeros_like(p_data_fp32) state['abserrors'] = torch.zeros((256, 256), device=p_data_fp32.device) state['relerrors'] = torch.zeros((256, 256), device=p_data_fp32.device) state['counts'] = torch.zeros((256, 256), device=p_data_fp32.device) if amsgrad: # Maintains max of all exp. moving avg. of sq. grad. values state["max_exp_avg_sq"] = torch.zeros_like(p_data_fp32) else: state["exp_avg"] = state["exp_avg"].to(p_data_fp32) state["exp_avg_sq"] = state["exp_avg_sq"].to(p_data_fp32) if amsgrad: state["max_exp_avg_sq"] = state["max_exp_avg_sq"].to( p_data_fp32 ) state["step"] += 1 beta1, beta2 = group["betas"] bias_correction1 = 1 - beta1 ** state["step"] bias_correction2 = 1 - beta2 ** state["step"] step_size = group["lr"] * math.sqrt(bias_correction2) / bias_correction1 e = state['abserrors'] rele = state['relerrors'] counts = state['counts'] if group["weight_decay"] != 0: p_data_fp32.add_( p_data_fp32, alpha=-group["weight_decay"] * group["lr"] ) exp_avg, exp_avg_sq = state["exp_avg"], state["exp_avg_sq"] if amsgrad: max_exp_avg_sq = state["max_exp_avg_sq"] # Decay the first and second moment running average coefficient exp_avg.mul_(beta1).add_(grad, alpha=1 - beta1) exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=1 - beta2) denom = exp_avg_sq.sqrt().add_(group["eps"]) update_fp32 = exp_avg/denom if p_data_fp32.numel() <= 8192 or p_data_fp32.numel() > 50000*1000: # embedding layer or too small p_data_fp32 += -step_size*update_fp32 else: if self.analysis == 'dynamic-blockwise': code1 = F.create_dynamic_map(signed=True).to(p.device) code2 = F.create_dynamic_map(signed=False).to(p.device) C1, S1 = F.quantize_blockwise(exp_avg, code=code1) state1 = F.dequantize_blockwise(C1, S1) C2, S2 = F.quantize_blockwise(exp_avg_sq, code=code2) state2 = F.dequantize_blockwise(C2, S2) elif self.analysis == 'dynamic': code1 = F.create_dynamic_map(signed=True).to(p.device) code2 = F.create_dynamic_map(signed=False).to(p.device) C1, S1 = F.quantize(exp_avg, code=code1) state1 = F.dequantize(C1, S1) C2, S2 = F.quantize(exp_avg_sq, code=code2) state2 = F.dequantize(C2, S2) elif self.analysis == 'linear': code1 = F.create_linear_map(signed=True).to(p.device) code2 = F.create_linear_map(signed=False).to(p.device) C1, S1 = F.quantize(exp_avg, code=code1) state1 = F.dequantize(C1, S1) C2, S2 = F.quantize(exp_avg_sq, code=code2) state2 = F.dequantize(C2, S2) elif self.analysis == 'quantile': code1 = F.estimate_quantiles(exp_avg) code2 = F.estimate_quantiles(exp_avg_sq) C1 = F.quantize_no_absmax(exp_avg, code=code1) state1 = F.dequantize_no_absmax(C1, code1) C2 = F.quantize_no_absmax(exp_avg_sq, code=code2) state2 = F.dequantize_no_absmax(C2, code2) elif self.analysis == 'my-quantization-routine': pass # 1. get code # 2. quantize # 3. dequantize # Error will be calculated automatically! else: raise ValueError(f'Invalid analysis value: {self.analysis}!') denom = state2.sqrt().add_(group["eps"]) update_8bit = state1/denom abserr = torch.abs(update_8bit-update_fp32) relerr = abserr/torch.abs(update_fp32+1e-6) C1, C2 = C1.int(), C2.int() F.histogram_scatter_add_2d(e, C1.int(), C2.int(), abserr) F.histogram_scatter_add_2d(rele, C1.int(), C2.int(), relerr) F.histogram_scatter_add_2d(counts, C1.int(), C2.int(), torch.ones_like(abserr)) p_data_fp32 += -step_size*update_fp32 if not dist.is_initialized() or dist.get_rank() == 0: if self.savedir != '' and state['step'] % 100 == 0: if not os.path.exists(self.savedir): os.makedirs(self.savedir) shapestr = '_'.join([str(dim) for dim in p_data_fp32.shape]) pathe = os.path.join(self.savedir, f'{p_id}_{shapestr}_abserr.pkl') pathrele = os.path.join(self.savedir, f'{p_id}_{shapestr}_relerr.pkl') pathcounts = os.path.join(self.savedir, f'{p_id}_{shapestr}_counts.pkl') torch.save(e, pathe) torch.save(rele, pathrele) torch.save(counts, pathcounts) if p.data.dtype in {torch.float16, torch.bfloat16}: p.data.copy_(p_data_fp32) return loss
# 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 defaultdict, abc as container_abcs class MockArgs(object): def __init__(self, initial_data): for key in initial_data: setattr(self, key, initial_data[key]) class GlobalOptimManager(object): _instance = None def __init__(self): raise RuntimeError('Call get_instance() instead') def initialize(self): self.pid2config = {} self.index2config = {} self.optimizer = None self.uses_config_override = False self.module_weight_config_triple = [] @classmethod def get_instance(cls): if cls._instance is None: cls._instance = cls.__new__(cls) cls._instance.initialize() return cls._instance def register_parameters(self, params): param_groups = list(params) if not isinstance(param_groups[0], dict): param_groups = [{'params': param_groups}] for group_index, group in enumerate(param_groups): for p_index, p in enumerate(group['params']): if id(p) in self.pid2config: self.index2config[(group_index, p_index)] = self.pid2config[id(p)] def override_config(self, parameters, key=None, value=None, key_value_dict=None): ''' Overrides initial optimizer config for specific parameters. The key-values of the optimizer config for the input parameters are overidden This can be both, optimizer parameters like "betas", or "lr" or it can be 8-bit specific paramters like "optim_bits", "percentile_clipping". Parameters ---------- parameters : torch.Tensor or list(torch.Tensors) The input parameters. key : str The hyperparamter to override. value : object The value for the hyperparamters. key_value_dict : dict A dictionary with multiple key-values to override. ''' self.uses_config_override = True if isinstance(parameters, torch.nn.Parameter): parameters = [parameters] if isinstance(parameters, torch.Tensor): parameters = [parameters] if key is not None and value is not None: assert key_value_dict is None key_value_dict = {key: value} if key_value_dict is not None: for p in parameters: if id(p) in self.pid2config:self.pid2config[id(p)].update(key_value_dict) else: self.pid2config[id(p)] = key_value_dict def register_module_override(self, module, param_name, config): self.module_weight_config_triple.append((module, param_name, config)) class Optimizer8bit(torch.optim.Optimizer): def __init__(self, params, defaults, optim_bits=32): super(Optimizer8bit, self).__init__(params, defaults) self.initialized = False self.name2qmap = {} self.mng = GlobalOptimManager.get_instance() self.non_castable_tensor_keys = set( ['qmap1', 'qmap2', 'max1', 'max2', 'new_max1', 'new_max2', 'state1', 'state2', 'gnorm_vec', 'absmax1', 'absmax2', 'unorm_vec']) if optim_bits == 8: self.fill_qmap() def fill_qmap(self): self.name2qmap['dynamic'] = F.create_dynamic_map(signed=True) self.name2qmap['udynamic'] = F.create_dynamic_map(signed=False) def __setstate__(self, state): super(Optimizer8bit, self).__setstate__(state) def load_state_dict(self, state_dict): r"""Loads the optimizer state. Args: state_dict (dict): optimizer state. Should be an object returned from a call to :meth:`state_dict`. """ # deepcopy, to be consistent with module API state_dict = deepcopy(state_dict) # Validate the state_dict groups = self.param_groups saved_groups = state_dict['param_groups'] if len(groups) != len(saved_groups): raise ValueError("loaded state dict has a different number of " "parameter groups") param_lens = (len(g['params']) for g in groups) saved_lens = (len(g['params']) for g in saved_groups) if any(p_len != s_len for p_len, s_len in zip(param_lens, saved_lens)): raise ValueError("loaded state dict contains a parameter group " "that doesn't match the size of optimizer's group") # Update the state id_map = {old_id: p for old_id, p in zip(chain.from_iterable((g['params'] for g in saved_groups)), chain.from_iterable((g['params'] for g in groups)))} def cast(param, value): r"""Make a deep copy of value, casting all tensors to device of param.""" if isinstance(value, torch.Tensor): # Floating-point types are a bit special here. They are the only ones # that are assumed to always match the type of params. if param.is_floating_point() and value.dtype != torch.uint8: value = value.to(param.dtype) return value elif isinstance(value, dict): for k, v in value.items(): if k in self.non_castable_tensor_keys: value[k] = v.to(param.device) else: value[k] = cast(param, v) return value elif isinstance(value, container_abcs.Iterable): return type(value)(cast(param, v) for v in value) else: return value # Copy state assigned to params (and cast tensors to appropriate types). # State that is not assigned to params is copied as is (needed for # backward compatibility). state = defaultdict(dict) for k, v in state_dict['state'].items(): if k in id_map: param = id_map[k] state[param] = cast(param, v) else: state[k] = v # Update parameter groups, setting their 'params' value def update_group(group, new_group): new_group['params'] = group['params'] return new_group param_groups = [ update_group(g, ng) for g, ng in zip(groups, saved_groups)] self.__setstate__({'state': state, 'param_groups': param_groups}) def to_gpu(self): for gindex, group in enumerate(self.param_groups): for pindex, p in enumerate(group['params']): if p in self.state: values = self.state[p] for k, v in values.items(): if isinstance(v, torch.Tensor): self.state[p][k] = v.to(p.device) def check_overrides(self): for module, attr, config in self.mng.module_weight_config_triple: pmodule = getattr(module, attr) assert pmodule is not None assert isinstance(pmodule, torch.Tensor) or isinstance(pmodule, torch.Parameter) found = False for gindex, group in enumerate(self.param_groups): if found: break for pindex, p in enumerate(group['params']): if found: break if id(p) == id(pmodule): # found the matching parameter # init override self.mng.pid2config[id(p)] = config self.mng.index2config[(gindex, pindex)] = self.mng.pid2config[id(p)] found = True @torch.no_grad() def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: with torch.enable_grad(): loss = closure() overflows = [] if not self.initialized: self.check_overrides() self.to_gpu() # needed for fairseq pure fp16 training self.initialized = True for gindex, group in enumerate(self.param_groups): for pindex, p in enumerate(group['params']): if p.grad is None: continue state = self.state[p] if len(state) == 0: self.init_state(group, p, gindex, pindex) self.update_step(group, p, gindex, pindex) return loss def get_config(self, gindex, pindex, group): config = {} config['betas'] = group['betas'] config['eps'] = group['eps'] config['weight_decay'] = group['weight_decay'] config['lr'] = group['lr'] config['optim_bits'] = self.args.optim_bits config['min_8bit_size'] = self.args.min_8bit_size config['percentile_clipping'] = self.args.percentile_clipping config['block_wise'] = self.args.block_wise config['max_unorm'] = self.args.max_unorm config['skip_zeros'] = self.args.skip_zeros if (gindex, pindex) in self.mng.index2config: config.update(self.mng.index2config[(gindex, pindex)]) return config def init_state(self, group, p, gindex, pindex): raise NotImplementedError(f'init_state method needs to be overidden') def update_step(self, group, p, gindex, pindex): raise NotImplementedError(f'The update_step method needs to be overidden') class Optimizer2State(Optimizer8bit): def __init__(self, optimizer_name, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0.0, optim_bits=32, args=None, min_8bit_size=4096, percentile_clipping=100, block_wise=True, max_unorm=0.0, skip_zeros=False): if not 0.0 <= lr: raise ValueError("Invalid learning rate: {}".format(lr)) if not 0.0 <= eps: raise ValueError("Invalid epsilon value: {}".format(eps)) if isinstance(betas, str): # format: '(beta1, beta2)' betas = betas.replace('(', '').replace(')', '').strip().split(',') betas = [float(b) for b in betas] for i in range(len(betas)): if not 0.0 <= betas[i] < 1.0: raise ValueError(f"Invalid beta parameter at index {i}: {betas[i]}") if not 0.0 <= weight_decay: raise ValueError("Invalid weight_decay value: {}".format(weight_decay)) defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay) super(Optimizer2State, self).__init__(params, defaults, optim_bits) if args is None: args = {} args['optim_bits'] = optim_bits args['percentile_clipping'] = 100 args['min_8bit_size'] = min_8bit_size args['percentile_clipping'] = percentile_clipping args['block_wise'] = block_wise args['max_unorm'] = max_unorm args['skip_zeros'] = skip_zeros self.args = MockArgs(args) else: self.args = args self.optimizer_name = optimizer_name @torch.no_grad() def init_state(self, group, p, gindex, pindex): config = self.get_config(gindex, pindex, group) if config['optim_bits'] == 32: dtype = torch.float32 elif config['optim_bits'] == 8: dtype = torch.uint8 else: raise NotImplementedError(f'Amount of optimizer bits not supported: {config["optim_bits"]}') if p.numel() < config['min_8bit_size']: dtype = torch.float32 state = self.state[p] state['step'] = 0 if dtype == torch.float32 or (dtype == torch.uint8 and p.numel() < 4096): state['state1'] = torch.zeros_like(p, memory_format=torch.preserve_format, dtype=torch.float32, device=p.device) state['state2'] = torch.zeros_like(p, memory_format=torch.preserve_format, dtype=torch.float32, device=p.device) elif dtype == torch.uint8: if state['step'] == 0: if 'dynamic' not in self.name2qmap: self.fill_qmap() self.name2qmap['dynamic'] = self.name2qmap['dynamic'].to(p.device) self.name2qmap['udynamic'] = self.name2qmap['udynamic'].to(p.device) state['state1'] = torch.zeros_like(p, memory_format=torch.preserve_format, dtype=torch.uint8, device=p.device) state['qmap1'] = self.name2qmap['dynamic'] state['state2'] = torch.zeros_like(p, memory_format=torch.preserve_format, dtype=torch.uint8, device=p.device) state['qmap2'] = self.name2qmap['udynamic'] if config['block_wise']: n = p.numel() blocks = n//2048 blocks += 1 if n % 2048 > 0 else 0 state['absmax1'] = torch.zeros((blocks,), dtype=torch.float32, device=p.device) state['absmax2'] = torch.zeros((blocks,), dtype=torch.float32, device=p.device) else: state['max1'] = torch.zeros((1,), dtype=torch.float32, device=p.device) state['new_max1'] = torch.zeros((1,), dtype=torch.float32, device=p.device) state['max2'] = torch.zeros((1,), dtype=torch.float32, device=p.device) state['new_max2'] = torch.zeros((1,), dtype=torch.float32, device=p.device) if config['percentile_clipping'] < 100: state['gnorm_vec'] = torch.zeros((100,), device=p.device) if config['max_unorm'] > 0.0: state['unorm_vec'] = torch.zeros((1,), device=p.device) @torch.no_grad() def update_step(self, group, p, gindex, pindex): state = self.state[p] grad = p.grad config = self.get_config(gindex, pindex, group) state['step'] += 1 step = state['step'] if config['percentile_clipping'] < 100: current_gnorm, clip_value, gnorm_scale = F.percentile_clipping(grad, state['gnorm_vec'], step, config['percentile_clipping']) else: gnorm_scale = 1.0 if state['state1'].dtype == torch.float: F.optimizer_update_32bit(self.optimizer_name, grad, p, state['state1'], config['betas'][0], config['eps'], step, config['lr'], state['state2'], config['betas'][1], config['weight_decay'], gnorm_scale, state['unorm_vec'] if config['max_unorm'] > 0.0 else None, max_unorm=config['max_unorm'], skip_zeros=config['skip_zeros']) elif state['state1'].dtype == torch.uint8 and not config['block_wise']: F.optimizer_update_8bit(self.optimizer_name, grad, p, state['state1'], state['state2'], config['betas'][0], config['betas'][1], config['eps'], step, config['lr'], state['qmap1'], state['qmap2'], state['max1'], state['max2'], state['new_max1'], state['new_max2'], config['weight_decay'], gnorm_scale=gnorm_scale, unorm_vec=state['unorm_vec'] if config['max_unorm'] > 0.0 else None, max_unorm=config['max_unorm']) # swap maxes state['max1'], state['new_max1'] = state['new_max1'], state['max1'] state['max2'], state['new_max2'] = state['new_max2'], state['max2'] elif state['state1'].dtype == torch.uint8 and config['block_wise']: F.optimizer_update_8bit_blockwise(self.optimizer_name, grad, p, state['state1'], state['state2'], config['betas'][0], config['betas'][1], config['eps'], step, config['lr'], state['qmap1'], state['qmap2'], state['absmax1'], state['absmax2'], config['weight_decay'], gnorm_scale=gnorm_scale, skip_zeros=config['skip_zeros']) class Optimizer1State(Optimizer8bit): def __init__(self, optimizer_name, params, lr=1e-3, betas=(0.9, 0.0), eps=1e-8, weight_decay=0.0, optim_bits=32, args=None, min_8bit_size=4096, percentile_clipping=100, block_wise=True, max_unorm=0.0, skip_zeros=False): if not 0.0 <= lr: raise ValueError("Invalid learning rate: {}".format(lr)) if not 0.0 <= eps: raise ValueError("Invalid epsilon value: {}".format(eps)) for i in range(len(betas)): if not 0.0 <= betas[i] < 1.0: raise ValueError(f"Invalid beta parameter at index {i}: {betas[i]}") if not 0.0 <= weight_decay: raise ValueError("Invalid weight_decay value: {}".format(weight_decay)) defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay) super(Optimizer1State, self).__init__(params, defaults, optim_bits) if args is None: args = {} args['optim_bits'] = optim_bits args['percentile_clipping'] = 100 args['min_8bit_size'] = min_8bit_size args['percentile_clipping'] = percentile_clipping args['block_wise'] = block_wise args['max_unorm'] = max_unorm args['skip_zeros'] = skip_zeros self.args = MockArgs(args) else: self.args = args self.optimizer_name = optimizer_name @torch.no_grad() def init_state(self, group, p, gindex, pindex): config = self.get_config(gindex, pindex, group) if config['optim_bits'] == 32: dtype = torch.float32 elif config['optim_bits'] == 8: dtype = torch.uint8 else: raise NotImplementedError(f'Amount of optimizer bits not supported: {config["optim_bits"]}') if p.numel() < config['min_8bit_size']: dtype = torch.float32 state = self.state[p] state['step'] = 0 if dtype == torch.float32 or (dtype == torch.uint8 and p.numel() < 4096): state['state1'] = torch.zeros_like(p, memory_format=torch.preserve_format, dtype=torch.float32, device=p.device) elif dtype == torch.uint8: if state['step'] == 0: if 'dynamic' not in self.name2qmap: self.fill_qmap() self.name2qmap['dynamic'] = self.name2qmap['dynamic'].to(p.device) state['state1'] = torch.zeros_like(p, memory_format=torch.preserve_format, dtype=torch.uint8, device=p.device) state['qmap1'] = self.name2qmap['dynamic'] if config['block_wise']: n = p.numel() blocks = n//2048 blocks += 1 if n % 2048 > 0 else 0 state['absmax1'] = torch.zeros((blocks,), dtype=torch.float32, device=p.device) else: state['max1'] = torch.zeros((1,), dtype=torch.float32, device=p.device) state['new_max1'] = torch.zeros((1,), dtype=torch.float32, device=p.device) if config['percentile_clipping'] < 100: state['gnorm_vec'] = torch.zeros((100,), device=p.device) if config['max_unorm'] > 0.0: state['unorm_vec'] = torch.zeros((1,), device=p.device) @torch.no_grad() def update_step(self, group, p, gindex, pindex): state = self.state[p] grad = p.grad config = self.get_config(gindex, pindex, group) state['step'] += 1 step = state['step'] if config['percentile_clipping'] < 100: current_gnorm, clip_value, gnorm_scale = F.percentile_clipping(grad, state['gnorm_vec'], step, config['percentile_clipping']) else: gnorm_scale = 1.0 if state['state1'].dtype == torch.float: F.optimizer_update_32bit(self.optimizer_name, grad, p, state['state1'], config['betas'][0], config['eps'], step, config['lr'], None, 0.0, config['weight_decay'], gnorm_scale, state['unorm_vec'] if config['max_unorm'] > 0.0 else None, max_unorm=config['max_unorm'], skip_zeros=config['skip_zeros']) elif state['state1'].dtype == torch.uint8 and not config['block_wise']: F.optimizer_update_8bit(self.optimizer_name, grad, p, state['state1'], None, config['betas'][0], config['betas'][1], config['eps'], step, config['lr'], state['qmap1'], None, state['max1'], None, state['new_max1'], None, config['weight_decay'], gnorm_scale, state['unorm_vec'] if config['max_unorm'] > 0.0 else None, max_unorm=config['max_unorm']) state['max1'], state['new_max1'] = state['new_max1'], state['max1'] elif state['state1'].dtype == torch.uint8 and config['block_wise']: F.optimizer_update_8bit_blockwise(self.optimizer_name, grad, p, state['state1'], None, config['betas'][0], config['betas'][1], config['eps'], step, config['lr'], state['qmap1'], None, state['absmax1'], None, config['weight_decay'], gnorm_scale=gnorm_scale, skip_zeros=config['skip_zeros'])
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_change_test_dir(request: pytest.FixtureRequest): os.chdir(request.fspath.dirname) # type: ignore (bad pytest stubs) yield os.chdir(request.config.invocation_dir) # type: ignore (bad pytest stubs) @pytest.fixture(scope="session", name="dummy_model_store") def fixture_dummy_model_store(tmpdir_factory: "pytest.TempPathFactory") -> ModelStore: store = ModelStore(tmpdir_factory.mktemp("models")) with bentoml.models.create( "testmodel", module=__name__, signatures={}, context=TEST_MODEL_CONTEXT, _model_store=store, ): pass with bentoml.models.create( "testmodel", module=__name__, signatures={}, context=TEST_MODEL_CONTEXT, _model_store=store, ): pass with bentoml.models.create( "anothermodel", module=__name__, signatures={}, context=TEST_MODEL_CONTEXT, _model_store=store, ): pass return store
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.models import ModelStore from bentoml._internal.models import ModelContext if TYPE_CHECKING: from pathlib import Path PYTHON_VERSION: str = f"{pyver.major}.{pyver.minor}.{pyver.micro}" BENTOML_VERSION: str = importlib_metadata.version("bentoml") def createfile(filepath: str) -> str: content = "".join(random.choices(string.ascii_uppercase + string.digits, k=200)) os.makedirs(os.path.dirname(filepath), exist_ok=True) with open(filepath, "w", encoding="utf-8") as f: f.write(content) return content TEST_MODEL_CONTEXT = ModelContext( framework_name="testing", framework_versions={"testing": "v1"} ) def test_models(tmpdir: "Path"): os.makedirs(os.path.join(tmpdir, "models")) store = ModelStore(os.path.join(tmpdir, "models")) with bentoml.models.create( "testmodel", module=__name__, signatures={}, context=TEST_MODEL_CONTEXT, _model_store=store, ) as testmodel: testmodel1tag = testmodel.tag with bentoml.models.create( "testmodel", module=__name__, signatures={}, context=TEST_MODEL_CONTEXT, _model_store=store, ) as testmodel: testmodel2tag = testmodel.tag testmodel_file_content = createfile(testmodel.path_of("file")) testmodel_infolder_content = createfile(testmodel.path_of("folder/file")) with bentoml.models.create( "anothermodel", module=__name__, signatures={}, context=TEST_MODEL_CONTEXT, _model_store=store, ) as anothermodel: anothermodeltag = anothermodel.tag anothermodel_file_content = createfile(anothermodel.path_of("file")) anothermodel_infolder_content = createfile(anothermodel.path_of("folder/file")) assert ( bentoml.models.get("testmodel:latest", _model_store=store).tag == testmodel2tag ) assert set([model.tag for model in bentoml.models.list(_model_store=store)]) == { testmodel1tag, testmodel2tag, anothermodeltag, } testmodel1 = bentoml.models.get(testmodel1tag, _model_store=store) with pytest.raises(FileNotFoundError): open(testmodel1.path_of("file"), encoding="utf-8") testmodel2 = bentoml.models.get(testmodel2tag, _model_store=store) with open(testmodel2.path_of("file"), encoding="utf-8") as f: assert f.read() == testmodel_file_content with open(testmodel2.path_of("folder/file"), encoding="utf-8") as f: assert f.read() == testmodel_infolder_content anothermodel = bentoml.models.get(anothermodeltag, _model_store=store) with open(anothermodel.path_of("file"), encoding="utf-8") as f: assert f.read() == anothermodel_file_content with open(anothermodel.path_of("folder/file"), encoding="utf-8") as f: assert f.read() == anothermodel_infolder_content export_path = os.path.join(tmpdir, "testmodel2.bentomodel") bentoml.models.export_model(testmodel2tag, export_path, _model_store=store) bentoml.models.delete(testmodel2tag, _model_store=store) with pytest.raises(NotFound): bentoml.models.delete(testmodel2tag, _model_store=store) assert set([model.tag for model in bentoml.models.list(_model_store=store)]) == { testmodel1tag, anothermodeltag, } retrieved_testmodel1 = bentoml.models.get("testmodel", _model_store=store) assert retrieved_testmodel1.tag == testmodel1tag assert retrieved_testmodel1.info.context.python_version == PYTHON_VERSION assert retrieved_testmodel1.info.context.bentoml_version == BENTOML_VERSION assert ( retrieved_testmodel1.info.context.framework_name == TEST_MODEL_CONTEXT.framework_name ) assert ( retrieved_testmodel1.info.context.framework_versions == TEST_MODEL_CONTEXT.framework_versions ) bentoml.models.import_model(export_path, _model_store=store) assert bentoml.models.get("testmodel", _model_store=store).tag == testmodel2tag export_path_2 = os.path.join(tmpdir, "testmodel1") bentoml.models.export_model(testmodel1tag, export_path_2, _model_store=store) bentoml.models.delete(testmodel1tag, _model_store=store) bentoml.models.import_model(export_path_2 + ".bentomodel", _model_store=store) assert bentoml.models.get("testmodel", _model_store=store).tag == testmodel2tag
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": "label", "label3": "anotherlabel"} outp = inp.copy() utils.validate_labels(outp) assert inp == outp inp = {(12,): "non-string label key"} with pytest.raises(ValueError): utils.validate_labels(inp) # type: ignore (testing bad types) inp = {"non-number label": 13} with pytest.raises(ValueError): utils.validate_labels(inp) # type: ignore (testing bad types) inp = "non-dict labels" with pytest.raises(ValueError): utils.validate_labels(inp) # type: ignore (testing bad types) def test_validate_metadata(): inp = "non-dict metadata" # type: ignore (testing bad types) with pytest.raises(ValueError): utils.validate_metadata(inp) inp = {(12,): "non-string key"} # type: ignore (testing bad types) with pytest.raises(ValueError): utils.validate_metadata(inp) # no validation required, inp == outp inp: MetadataDict = { "my key": 12, "float": 13.3, "string": "str", "date": datetime(2022, 3, 14), "timedelta": timedelta(days=3), } outp = inp.copy() utils.validate_metadata(outp) assert inp == outp inp: MetadataDict = {"ndarray": np.array([1, 2, 3])} # type: ignore (we don't annotate translated types) expected = {"ndarray": [1, 2, 3]} utils.validate_metadata(inp) assert inp == expected inp: MetadataDict = {"uint": np.uint(3)} # type: ignore (we don't annotate translated types) expected = {"uint": 3} utils.validate_metadata(inp) assert inp == expected inp: MetadataDict = {"date": np.datetime64("2022-03-17")} # type: ignore (we don't annotate translated types) expected = {"date": date(2022, 3, 17)} utils.validate_metadata(inp) assert inp == expected inp: MetadataDict = {"spmatrix": csr_matrix([0, 0, 0, 0, 0, 1, 1, 0, 2])} # type: ignore (we don't annotate translated types) with pytest.raises(ValueError): utils.validate_metadata(inp) inp: MetadataDict = {"series": pd.Series([1, 2, 4], name="myseriesname")} # type: ignore (we don't annotate translated types) expected = {"series": {"myseriesname": {0: 1, 1: 2, 2: 4}}} utils.validate_metadata(inp) assert inp == expected inp: MetadataDict = {"pandasarray": pd.arrays.PandasArray(np.array([2, 4, 6]))} # type: ignore (we don't annotate translated types) expected = {"pandasarray": [2, 4, 6]} utils.validate_metadata(inp) assert inp == expected inp: MetadataDict = { "dataframe": pd.DataFrame(data={"col1": [1, 2], "col2": pd.Series({"a": 3, "b": 4})}) # type: ignore (we don't annotate translated types) } expected = {"dataframe": {"col1": {"a": 1, "b": 2}, "col2": {"a": 3, "b": 4}}} utils.validate_metadata(inp) assert inp == expected inp: MetadataDict = {"timestamp": pd.Timestamp(datetime(2022, 4, 12))} # type: ignore (we don't annotate translated types) expected = {"timestamp": datetime(2022, 4, 12)} utils.validate_metadata(inp) assert inp == expected inp: MetadataDict = {"timedelta": pd.Timedelta(timedelta(2022))} # type: ignore (we don't annotate translated types) expected = {"timedelta": timedelta(2022)} utils.validate_metadata(inp) assert inp == expected inp: MetadataDict = {"period": pd.Period("2012-05", freq="D")} # type: ignore (we don't annotate translated types) expected = {"period": datetime(2012, 5, 1)} utils.validate_metadata(inp) assert inp == expected inp: MetadataDict = {"interval": pd.Interval(left=0, right=5)} # type: ignore (we don't annotate translated types) expected = {"interval": (0, 5)} utils.validate_metadata(inp) assert inp == expected inp = {"unsupported": None} # type: ignore (testing bad types) with pytest.raises(ValueError): utils.validate_metadata(inp)
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.store import StoreItem if sys.version_info < (3, 7): from backports.datetime_fromisoformat import MonkeyPatch MonkeyPatch.patch_fromisoformat() if TYPE_CHECKING: from pathlib import Path from fs.base import FS from bentoml._internal.types import PathType @attr.define(repr=False) class DummyItem(StoreItem): _tag: Tag fs: "FS" _creation_time: datetime store: "DummyStore" = attr.field(init=False) @staticmethod def _export_ext() -> str: return "bentodummy" @property def tag(self) -> Tag: return self._tag @property def creation_time(self) -> datetime: return self._creation_time @staticmethod def create(tag: t.Union[str, Tag], creation_time: t.Optional[datetime] = None): creation_time = datetime.now() if creation_time is None else creation_time with DummyItem.store.register(tag) as path: dummy_fs = fs.open_fs(path) dummy_fs.writetext("tag", str(tag)) dummy_fs.writetext("ctime", creation_time.isoformat()) @classmethod def from_fs(cls, item_fs: "FS") -> "DummyItem": return DummyItem( Tag.from_str(item_fs.readtext("tag")), item_fs, datetime.fromisoformat(item_fs.readtext("ctime")), ) class DummyStore(Store[DummyItem]): def __init__(self, base_path: "t.Union[PathType, FS]"): super().__init__(base_path, DummyItem) def test_store(tmpdir: "Path"): store = DummyStore(tmpdir) open(os.path.join(tmpdir, ".DS_store"), "a", encoding="utf-8") DummyItem.store = store oldtime = datetime.now() DummyItem.create("test:version1") DummyItem.create("test:otherprefix") DummyItem.create(Tag("test", "version2")) DummyItem.create("test:version3", creation_time=oldtime) DummyItem.create("test1:version1") with pytest.raises(BentoMLException): DummyItem.create("test:version2") item = store.get("test:version1") assert item.tag == Tag("test", "version1") item = store.get("test:oth") assert item.tag == Tag("test", "otherprefix") latest = store.get("test:latest") assert latest.tag == Tag("test", "version2") latest = store.get("test") assert latest.tag == Tag("test", "version2") with pytest.raises(BentoMLException): store.get("test:ver") with pytest.raises(NotFound): store.get("nonexistent:latest") with pytest.raises(NotFound): store.get("test:version4") vers = store.list() assert set([ver.tag for ver in vers]) == { Tag("test", "version1"), Tag("test", "version2"), Tag("test", "version3"), Tag("test", "otherprefix"), Tag("test1", "version1"), } vers = store.list("test") assert set([ver.tag for ver in vers]) == { Tag("test", "version1"), Tag("test", "version2"), Tag("test", "version3"), Tag("test", "otherprefix"), } vers = store.list("test:version1") assert set([ver.tag for ver in vers]) == {Tag("test", "version1")} assert store.list("nonexistent:latest") == [] assert store.list("test:version4") == [] store.delete("test:version2") latest = store.get("test") assert latest.tag == Tag("test", "otherprefix") with pytest.raises(NotFound): store.delete("test:version4") store.delete("test1:version1") with pytest.raises(NotFound): store.get("test1") with pytest.raises(NotFound): store.list("test1") store.delete("test") with pytest.raises(NotFound): store.list("test") assert store.list() == []
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] batch, indices = c.DefaultContainer.batches_to_batch([l1, l2]) assert batch == l1 + l2 assert indices == [0, 3, 7] restored_l1, restored_l2 = c.DefaultContainer.batch_to_batches(batch, indices) assert restored_l1 == l1 assert restored_l2 == l2 # DefaultContainer should only allow batch_dim = 0 with pytest.raises(batch_dim_exc): c.DefaultContainer.batches_to_batch([l1, l2], batch_dim=wrong_batch_dim) with pytest.raises(batch_dim_exc): c.DefaultContainer.batch_to_batches(batch, indices, batch_dim=wrong_batch_dim) def _generator(): yield "apple" yield "banana" yield "cherry" assert c.DefaultContainer.from_payload( c.DefaultContainer.to_payload(_generator()) ) == list(_generator()) assert c.DefaultContainer.from_batch_payloads( c.DefaultContainer.batch_to_payloads(batch, indices) ) == (batch, indices) @pytest.mark.parametrize("batch_dim", [0, 1]) def test_ndarray_container(batch_dim): arr1 = np.ones((3, 3)) if batch_dim == 0: arr2 = np.arange(6).reshape(2, 3) else: arr2 = np.arange(6).reshape(3, 2) batches = [arr1, arr2] batch, indices = c.NdarrayContainer.batches_to_batch(batches, batch_dim=batch_dim) assert (batch == np.concatenate(batches, axis=batch_dim)).all() restored_arr1, restored_arr2 = c.NdarrayContainer.batch_to_batches( batch, indices, batch_dim=batch_dim ) assert (arr1 == restored_arr1).all() assert (arr2 == restored_arr2).all() assert ( c.NdarrayContainer.from_payload(c.NdarrayContainer.to_payload(arr1)) == arr1 ).all() restored_batch, restored_indices = c.NdarrayContainer.from_batch_payloads( c.NdarrayContainer.batch_to_payloads(batch, indices, batch_dim=batch_dim), batch_dim=batch_dim, ) assert restored_indices == indices assert (restored_batch == batch).all() @pytest.mark.parametrize("batch_dim_exc", [AssertionError]) @pytest.mark.parametrize("wrong_batch_dim", [1, 19]) def test_pandas_container(batch_dim_exc, wrong_batch_dim): cols = ["a", "b", "c"] arr1 = np.ones((3, 3)) df1 = pd.DataFrame(arr1, columns=cols) arr2 = np.arange(6, dtype=np.float64).reshape(2, 3) df2 = pd.DataFrame(arr2, columns=cols) batches = [df1, df2] batch, indices = c.PandasDataFrameContainer.batches_to_batch(batches) assert batch.equals(pd.concat(batches, ignore_index=True)) restored_df1, restored_df2 = c.PandasDataFrameContainer.batch_to_batches( batch, indices ) assert df1.equals(restored_df1) assert df2.equals(restored_df2) assert c.PandasDataFrameContainer.from_payload( c.PandasDataFrameContainer.to_payload(df1) ).equals(df1) restored_batch, restored_indices = c.PandasDataFrameContainer.from_batch_payloads( c.PandasDataFrameContainer.batch_to_payloads(batch, indices) ) assert restored_indices == indices assert restored_batch.equals(batch) # PandasDataFrameContainer should only allow batch_dim = 0 with pytest.raises(batch_dim_exc): c.PandasDataFrameContainer.batches_to_batch(batches, batch_dim=wrong_batch_dim) with pytest.raises(batch_dim_exc): c.PandasDataFrameContainer.batch_to_batches( batch, indices, batch_dim=wrong_batch_dim )
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.BaseModel): name: str endpoints: t.List[str] @pytest.mark.parametrize( "exp, model", [ ( { "application/json": { "schema": { "title": "_Schema", "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "endpoints": { "title": "Endpoints", "type": "array", "items": {"type": "string"}, }, }, "required": ["name", "endpoints"], } } }, _Schema, ), ({"application/json": {"schema": {"type": "object"}}}, None), ], ) def test_json_openapi_schema( exp: t.Dict[str, t.Any], model: t.Optional[pydantic.BaseModel] ): assert JSON(pydantic_model=model).openapi_request_schema() == exp assert JSON(pydantic_model=model).openapi_responses_schema() == exp @pytest.mark.parametrize( "exp, mime_type", [ ( { "application/octet-stream": { "schema": {"type": "string", "format": "binary"} } }, None, ), ( {"application/pdf": {"schema": {"type": "string", "format": "binary"}}}, "application/pdf", ), ], ) def test_file_openapi_schema(exp: t.Dict[str, t.Any], mime_type: str): assert File(mime_type=mime_type).openapi_request_schema() == exp assert File(mime_type=mime_type).openapi_responses_schema() == exp @pytest.mark.parametrize( "exp, mime_type", [ ( {"image/jpeg": {"schema": {"type": "string", "format": "binary"}}}, "image/jpeg", ), ( {"image/png": {"schema": {"type": "string", "format": "binary"}}}, "image/png", ), ], ) def test_image_openapi_schema(exp: t.Dict[str, t.Any], mime_type: str): assert Image(mime_type=mime_type).openapi_request_schema() == exp assert Image(mime_type=mime_type).openapi_responses_schema() == exp def test_text_openapi_schema(): exp = {"text/plain": {"schema": {"type": "string"}}} assert Text().openapi_request_schema() == exp assert Text().openapi_responses_schema() == exp @pytest.mark.parametrize( "exp, kwargs", [ ( {"application/json": {"schema": {"type": "object"}}}, {}, ), ( {"application/json": {"schema": {"type": "object"}}}, {"dtype": "int"}, ), ( { "application/json": { "schema": { "type": "object", "properties": { "index": {"type": "array", "items": {"type": "integer"}}, "name": {"type": "array", "items": {"type": "string"}}, }, } } }, { "dtype": {"index": "int64", "name": "str"}, "columns": ["int64", "str"], }, ), ( {"application/octet-stream": {"schema": {"type": "object"}}}, {"default_format": "parquet"}, ), ( {"text/csv": {"schema": {"type": "object"}}}, {"default_format": "csv"}, ), ], ) def test_pandas_openapi_schema(exp: t.Dict[str, t.Any], kwargs: t.Dict[str, t.Any]): assert PandasDataFrame(**kwargs).openapi_request_schema() == exp assert PandasDataFrame(**kwargs).openapi_responses_schema() == exp @pytest.mark.parametrize( "exp, kwargs", [ ({"application/json": {"schema": {"type": "array", "items": {}}}}, {}), ( { "application/json": { "schema": {"type": "array", "items": {"type": "object"}} } }, {"shape": (1,)}, ), ( { "application/json": { "schema": {"type": "array", "items": {"type": "number"}} } }, {"shape": (1,), "dtype": "complex128"}, ), ( { "application/json": { "schema": {"type": "array", "items": {"type": "number"}} } }, {"shape": (1,), "dtype": np.dtype("float32")}, ), ( { "application/json": { "schema": { "type": "array", "items": {"type": "array", "items": {"type": "integer"}}, } } }, {"shape": (3, 2), "dtype": np.dtype("int8")}, ), ], ) def test_numpy_openapi_schema(exp: t.Dict[str, t.Any], kwargs: t.Dict[str, t.Any]): assert NumpyNdarray(**kwargs).openapi_request_schema() == exp assert NumpyNdarray(**kwargs).openapi_responses_schema() == exp def test_multipart_openapi_schema(): array = NumpyNdarray(shape=(3, 2), dtype=np.dtype("float32")) dataframe = PandasDataFrame( dtype={"index": "int64", "name": "str"}, columns=["index", "name"], orient="records", ) exp = { "multipart/form-data": { "schema": { "type": "object", "properties": { "arr": { "type": "array", "items": {"type": "array", "items": {"type": "number"}}, }, "df": { "type": "object", "properties": { "index": {"type": "array", "items": {"type": "integer"}}, "name": {"type": "array", "items": {"type": "string"}}, }, }, }, } } } assert Multipart(arr=array, df=dataframe).openapi_request_schema() == exp assert Multipart(arr=array, df=dataframe).openapi_responses_schema() == exp
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.int32]]", np.array([[1]])) @pytest.mark.parametrize( "obj", [ _ExampleSchema(name="test", endpoints=["predict", "health"]), _Schema(name="test", endpoints=["predict", "health"]), test_arr, ], ) def test_json_encoder( obj: t.Union[ _ExampleSchema, pydantic.BaseModel, "np.ndarray[t.Any, np.dtype[t.Any]]" ] ) -> None: from bentoml._internal.io_descriptors.json import DefaultJsonEncoder dumped = json.dumps( obj, cls=DefaultJsonEncoder, ensure_ascii=False, allow_nan=False, indent=None, separators=(",", ":"), ) assert ( dumped == '{"name":"test","endpoints":["predict","health"]}' or dumped == "[[1]]" )
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_timestamp": str, "id": str}, "memory_usage_percent": Or(int, float), "platform": str, "python_version": str, "total_memory_in_mb": int, "yatai_user_email": Or(str, None), "yatai_version": Or(str, None), "yatai_org_uid": Or(str, None), "yatai_cluster_uid": Or(str, None), "yatai_deployment_uid": Or(str, None), "is_interactive": bool, "in_notebook": bool, }, "event_properties": { "module": str, "model_size_in_kb": Or(float, int), }, "session_id": str, "event_type": And(str, str.islower), } ) def test_get_payload(): event_properties = analytics_lib.schemas.ModelSaveEvent( module="test", model_size_in_kb=123123123, ) payload = analytics_lib.usage_stats.get_payload( event_properties=event_properties, session_id="random_session_id" ) assert SCHEMA.validate(payload) @patch("bentoml._internal.utils.analytics.usage_stats.requests.post") @patch("bentoml._internal.utils.analytics.usage_stats.do_not_track") def test_send_usage(mock_do_not_track, mock_post): event_properties = analytics_lib.schemas.ModelSaveEvent( module="test", model_size_in_kb=123123123, ) mock_do_not_track.return_value = False analytics_lib.track( event_properties, ) assert mock_do_not_track.called assert mock_post.called @patch("bentoml._internal.utils.analytics.usage_stats.requests.post") @patch("bentoml._internal.utils.analytics.usage_stats.do_not_track") def test_do_not_track(mock_do_not_track, mock_post): event_properties = analytics_lib.schemas.ModelSaveEvent( module="test", model_size_in_kb=123123123, ) mock_do_not_track.return_value = True analytics_lib.track( event_properties, ) assert mock_do_not_track.called assert not mock_post.called @patch("bentoml._internal.utils.analytics.usage_stats.logger") @patch("bentoml._internal.utils.analytics.usage_stats.requests.post") @patch("bentoml._internal.utils.analytics.usage_stats.do_not_track") def test_send_usage_failure(mock_do_not_track, mock_post, mock_logger): event_properties = analytics_lib.schemas.ModelSaveEvent( module="test", model_size_in_kb=123123123, ) mock_do_not_track.return_value = False mock_post.side_effect = AssertionError("something went wrong") # nothing should happen analytics_lib.track( event_properties, ) assert mock_do_not_track.called assert mock_post.called mock_logger.debug.assert_called_with("Tracking Error: something went wrong")
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/path"] @pytest.fixture() def example_paths(): if psutil.WINDOWS: return WINDOWS_PATHS else: return POSIX_PATHS def test_uri_path_conversion( example_paths: t.List[str], # pylint: disable=redefined-outer-name ) -> None: from bentoml._internal.utils.uri import path_to_uri from bentoml._internal.utils.uri import uri_to_path for path in example_paths: restored = uri_to_path(path_to_uri(path)) assert restored == path or restored == os.path.abspath(path)
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 BentoMLException from bentoml._internal.models import ModelContext from bentoml._internal.models import ModelOptions as InternalModelOptions from bentoml._internal.models.model import Model from bentoml._internal.models.model import ModelInfo from bentoml._internal.models.model import ModelStore from bentoml._internal.configuration import BENTOML_VERSION if TYPE_CHECKING: from pathlib import Path TEST_MODEL_CONTEXT = ModelContext( framework_name="testing", framework_versions={"testing": "v1"} ) TEST_PYTHON_VERSION = f"{pyver.major}.{pyver.minor}.{pyver.micro}" expected_yaml = """\ name: test version: v1 module: test_model labels: label: stringvalue options: option_a: 1 option_b: foo option_c: - 0.1 - 0.2 metadata: a: 0.1 b: 1 c: - 2 - 3 - 4 context: framework_name: testing framework_versions: testing: v1 bentoml_version: {bentoml_version} python_version: {python_version} signatures: predict: batchable: false classify: batchable: true batch_dim: - 0 - 0 predict_ii: batchable: true batch_dim: - 0 - 3 classify_ii: batchable: true batch_dim: - 1 - 3 api_version: v1 creation_time: '{creation_time}' """ @attr.define class TestModelOptions(InternalModelOptions): option_a: int option_b: str option_c: list[float] ModelOptions = TestModelOptions def test_model_info(tmpdir: "Path"): start = datetime.now(timezone.utc) modelinfo_a = ModelInfo( tag=Tag("tag"), module="module", api_version="v1", labels={}, options=TestModelOptions(option_a=42, option_b="foo", option_c=[0.1, 0.2]), metadata={}, context=TEST_MODEL_CONTEXT, signatures={"predict": {"batchable": True}}, ) end = datetime.now(timezone.utc) assert modelinfo_a.context.bentoml_version == BENTOML_VERSION assert modelinfo_a.context.python_version == TEST_PYTHON_VERSION assert start <= modelinfo_a.creation_time <= end tag = Tag("test", "v1") module = __name__ labels = {"label": "stringvalue"} options = TestModelOptions(option_a=1, option_b="foo", option_c=[0.1, 0.2]) metadata = {"a": 0.1, "b": 1, "c": np.array([2, 3, 4], dtype=np.uint32)} # TODO: add test cases for input_spec and output_spec signatures = { "predict": {"batchable": False}, "classify": {"batchable": True, "batch_dim": (0, 0)}, "predict_ii": {"batchable": True, "batch_dim": (0, 3)}, "classify_ii": {"batchable": True, "batch_dim": (1, 3)}, } modelinfo_b = ModelInfo( tag=tag, module=module, api_version="v1", labels=labels, options=options, metadata=metadata, context=TEST_MODEL_CONTEXT, signatures=signatures, ) model_yaml_b_filename = os.path.join(tmpdir, "b_dump.yml") with open(model_yaml_b_filename, "w", encoding="utf-8") as model_yaml_b: modelinfo_b.dump(model_yaml_b) with open(model_yaml_b_filename, encoding="utf-8") as model_yaml_b: assert model_yaml_b.read() == expected_yaml.format( bentoml_version=BENTOML_VERSION, creation_time=modelinfo_b.creation_time.isoformat(), python_version=TEST_PYTHON_VERSION, ) with open(model_yaml_b_filename, encoding="utf-8") as model_yaml_b: modelinfo_b_from_yaml = ModelInfo.from_yaml_file(model_yaml_b) assert modelinfo_b_from_yaml == modelinfo_b # attempt to test that serialization is deterministic det_check_filename = os.path.join(tmpdir, "det_check.yml") with open(det_check_filename, "a+", encoding="utf-8") as det_check_yaml: modelinfo_b.dump(det_check_yaml) old_info = det_check_yaml.read() # re-flush modelinfo_b.dump(det_check_yaml) assert det_check_yaml.read() == old_info def test_model_creationtime(): start = datetime.now(timezone.utc) model_a = Model.create( "testmodel", module="test", api_version="v1", signatures={}, context=TEST_MODEL_CONTEXT, ) end = datetime.now(timezone.utc) assert model_a.tag.name == "testmodel" assert start <= model_a.creation_time <= end assert str(model_a) == f'Model(tag="{model_a.tag}")' assert repr(model_a) == f'Model(tag="{model_a.tag}", path="{model_a.path}")' class AdditionClass: def __init__(self, x: int): self.x = x def __call__(self, y: int) -> int: return self.x + y add_num_1 = 5 @pytest.fixture(name="bento_model") def fixture_bento_model(): model = Model.create( "testmodel", module=__name__, api_version="v1", signatures={}, context=TEST_MODEL_CONTEXT, options=TestModelOptions(option_a=1, option_b="foo", option_c=[0.1, 0.2]), custom_objects={ "add": AdditionClass(add_num_1), }, ) model.flush() return model def test_model_equal(bento_model): # note: models are currently considered to be equal if their tag is equal; # this is a test of that behavior eq_to_b = Model.create( "tmp", module="bar", api_version="v1", signatures={}, context=TEST_MODEL_CONTEXT ) eq_to_b._tag = bento_model._tag # type: ignore assert eq_to_b == bento_model assert eq_to_b.__hash__() == bento_model.__hash__() def test_model_export_import(bento_model, tmpdir: "Path"): # note: these tests rely on created models having a system path sys_written_path = bento_model.path_of("sys_written/file") assert sys_written_path == os.path.join(bento_model.path, "sys_written", "file") os.makedirs(os.path.dirname(sys_written_path)) sys_written_content = "this is a test\n" with open( sys_written_path, mode="w", encoding="utf-8", newline="" ) as sys_written_file: sys_written_file.write(sys_written_content) with open(bento_model.path_of("sys_written/file"), encoding="utf-8") as f: assert f.read() == sys_written_content export_tar_path = f"tar://{fs.path.join(str(tmpdir), 'model_b.tar')}" bento_model.export(export_tar_path) tar_fs = fs.open_fs(export_tar_path) from_tar_model = Model.from_fs(tar_fs) assert from_tar_model == bento_model assert from_tar_model.info == bento_model.info assert ( from_tar_model._fs.readtext("sys_written/file") # type: ignore == sys_written_content ) assert from_tar_model.custom_objects["add"](4) == add_num_1 + 4 # type: ignore with pytest.raises(fs.errors.NoSysPath): assert from_tar_model.path # tmpdir/modelb.bentomodel export_bentomodel_path = fs.path.join(str(tmpdir), "modelb.bentomodel") bento_model.export(export_bentomodel_path) from_fs_model = Model.from_fs( fs.tarfs.TarFS(export_bentomodel_path, compression="xz") ) # can cause model.path to fail by using `from_fs`. with pytest.raises(fs.errors.NoSysPath): assert from_fs_model.path model_store = ModelStore(tmpdir) from_fs_model.save(model_store) save_path = os.path.join( tmpdir, os.path.join(from_fs_model.tag.name, from_fs_model.tag.version) + os.path.sep, ) assert str(from_fs_model) == f'Model(tag="{bento_model.tag}")' assert repr(from_fs_model) == f'Model(tag="{bento_model.tag}", path="{save_path}")' def test_load_bad_model(tmpdir: "Path"): with pytest.raises(BentoMLException): Model.from_fs(fs.open_fs(os.path.join(tmpdir, "nonexistent"), create=True)) bad_path = os.path.join(tmpdir, "badmodel") os.makedirs(bad_path) with open( os.path.join(bad_path, "model.yaml"), "w", encoding="utf-8", newline="" ) as model_yaml: model_yaml.write("bad yaml") with pytest.raises(BentoMLException): Model.from_fs(fs.open_fs(bad_path))
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._internal.bento.bento import BentoInfo from bentoml._internal.bento.bento import BentoApiInfo from bentoml._internal.bento.bento import BentoModelInfo from bentoml._internal.bento.bento import BentoRunnerInfo from bentoml._internal.configuration import BENTOML_VERSION from bentoml._internal.runner.resource import Resource from bentoml._internal.bento.build_config import BentoBuildConfig if TYPE_CHECKING: from pathlib import Path def test_bento_info(tmpdir: Path): start = datetime.now(timezone.utc) bentoinfo_a = BentoInfo(tag=Tag("tag"), service="service") end = datetime.now(timezone.utc) assert bentoinfo_a.bentoml_version == BENTOML_VERSION assert start <= bentoinfo_a.creation_time <= end # validate should fail tag = Tag("test", "version") service = "testservice" labels = {"label": "stringvalue"} model_creation_time = datetime.now(timezone.utc) model_a = BentoModelInfo( tag=Tag("model_a", "v1"), module="model_a_module", creation_time=model_creation_time, ) model_b = BentoModelInfo( tag=Tag("model_b", "v3"), module="model_b_module", creation_time=model_creation_time, ) models = [model_a, model_b] runner_a = BentoRunnerInfo( name="runner_a", runnable_type="test_runnable_a", models=["runner_a_model"], resource_config=Resource(cpu=2), ) runners = [runner_a] api_predict = BentoApiInfo( name="predict", input_type="NumpyNdarray", output_type="NumpyNdarray", ) apis = [api_predict] bentoinfo_b = BentoInfo( tag=tag, service=service, labels=labels, runners=runners, models=models, apis=apis, ) bento_yaml_b_filename = os.path.join(tmpdir, "b_dump.yml") with open(bento_yaml_b_filename, "w", encoding="utf-8") as bento_yaml_b: bentoinfo_b.dump(bento_yaml_b) expected_yaml = """\ service: testservice name: test version: version bentoml_version: {bentoml_version} creation_time: '{creation_time}' labels: label: stringvalue models: - tag: model_a:v1 module: model_a_module creation_time: '{model_creation_time}' - tag: model_b:v3 module: model_b_module creation_time: '{model_creation_time}' runners: - name: runner_a runnable_type: test_runnable_a models: - runner_a_model resource_config: cpu: 2 apis: - name: predict input_type: NumpyNdarray output_type: NumpyNdarray docker: distro: debian python_version: '{python_version}' cuda_version: null env: {{}} system_packages: [] setup_script: null base_image: null dockerfile_template: null python: requirements_txt: null packages: null lock_packages: true index_url: null no_index: null trusted_host: null find_links: null extra_index_url: null pip_args: null wheels: null conda: environment_yml: null channels: null dependencies: null pip: null """ with open(bento_yaml_b_filename, encoding="utf-8") as bento_yaml_b: assert bento_yaml_b.read() == expected_yaml.format( bentoml_version=BENTOML_VERSION, creation_time=bentoinfo_b.creation_time.isoformat(), model_creation_time=model_creation_time.isoformat(), python_version=f"{version_info.major}.{version_info.minor}", ) with open(bento_yaml_b_filename, encoding="utf-8") as bento_yaml_b: bentoinfo_b_from_yaml = BentoInfo.from_yaml_file(bento_yaml_b) assert bentoinfo_b_from_yaml == bentoinfo_b def build_test_bento(model_store: ModelStore) -> Bento: bento_cfg = BentoBuildConfig( "simplebento.py:svc", include=["*.py", "config.json", "somefile", "*dir*", ".bentoignore"], exclude=[ "*.storage", "/somefile", ], conda={ "environment_yml": "./environment.yaml", }, docker={ "setup_script": "./setup_docker_container.sh", }, labels={ "team": "foo", "dataset_version": "abc", "framework": "pytorch", }, ) return Bento.create(bento_cfg, version="1.0", build_ctx="./simplebento") def fs_identical(fs1: fs.base.FS, fs2: fs.base.FS): for path in fs1.walk.dirs(): assert fs2.isdir(path) for path in fs1.walk.files(): assert fs2.isfile(path) assert fs1.readbytes(path) == fs2.readbytes(path) @pytest.mark.usefixtures("change_test_dir") def test_bento_export(tmpdir: "Path", dummy_model_store: "ModelStore"): working_dir = os.getcwd() testbento = build_test_bento(dummy_model_store) # Bento build will change working dir to the build_context, this will reset it os.chdir(working_dir) cfg = BentoBuildConfig("bentoa.py:svc") bentoa = Bento.create(cfg, build_ctx="./bentoa") # Bento build will change working dir to the build_context, this will reset it os.chdir(working_dir) bentoa1 = Bento.create(cfg, build_ctx="./bentoa1") # Bento build will change working dir to the build_context, this will reset it os.chdir(working_dir) cfg = BentoBuildConfig("bentob.py:svc") bentob = Bento.create(cfg, build_ctx="./bentob") bento = testbento path = os.path.join(tmpdir, "testbento") export_path = bento.export(path) assert export_path == path + ".bento" assert os.path.isfile(export_path) imported_bento = Bento.import_from(export_path) assert imported_bento.tag == bento.tag assert imported_bento.info == bento.info del imported_bento bento = bentoa path = os.path.join(tmpdir, "bentoa") export_path = bento.export(path) assert export_path == path + ".bento" assert os.path.isfile(export_path) imported_bento = Bento.import_from(export_path) assert imported_bento.tag == bento.tag assert imported_bento.info == bento.info del imported_bento bento = bentoa1 path = os.path.join(tmpdir, "bentoa1") export_path = bento.export(path) assert export_path == path + ".bento" assert os.path.isfile(export_path) imported_bento = Bento.import_from(export_path) assert imported_bento.tag == bento.tag assert imported_bento.info == bento.info del imported_bento bento = bentob path = os.path.join(tmpdir, "bentob") export_path = bento.export(path) assert export_path == path + ".bento" assert os.path.isfile(export_path) imported_bento = Bento.import_from(export_path) assert imported_bento.tag == bento.tag assert imported_bento.info == bento.info del imported_bento bento = testbento path = os.path.join(tmpdir, "testbento.bento") export_path = bento.export(path) assert export_path == path assert os.path.isfile(export_path) imported_bento = Bento.import_from(path) assert imported_bento.tag == bento.tag assert imported_bento.info == bento.info del imported_bento path = os.path.join(tmpdir, "testbento-parent") os.mkdir(path) export_path = bento.export(path) assert export_path == os.path.join(path, bento._export_name + ".bento") assert os.path.isfile(export_path) imported_bento = Bento.import_from(export_path) assert imported_bento.tag == bento.tag assert imported_bento.info == bento.info del imported_bento path = os.path.join(tmpdir, "testbento-parent-2/") with pytest.raises(ValueError): export_path = bento.export(path) path = os.path.join(tmpdir, "bento-dir") os.mkdir(path) export_path = bento.export(path) assert export_path == os.path.join(path, bento._export_name + ".bento") assert os.path.isfile(export_path) imported_bento = Bento.import_from(export_path) assert imported_bento.tag == bento.tag assert imported_bento.info == bento.info del imported_bento path = "temp://pytest-some-temp" export_path = bento.export(path) assert export_path.endswith( os.path.join("pytest-some-temp", bento._export_name + ".bento") ) # because this is a tempdir, it's cleaned up immediately after creation... path = "osfs://" + fs.path.join(str(tmpdir), "testbento-by-url") export_path = bento.export(path) assert export_path == os.path.join(tmpdir, "testbento-by-url.bento") assert os.path.isfile(export_path) imported_bento = Bento.import_from(export_path) assert imported_bento.tag == bento.tag assert imported_bento.info == bento.info del imported_bento imported_bento = Bento.import_from(path + ".bento") assert imported_bento.tag == bento.tag assert imported_bento.info == bento.info del imported_bento path = "osfs://" + fs.path.join(str(tmpdir), "testbento-by-url") with pytest.raises(ValueError): bento.export(path, subpath="/badsubpath") path = "zip://" + fs.path.join(str(tmpdir), "testbento.zip") export_path = bento.export(path) assert export_path == path imported_bento = Bento.import_from(export_path) assert imported_bento.tag == bento.tag assert imported_bento.info == bento.info del imported_bento path = os.path.join(tmpdir, "testbento-gz") os.mkdir(path) export_path = bento.export(path, output_format="gz") assert export_path == os.path.join(path, bento._export_name + ".gz") assert os.path.isfile(export_path) imported_bento = Bento.import_from(export_path) assert imported_bento.tag == bento.tag assert imported_bento.info == bento.info del imported_bento path = os.path.join(tmpdir, "testbento-gz-1/") with pytest.raises(ValueError): bento.export(path, output_format="gz") @pytest.mark.usefixtures("change_test_dir") def test_bento(dummy_model_store: ModelStore): start = datetime.now(timezone.utc) bento = build_test_bento(dummy_model_store) end = datetime.now(timezone.utc) assert bento.info.bentoml_version == BENTOML_VERSION assert start <= bento.creation_time <= end # validate should fail with bento._fs as bento_fs: # type: ignore assert set(bento_fs.listdir("/")) == { "bento.yaml", "apis", "models", "README.md", "src", "env", } assert set(bento_fs.listdir("src")) == { "simplebento.py", "subdir", ".bentoignore", } assert set(bento_fs.listdir("src/subdir")) == {"somefile"}
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_data: np.ndarray): # return iris_model_runner.predict(request_data) # For simple use cases, only models list is required: # svc.bento_options.models = [] # svc.bento_files.include = ["*"] # svc.bento_env.pip_install = "./requirements.txt"
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") -> None: parser.addoption( "--runslow", action="store_true", default=False, help="run slow tests" ) parser.addoption( "--gpus", action="store_true", default=False, help="run gpus related tests" ) def pytest_collection_modifyitems(config: "Config", items: t.List["Item"]) -> None: if config.getoption("--gpus"): return skip_gpus = pytest.mark.skip(reason="need --gpus option to run") for item in items: if "gpus" in item.keywords: item.add_marker(skip_gpus) def pytest_sessionstart(session): path = tempfile.mkdtemp("bentoml-pytest") from bentoml._internal.configuration.containers import BentoMLContainer BentoMLContainer.model_store.set(ModelStore(path))
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_activation from tests.utils.frameworks.tensorflow_utils import KerasSequentialModel if TYPE_CHECKING: import tensorflow.keras as keras MODEL_NAME = __name__.split(".")[-1] test_data = [1, 2, 3, 4, 5] res = KerasSequentialModel().predict(np.array([test_data])) def predict_assert_equal(model: "keras.Model") -> None: t_data = np.array([test_data]) assert model.predict(t_data) == res @pytest.mark.parametrize( "model, kwargs", [ ( KerasSequentialModel(), {}, ), ( KerasSequentialModel(), { "custom_objects": { "CustomLayer": CustomLayer, "custom_activation": custom_activation, }, }, ), ], ) def test_keras_save_load( model: "keras.Model", kwargs: t.Dict[str, t.Any], ) -> None: bento_model = bentoml.keras.save_model(MODEL_NAME, model, **kwargs) assert bento_model == bentoml.keras.get(bento_model.tag) assert_have_file_extension(bento_model.path, ".pb") loaded = bentoml.keras.load_model(bento_model.tag) predict_assert_equal(loaded) @pytest.mark.parametrize("signatures", [None, {"__call__": {"batchable": True}}]) def test_keras_run(signatures) -> None: model = KerasSequentialModel() bento_model = bentoml.keras.save_model(MODEL_NAME, model, signatures=signatures) runner = bento_model.to_runner() runner.init_local() # keras model's `__call__` will return a Tensor instead of # ndarray, here we test if we convert the Tensor to ndarray run_res = runner.run([test_data]) assert isinstance(run_res, np.ndarray) assert np.array_equal(run_res, res)
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 = SparkSession.builder.appName(SPARK_SESSION_NAMESPACE).getOrCreate() train_pd_df = pd.DataFrame([[0, -1.0], [1, 1.0]], columns=["label", "feature1"]) test_pd_df = pd.DataFrame([-5.0, 5.0, -0.5, 0.5], columns=["feature1"]) def predict_df(model: pyspark.ml.Model, df: "pd.DataFrame"): spark_df = spark_session.createDataFrame(df) col_labels = [str(c) for c in list(df.columns)] assembler = VectorAssembler(inputCols=col_labels, outputCol="features") spark_df = assembler.transform(spark_df).select(["features"]) output_df = model.transform(spark_df) return output_df.select("prediction").toPandas().prediction.values @pytest.fixture(scope="module") def pyspark_model(): train_sp_df = spark_session.createDataFrame(train_pd_df) assembler = VectorAssembler(inputCols=["feature1"], outputCol="features") train_sp_df = assembler.transform(train_sp_df).select(["features", "label"]) # train model (x=neg -> y=0, x=pos -> y=1) lr = LogisticRegression() model = lr.fit(train_sp_df) return model def test_pyspark_mllib_save_load( tmpdir, pyspark_model ): # pylint: disable=redefined-outer-name PySparkMLlibModel(pyspark_model).save(tmpdir) pyspark_loaded: pyspark.ml.Model = PySparkMLlibModel.load(tmpdir) assert ( predict_df(pyspark_loaded, test_pd_df).tolist() == predict_df(pyspark_model, test_pd_df).tolist() )
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_tests(metafunc: pytest.Metafunc) -> None: framework_name: str = metafunc.config.getoption("framework") # type: ignore if "framework" in metafunc.fixturenames and "test_model" in metafunc.fixturenames: metafunc.parametrize("framework,test_model", test_inputs(framework_name)) elif "framework" in metafunc.fixturenames: metafunc.parametrize( "framework", [inp[0] for inp in test_inputs(framework_name)] ) def test_inputs(framework: str | None) -> list[tuple[ModuleType, FrameworkTestModel]]: if framework is None: frameworks = [ name for _, name, _ in pkgutil.iter_modules( [os.path.join(os.path.dirname(__file__), "models")] ) ] else: frameworks = [framework] input_modules: list[ModuleType] = [] for framework_name in frameworks: try: input_modules.append( import_module( f".{framework_name}", "tests.integration.frameworks.models" ) ) except ModuleNotFoundError as e: raise ModuleNotFoundError( f"Failed to find test module for framework {framework_name} (tests.integration.frameworks.models.{framework_name})" ) from e return [ (module.framework, _model) for module in input_modules for _model in module.models ]
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._internal.runner.resource import Resource from bentoml._internal.runner.runner_handle.local import LocalRunnerRef from .models import FrameworkTestModel def test_wrong_module_load_exc(framework: types.ModuleType): with bentoml.models.create( "wrong_module", module=__name__, context=ModelContext("wrong_module", {"wrong_module": "1.0.0"}), signatures={}, ) as ctx: tag = ctx.tag model = ctx with pytest.raises( NotFound, match=f"Model wrong_module:.* was saved with module {__name__}, " ): framework.get(tag) with pytest.raises( NotFound, match=f"Model wrong_module:.* was saved with module {__name__}, " ): framework.load_model(tag) with pytest.raises( NotFound, match=f"Model wrong_module:.* was saved with module {__name__}, " ): framework.load_model(model) def test_generic_arguments(framework: types.ModuleType, test_model: FrameworkTestModel): # test that the generic save API works from sklearn.preprocessing import StandardScaler # type: ignore (bad sklearn types) scaler: StandardScaler = StandardScaler().fit( # type: ignore (bad sklearn types) [[4], [3], [7], [8], [4], [3], [9], [6]] ) assert scaler.mean_[0] == 5.5 # type: ignore (bad sklearn types) assert scaler.var_[0] == 4.75 # type: ignore (bad sklearn types) kwargs = test_model.save_kwargs.copy() kwargs["signatures"] = { "pytest-signature-rjM5": {"batchable": True, "batch_dim": (1, 0)} } kwargs["labels"] = { "pytest-label-N4nr": "pytest-label-value-4mH7", "pytest-label-7q72": "pytest-label-value-3mDd", } kwargs["custom_objects"] = {"pytest-custom-object-r7BU": scaler} kwargs["metadata"] = { "pytest-metadata-vSW4": [0, 9, 2], "pytest-metadata-qJJ3": "Wy5M", } bento_model = framework.save_model( test_model.name, test_model.model, **kwargs, ) meth = "pytest-signature-rjM5" assert bento_model.info.signatures[meth] == ModelSignature.from_dict(kwargs["signatures"][meth]) # type: ignore assert bento_model.info.labels == kwargs["labels"] # print(bento_model.custom_objects) assert bento_model.custom_objects["pytest-custom-object-r7BU"].mean_[0] == 5.5 assert bento_model.custom_objects["pytest-custom-object-r7BU"].var_[0] == 4.75 assert bento_model.info.metadata == kwargs["metadata"] @pytest.fixture(name="saved_model") def fixture_saved_model( framework: types.ModuleType, test_model: FrameworkTestModel ) -> bentoml.Model: return framework.save_model( test_model.name, test_model.model, **test_model.save_kwargs ) def test_get( framework: types.ModuleType, test_model: FrameworkTestModel, saved_model: bentoml.Model, ): # test that the generic get API works bento_model = framework.get(saved_model.tag) assert bento_model == saved_model assert bento_model.info.name == test_model.name bento_model_from_str = framework.get(str(saved_model.tag)) assert bento_model == bento_model_from_str def test_get_runnable( framework: types.ModuleType, saved_model: bentoml.Model, ): runnable = framework.get_runnable(saved_model) assert isinstance( runnable, t.Type ), "get_runnable for {bento_model.info.name} does not return a type" assert issubclass( runnable, bentoml.Runnable ), "get_runnable for {bento_model.info.name} doesn't return a subclass of bentoml.Runnable" assert ( len(runnable.methods) > 0 ), "get_runnable for {bento_model.info.name} gives a runnable with no methods" def test_load( framework: types.ModuleType, test_model: FrameworkTestModel, saved_model: bentoml.Model, ): for configuration in test_model.configurations: model = framework.load_model(saved_model) configuration.check_model(model, Resource()) for method, inps in configuration.test_inputs.items(): for inp in inps: args = [inp.preprocess(arg) for arg in inp.input_args] kwargs = { key: inp.preprocess(kwarg) for key, kwarg in inp.input_kwargs.items() } out = getattr(model, method)(*args, **kwargs) inp.check_output(out) def test_runner_batching( test_model: FrameworkTestModel, saved_model: bentoml.Tag, ): from bentoml._internal.runner.utils import Params from bentoml._internal.runner.utils import payload_paramss_to_batch_params from bentoml._internal.runner.container import AutoContainer ran_tests = False for config in test_model.configurations: runner = saved_model.with_options(**config.load_kwargs).to_runner() runner.init_local() for meth, inputs in config.test_inputs.items(): if len(inputs) < 2: continue ran_tests = True batch_dim = getattr(runner, meth).config.batch_dim paramss = [ Params(*inp.input_args, **inp.input_kwargs).map( # pylint: disable=cell-var-from-loop # lambda used before loop continues lambda arg: AutoContainer.to_payload(arg, batch_dim=batch_dim[0]) ) for inp in inputs ] params, indices = payload_paramss_to_batch_params(paramss, batch_dim[0]) batch_res = getattr(runner, meth).run(*params.args, **params.kwargs) outps = AutoContainer.batch_to_payloads(batch_res, indices, batch_dim[1]) for i, outp in enumerate(outps): inputs[i].check_output(AutoContainer.from_payload(outp)) runner.destroy() if not ran_tests: pytest.skip( "skipping batching tests because no configuration had multiple test inputs" ) @pytest.mark.gpus def test_runner_nvidia_gpu( framework: types.ModuleType, test_model: FrameworkTestModel, saved_model: bentoml.Tag, ): gpu_resource = Resource(nvidia_gpu=1.0) ran_tests = False for config in test_model.configurations: model_with_options = saved_model.with_options(**config.load_kwargs) runnable = framework.get_runnable(model_with_options) if not runnable.SUPPORT_NVIDIA_GPU: continue ran_tests = True runner = Runner(runnable, nvidia_gpu=1) for meth, inputs in config.test_inputs.items(): # TODO: use strategies to initialize GPU # strategy = DefaultStrategy() # strategy.setup_worker(runnable, gpu_resource) runner.init_local() runner_handle = t.cast(LocalRunnerRef, runner._runner_handle) runnable = runner_handle._runnable if hasattr(runnable, "model") and runnable.model is not None: config.check_model(runner, gpu_resource) for inp in inputs: outp = getattr(runner, meth).run(*inp.input_args, **inp.input_kwargs) inp.check_output(outp) runner.destroy() if not ran_tests: pytest.skip( f"no configurations for model '{test_model.name}' supported running on Nvidia GPU" )
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(124) def tf_gpt2_pipeline(): model = transformers.TFAutoModelForCausalLM.from_pretrained("gpt2") tokenizer = transformers.AutoTokenizer.from_pretrained("gpt2") return transformers.pipeline( task="text-generation", model=model, tokenizer=tokenizer ) def pt_gpt2_pipeline(): model = transformers.AutoModelForCausalLM.from_pretrained("gpt2", from_tf=False) tokenizer = transformers.AutoTokenizer.from_pretrained("gpt2", from_tf=False) return transformers.pipeline( task="text-generation", model=model, tokenizer=tokenizer ) @pytest.mark.parametrize( "name, pipeline, with_options, expected_options, input_data", [ ( "text-generation", transformers.pipeline(task="text-generation"), # type: ignore {}, {"task": "text-generation", "kwargs": {}}, "A Bento box is a ", ), ( "text-generation", transformers.pipeline(task="text-generation"), # type: ignore {"kwargs": {"a": 1}}, {"task": "text-generation", "kwargs": {"a": 1}}, "A Bento box is a ", ), ( "text-generation", tf_gpt2_pipeline(), {}, {"task": "text-generation", "kwargs": {}}, "A Bento box is a ", ), ( "text-generation", pt_gpt2_pipeline(), {}, {"task": "text-generation", "kwargs": {}}, "A Bento box is a ", ), ( "image-classification", transformers.pipeline("image-classification"), # type: ignore {}, {"task": "image-classification", "kwargs": {}}, Image.open( requests.get( "http://images.cocodataset.org/val2017/000000039769.jpg", stream=True, ).raw ), ), ( "text-classification", transformers.pipeline("text-classification"), # type: ignore {}, {"task": "text-classification", "kwargs": {}}, "BentoML is an awesome library for machine learning.", ), ], ) def test_transformers( name: str, pipeline: "ext.TransformersPipelineType", # type: ignore with_options: t.Dict[str, t.Any], expected_options: t.Dict[str, t.Any], input_data: t.Any, ): saved_model = bentoml.transformers.save_model(name, pipeline) assert saved_model is not None assert saved_model.tag.name == name bento_model: bentoml.Model = saved_model.with_options(**with_options) assert bento_model.tag == saved_model.tag assert bento_model.info.context.framework_name == "transformers" assert bento_model.info.options.task == expected_options["task"] # type: ignore assert bento_model.info.options.kwargs == expected_options["kwargs"] # type: ignore runnable: bentoml.Runnable = bentoml.transformers.get_runnable(bento_model)() output_data = runnable(input_data) # type: ignore assert output_data is not None
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.NamedTemporaryFile(suffix=".txt", mode="w+") temp_file.write(contents) temp_file.seek(0) yield temp_file.name temp_file.close() def test_fasttext_save_load(tmpdir): with _temp_filename_with_content("__label__bar foo") as inf: model = fasttext.train_supervised(input=inf) FastTextModel(model).save(tmpdir) assert os.path.isfile(os.path.join(tmpdir, "saved_model")) fasttext_loaded: "fasttext.FastText._FastText" = FastTextModel.load(tmpdir) assert fasttext_loaded.predict(test_json["text"])[0] == ("__label__bar",)
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_integer: t.List[int]): return list(map(lambda x: x**2, some_integer)) def save_test_model( metadata: t.Dict[str, t.Any], labels: t.Optional[t.Dict[str, str]] = None, custom_objects: t.Optional[t.Dict[str, t.Any]] = None, ) -> "Tag": model_to_save = MyCoolModel() bento_model = bentoml.picklable_model.save_model( "test_picklable_model", model_to_save, signatures={ "predict": {"batchable": False}, "batch_predict": {"batchable": True}, }, metadata=metadata, labels=labels, custom_objects=custom_objects, ) return bento_model @pytest.mark.parametrize( "metadata", [({"model": "PicklableModel", "test": True})], ) def test_picklable_model_save_load( metadata: t.Dict[str, t.Any], ) -> None: labels = {"stage": "dev"} def custom_f(x: int) -> int: return x + 1 bentomodel = save_test_model( metadata, labels=labels, custom_objects={"func": custom_f} ) assert bentomodel.info.metadata is not None for k in labels.keys(): assert labels[k] == bentomodel.info.labels[k] assert bentomodel.custom_objects["func"](3) == custom_f(3) loaded_model = bentoml.picklable_model.load_model(bentomodel.tag) assert isinstance(loaded_model, MyCoolModel) assert loaded_model.predict(4) == np.array([16]) def test_picklable_runner() -> None: bento_model = save_test_model({}) runner = bento_model.to_runner() runner.init_local() assert runner.models[0].tag == bento_model.tag assert runner.predict.run(3) == np.array([9]) assert runner.batch_predict.run([3, 9]) == [9, 81] def test_picklable_model_default_signature() -> None: bento_model = bentoml.picklable_model.save_model( "test_pickle_model", lambda x: x**2, metadata={} ) runner = bento_model.to_runner() runner.init_local() assert runner.models[0].tag == bento_model.tag assert runner.run(3) == np.array([9])
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_arr = np.array( [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] ) # fmt: on if TYPE_CHECKING: from bentoml import Tag def save_test_model( metadata: t.Dict[str, t.Any], labels: t.Optional[t.Dict[str, str]] = None, custom_objects: t.Optional[t.Dict[str, t.Any]] = None, ) -> "Tag": model, _ = sklearn_model_data(clf=RandomForestClassifier) tag_info = bentoml.sklearn.save_model( "test_sklearn_model", model, metadata=metadata, labels=labels, custom_objects=custom_objects, ) return tag_info @pytest.mark.parametrize( "metadata", [ ({"model": "Sklearn", "test": True}), ({"acc": 0.876}), ], ) def test_sklearn_save_load(metadata: t.Dict[str, t.Any]) -> None: labels = {"stage": "dev"} def custom_f(x: int) -> int: return x + 1 _, data = sklearn_model_data(clf=RandomForestClassifier) bentomodel = save_test_model( metadata, labels=labels, custom_objects={"func": custom_f} ) assert bentomodel.info.metadata is not None assert_have_file_extension(bentomodel.path, ".pkl") for k in labels.keys(): assert labels[k] == bentomodel.info.labels[k] assert bentomodel.custom_objects["func"](3) == custom_f(3) loaded = bentoml.sklearn.load_model(bentomodel.tag) assert isinstance(loaded, RandomForestClassifier) np.testing.assert_array_equal(loaded.predict(data), res_arr) def test_sklearn_runner() -> None: _, data = sklearn_model_data(clf=RandomForestClassifier) bento_model = save_test_model({}) runner = bento_model.to_runner() runner.init_local() assert runner.models[0].tag == bento_model.tag assert runner.scheduled_worker_count == 1 res = runner.run(data) assert (res == res_arr).all()
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.utils.frameworks.pytorch_utils import LinearModel def get_items(_x): return np.ones([5, 5], np.float32) class Loss(Module): reduction = "none" def forward(self, x, _y): return x def activation(self, x): return x def decodes(self, x): return x def pack_models(path: str) -> None: model = LinearModel() loss = Loss() dblock = DataBlock(get_items=get_items, get_y=np.sum) dls = dblock.datasets(None).dataloaders() learner = Learner(dls, model, loss) FastAIModel(learner).save(path) def predict_df(model: "Learner", df: "pd.DataFrame"): input_df = df.to_numpy().astype(np.float32) _, _, res = model.predict(input_df) return res.squeeze().item() def test_fastai_save_pack(tmpdir): pack_models(tmpdir) assert_have_file_extension(tmpdir, ".pkl") loaded_fastai: "Learner" = FastAIModel.load(tmpdir) assert predict_df(loaded_fastai, test_df) == 5.0
# 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.frameworks.pytorch_utils import ExtendedModel 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 LinearModel # TODO: signatures # TODO: to_payload with plasma @pytest.fixture(scope="module") def model(): return LinearModel() @pytest.fixture(scope="module") def bento_model(model: nn.Module): labels = {"stage": "dev"} def custom_f(x: int) -> int: return x + 1 return bentoml.pytorch.save_model( "pytorch_test", model, labels=labels, custom_objects={"func": custom_f}, ) def test_pytorch_save_load(model: nn.Module): labels = {"stage": "dev"} def custom_f(x: int) -> int: return x + 1 bentomodel = bentoml.pytorch.save_model( "pytorch_test", model, labels=labels, custom_objects={"func": custom_f}, ) assert_have_file_extension(bentomodel.path, ".pt") for k in labels.keys(): assert labels[k] == bentomodel.info.labels[k] assert bentomodel.custom_objects["func"](3) == custom_f(3) pytorch_loaded: nn.Module = bentoml.pytorch.load_model(bentomodel.tag) assert predict_df(pytorch_loaded, test_df) == 5.0 @pytest.mark.gpus @pytest.mark.parametrize("dev", ["cpu", "cuda", "cuda:0"]) def test_pytorch_save_load_across_devices(dev: str, bento_model: bentoml.Model): def is_cuda(model: nn.Module) -> bool: return next(model.parameters()).is_cuda loaded: nn.Module = bentoml.pytorch.load_model(bento_model.tag, device_id=dev) if dev == "cpu": assert not is_cuda(loaded) else: assert is_cuda(loaded) @pytest.mark.parametrize( "input_data", [ test_df.to_numpy().astype(np.float32), torch.from_numpy(test_df.to_numpy().astype(np.float32)), ], ) def test_pytorch_runner_setup_run_batch(input_data, bento_model: bentoml.Model): runner = bento_model.to_runner(cpu=4) assert bento_model.tag in [m.tag for m in runner.models] assert runner.scheduled_worker_count == 1 runner.init_local() res = runner.run(input_data) assert res.unsqueeze(dim=0).item() == 5.0 @pytest.mark.gpus @pytest.mark.parametrize("nvidia_gpu", [1, 2]) def test_pytorch_runner_setup_on_gpu(nvidia_gpu: int, bento_model: bentoml.Model): runner = bento_model.to_runner(nvidia_gpu=nvidia_gpu) assert runner.scheduled_worker_count == nvidia_gpu """ @pytest.mark.parametrize( "bias_pair", [(0.0, 1.0), (-0.212, 1.1392)], ) def test_pytorch_runner_with_partial_kwargs(bias_pair): N, D_in, H, D_out = 64, 1000, 100, 1 x = torch.randn(N, D_in) model = ExtendedModel(D_in, H, D_out) tag = bentoml.pytorch.save_model("pytorch_test_extended", model) bias1, bias2 = bias_pair runner1 = bentoml.pytorch.load_runner(tag, partial_kwargs=dict(bias=bias1)) runner2 = bentoml.pytorch.load_runner(tag, partial_kwargs=dict(bias=bias2)) res1 = runner1.run_batch(x)[0][0].item() res2 = runner2.run_batch(x)[0][0].item() # tensor to float may introduce larger errors, so we bump rel_tol # from 1e-9 to 1e-6 just in case assert math.isclose(res1 - res2, bias1 - bias2, rel_tol=1e-6) """ @pytest.mark.parametrize("batch_axis", [0, 1]) def test_pytorch_container(batch_axis: int): one_batch = torch.arange(6).reshape(2, 3) batch_list = [one_batch, one_batch + 1] merged_batch = torch.cat(batch_list, dim=batch_axis) batches, indices = PyTorchTensorContainer.batches_to_batch( batch_list, batch_dim=batch_axis, ) assert batches.shape == merged_batch.shape assert (batches == merged_batch).all() assert ( PyTorchTensorContainer.batch_to_batches( merged_batch, indices=indices, batch_dim=batch_axis, )[0] == one_batch ).all() assert ( PyTorchTensorContainer.from_payload( PyTorchTensorContainer.to_payload(one_batch) ) == one_batch ).all() assert ( AutoContainer.from_payload(AutoContainer.to_payload(one_batch, batch_dim=0)) == one_batch ).all()
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 LinearModel from tests.utils.frameworks.pytorch_utils import ( make_pytorch_lightning_linear_model_class, ) @pytest.fixture(scope="module") def models(): def _(test_type, labels=None, custom_objects=None): _model: nn.Module = LinearModel() if "trace" in test_type: tracing_inp = torch.ones(5) model = torch.jit.trace(_model, tracing_inp) bento_model = bentoml.torchscript.save_model( "torchscript_test", model, labels=labels, custom_objects=custom_objects, ) elif "script" in test_type: model = torch.jit.script(_model) bento_model = bentoml.torchscript.save_model( "torchscript_test", model, labels=labels, custom_objects=custom_objects, ) elif "pytorch_lightning" in test_type: PlLinearModel = make_pytorch_lightning_linear_model_class() model = PlLinearModel() bento_model = bentoml.pytorch_lightning.save_model( "torchscript_test", model, labels=labels, custom_objects=custom_objects, ) return bento_model return _ @pytest.mark.parametrize( "test_type", ["tracedmodel", "scriptedmodel", "pytorch_lightning"], ) def test_torchscript_save_load(test_type, models): labels = {"stage": "dev"} def custom_f(x: int) -> int: return x + 1 bentomodel = models(test_type, labels=labels, custom_objects={"func": custom_f}) assert_have_file_extension(bentomodel.path, ".pt") for k in labels.keys(): assert labels[k] == bentomodel.info.labels[k] assert bentomodel.custom_objects["func"](3) == custom_f(3) torchscript_loaded: nn.Module = bentoml.torchscript.load_model(bentomodel.tag) assert predict_df(torchscript_loaded, test_df) == 5.0 @pytest.mark.gpus @pytest.mark.parametrize("dev", ["cpu", "cuda", "cuda:0"]) @pytest.mark.parametrize( "test_type", ["tracedmodel", "scriptedmodel", "pytorch_lightning"], ) def test_torchscript_save_load_across_devices(dev, test_type, models): def is_cuda(model): return next(model.parameters()).is_cuda bento_model = models(test_type) loaded = bentoml.torchscript.load_model(bento_model.tag) if dev == "cpu": assert not is_cuda(loaded) else: assert is_cuda(loaded) @pytest.mark.parametrize( "input_data", [ test_df.to_numpy().astype(np.float32), torch.from_numpy(test_df.to_numpy().astype(np.float32)), ], ) @pytest.mark.parametrize( "test_type", ["tracedmodel", "scriptedmodel", "pytorch_lightning"], ) def test_torchscript_runner_setup_run_batch(input_data, models, test_type): bento_model = models(test_type) runner = bento_model.to_runner(cpu=4) assert bento_model.tag in [m.tag for m in runner.models] assert runner.scheduled_worker_count == 1 runner.init_local() res = runner.run(input_data) assert res.unsqueeze(dim=0).item() == 5.0 @pytest.mark.gpus @pytest.mark.parametrize("nvidia_gpu", [1, 2]) @pytest.mark.parametrize( "test_type", ["tracedmodel", "scriptedmodel", "pytorch_lightning"], ) def test_torchscript_runner_setup_on_gpu(nvidia_gpu: int, models, test_type): bento_model = models(test_type) runner = bento_model.to_runner(nvidia_gpu=nvidia_gpu) assert runner.scheduled_worker_count == nvidia_gpu for i in range(nvidia_gpu): runner.setup_worker(i + 1) assert os.environ["CUDA_VISIBLE_DEVICES"] == str(i)
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 MultiInputModel from tests.utils.frameworks.tensorflow_utils import NativeRaggedModel from tests.utils.frameworks.tensorflow_utils import KerasSequentialModel from bentoml._internal.frameworks.tensorflow_v2 import TensorflowTensorContainer if TYPE_CHECKING: from typing import Callable from bentoml._internal.external_typing import tensorflow as tf_ext MODEL_NAME = __name__.split(".")[-1] test_data = [[1.1, 2.2]] test_tensor: "tf_ext.TensorLike" = tf.constant(test_data) native_data = [[1, 2, 3, 4, 5]] native_tensor: "tf_ext.TensorLike" = tf.constant(native_data, dtype=tf.float64) ragged_data = [[15], [7, 8], [1, 2, 3, 4, 5]] ragged_tensor: "tf_ext.TensorLike" = tf.ragged.constant(ragged_data, dtype=tf.float64) def _model_dunder_call( model: "tf_ext.Module", tensor: "tf_ext.TensorLike" ) -> "tf_ext.TensorLike": return model(tensor) def _tensor_equal(t1: "tf_ext.TensorLike", t2: "tf_ext.TensorLike") -> bool: return tf.math.equal(t1, t2).numpy().all() @pytest.mark.parametrize( "mcls, tensor, predict_fn, is_ragged", [ (KerasSequentialModel(), native_tensor, _model_dunder_call, False), (NativeModel(), native_tensor, _model_dunder_call, False), (NativeRaggedModel(), ragged_tensor, _model_dunder_call, True), ], ) def test_tensorflow_v2_save_load( mcls: "tf_ext.Module", tensor: "tf_ext.TensorLike", predict_fn: Callable[ ["tf_ext.AutoTrackable", "tf_ext.TensorLike"], "tf_ext.TensorLike" ], is_ragged: bool, ): labels = {"stage": "dev"} def custom_f(x: int) -> int: return x + 1 bentomodel = bentoml.tensorflow.save_model( MODEL_NAME, mcls, labels=labels, custom_objects={"func": custom_f} ) assert_have_file_extension(bentomodel.path, ".pb") for k in labels.keys(): assert labels[k] == bentomodel.info.labels[k] assert bentomodel.custom_objects["func"](3) == custom_f(3) model = bentoml.tensorflow.load_model(MODEL_NAME) output = predict_fn(model, tensor) if is_ragged: assert all(output.numpy() == np.array([[15.0]] * 3)) else: assert all(output.numpy() == np.array([[15.0]])) def test_tensorflow_v2_setup_run_batch(): model_class = NativeModel() bento_model = bentoml.tensorflow.save_model(MODEL_NAME, model_class) runner = bento_model.to_runner() assert bento_model.tag in [model.tag for model in runner.models] runner.init_local() assert runner.run(native_data) == np.array([[15.0]]) @pytest.mark.gpus def test_tensorflow_v2_setup_on_gpu(): model_class = NativeModel() bento_model = bentoml.tensorflow.save_model(MODEL_NAME, model_class) runner = bento_model.to_runner(nvidia_gpu=1) runner.init_local() # assert runner.num_replica == len(tf.config.list_physical_devices("GPU")) assert runner.run(native_tensor) == np.array([[15.0]]) def test_tensorflow_v2_multi_args(): model_class = MultiInputModel() bento_model = bentoml.tensorflow.save_model(MODEL_NAME, model_class) partial_kwargs1 = {"__call__": {"factor": tf.constant(3.0, dtype=tf.float64)}} runner1 = bento_model.with_options(partial_kwargs=partial_kwargs1).to_runner() partial_kwargs2 = {"__call__": {"factor": tf.constant(2.0, dtype=tf.float64)}} runner2 = bento_model.with_options(partial_kwargs=partial_kwargs2).to_runner() runner1.init_local() runner2.init_local() assert runner1.run(native_data, native_data) == np.array([[60.0]]) assert runner2.run(native_data, native_data) == np.array([[45.0]]) @pytest.mark.parametrize("batch_dim", [0, 1]) def test_tensorflow_container(batch_dim: int): arr1 = np.ones((3, 3)) if batch_dim == 0: arr2 = np.arange(6).reshape(2, 3) else: arr2 = np.arange(6).reshape(3, 2) tensor1: "tf_ext.TensorLike" = tf.convert_to_tensor(arr1, dtype=tf.float32) tensor2: "tf_ext.TensorLike" = tf.convert_to_tensor(arr2, dtype=tf.float32) batches = [tensor1, tensor2] batch, indices = TensorflowTensorContainer.batches_to_batch( batches, batch_dim=batch_dim ) expected_batch: tf.Tensor = tf.concat(batches, axis=batch_dim) assert _tensor_equal(batch, expected_batch) restored_tensor1, restored_tensor2 = TensorflowTensorContainer.batch_to_batches( batch, indices, batch_dim=batch_dim ) assert _tensor_equal(restored_tensor1, tensor1) assert _tensor_equal(restored_tensor2, tensor2) from_payload = TensorflowTensorContainer.from_payload( TensorflowTensorContainer.to_payload(tensor1) ) assert _tensor_equal(from_payload, tensor1) restored_batch, restored_indices = TensorflowTensorContainer.from_batch_payloads( TensorflowTensorContainer.batch_to_payloads( batch, indices, batch_dim=batch_dim ), batch_dim=batch_dim, ) assert restored_indices == indices assert _tensor_equal(restored_batch, batch)
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, "a"], [0, "a"], [0, "a"], [42, "b"], [42, "b"], [42, "b"]]) y = pd.Series([0, 0, 0, 1, 1, 1], name="target") pipeline = evalml.pipelines.BinaryClassificationPipeline( ["Imputer", "One Hot Encoder", "Random Forest Classifier"] ) pipeline.fit(X, y) return pipeline def test_evalml_save_load(tmpdir, binary_pipeline): EvalMLModel(binary_pipeline).save(tmpdir) assert_have_file_extension(tmpdir, ".pkl") evalml_loaded: "evalml.pipelines.PipelineBase" = EvalMLModel.load(tmpdir) assert ( evalml_loaded.predict(test_df).to_numpy() == binary_pipeline.predict(test_df).to_numpy() )
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(__file__).parent MODEL_NAME = __name__.split(".")[-1] # fmt: off res_arr = np.array( [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] ) # fmt: on def test_mlflow_save(): with pytest.raises(BentoMLException): bentoml.mlflow.save() def test_mlflow_save_load(): (model, data) = sklearn_model_data() uri = Path(current_file, "sklearn_clf") if not uri.exists(): mlflow.sklearn.save_model(model, uri.resolve()) tag = bentoml.mlflow.import_from_uri(MODEL_NAME, str(uri.resolve())) model_info = bentoml.models.get(tag) assert_have_file_extension(os.path.join(model_info.path, "sklearn_clf"), ".pkl") loaded = bentoml.mlflow.load(tag) np.testing.assert_array_equal(loaded.predict(data), res_arr) # noqa @pytest.fixture() def invalid_save_with_no_mlmodel(): uri = Path(current_file, "sklearn_clf").resolve() tag = bentoml.mlflow.import_from_uri("sklearn_clf", str(uri)) info = bentoml.models.get(tag) os.remove(str(Path(info.path, "sklearn_clf", "MLmodel").resolve())) return tag def test_invalid_load(invalid_save_with_no_mlmodel): with pytest.raises(FileNotFoundError): _ = bentoml.mlflow.load(invalid_save_with_no_mlmodel) def test_mlflow_load_runner(): (_, data) = sklearn_model_data() uri = Path(current_file, "sklearn_clf").resolve() tag = bentoml.mlflow.import_from_uri(MODEL_NAME, str(uri)) runner = bentoml.mlflow.load_runner(tag) from bentoml._internal.frameworks.mlflow import _PyFuncRunner assert isinstance(runner, _PyFuncRunner) assert tag in runner.required_models assert runner.num_replica == 1 res = runner.run_batch(data) assert all(res == res_arr) @pytest.mark.parametrize( "uri", [ Path(current_file, "SimpleMNIST").resolve(), Path(current_file, "NestedMNIST").resolve(), ], ) def test_mlflow_invalid_import_mlproject(uri): with pytest.raises(BentoMLException): _ = bentoml.mlflow.import_from_uri(MODEL_NAME, str(uri))
# # 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 # pylint: disable=unused-argument # pylint: disable=abstract-method import os from argparse import ArgumentParser import torch import mlflow.pytorch import pytorch_lightning as pl from torch.nn import functional as F from torchvision import datasets from torchvision import transforms from torch.utils.data import DataLoader from torch.utils.data import random_split from pytorch_lightning.callbacks import ModelCheckpoint from pytorch_lightning.callbacks import LearningRateMonitor from pytorch_lightning.metrics.functional import accuracy from pytorch_lightning.callbacks.early_stopping import EarlyStopping class MNISTDataModule(pl.LightningDataModule): def __init__(self, **kwargs): """ Initialization of inherited lightning data module """ super(MNISTDataModule, self).__init__() self.df_train = None self.df_val = None self.df_test = None self.train_data_loader = None self.val_data_loader = None self.test_data_loader = None self.args = kwargs # transforms for images self.transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))] ) def setup(self, stage=None): """ Downloads the data, parses it, and splits the data into training, test, and validation data :param stage: Stage - training or testing """ self.df_train = datasets.MNIST( "dataset", download=True, train=True, transform=self.transform ) self.df_train, self.df_val = random_split(self.df_train, [55000, 5000]) self.df_test = datasets.MNIST( "dataset", download=True, train=False, transform=self.transform ) def create_data_loader(self, df): """ Generic data loader function :param df: Input tensor :return: Returns the constructed dataloader """ return DataLoader( df, batch_size=self.args["batch_size"], num_workers=self.args["num_workers"], ) def train_dataloader(self): """ :return: output - Train data loader for the given input """ return self.create_data_loader(self.df_train) def val_dataloader(self): """ :return: output - Validation data loader for the given input """ return self.create_data_loader(self.df_val) def test_dataloader(self): """ :return: output - Test data loader for the given input """ return self.create_data_loader(self.df_test) class LightningMNISTClassifier(pl.LightningModule): def __init__(self, **kwargs): """ Initializes the network """ super(LightningMNISTClassifier, self).__init__() # mnist images are (1, 28, 28) (channels, width, height) self.optimizer = None self.scheduler = None self.layer_1 = torch.nn.Linear(28 * 28, 128) self.layer_2 = torch.nn.Linear(128, 256) self.layer_3 = torch.nn.Linear(256, 10) self.args = kwargs @staticmethod def add_model_specific_args(parent_parser): parser = ArgumentParser(parents=[parent_parser], add_help=False) parser.add_argument( "--batch_size", type=int, default=64, metavar="N", help="input batch size for training (default: 64)", ) parser.add_argument( "--num_workers", type=int, default=3, metavar="N", help="number of workers (default: 3)", ) parser.add_argument( "--lr", type=float, default=0.001, metavar="LR", help="learning rate (default: 0.001)", ) return parser def forward(self, x): """ :param x: Input data :return: output - mnist digit label for the input image """ batch_size = x.size()[0] # (b, 1, 28, 28) -> (b, 1*28*28) x = x.view(batch_size, -1) # layer 1 (b, 1*28*28) -> (b, 128) x = self.layer_1(x) x = torch.relu(x) # layer 2 (b, 128) -> (b, 256) x = self.layer_2(x) x = torch.relu(x) # layer 3 (b, 256) -> (b, 10) x = self.layer_3(x) # probability distribution over labels x = torch.log_softmax(x, dim=1) return x def cross_entropy_loss(self, logits, labels): """ Initializes the loss function :return: output - Initialized cross entropy loss function """ return F.nll_loss(logits, labels) def training_step(self, train_batch, batch_idx): """ Training the data as batches and returns training loss on each batch :param train_batch: Batch data :param batch_idx: Batch indices :return: output - Training loss """ x, y = train_batch logits = self.forward(x) loss = self.cross_entropy_loss(logits, y) return {"loss": loss} def validation_step(self, val_batch, batch_idx): """ Performs validation of data in batches :param val_batch: Batch data :param batch_idx: Batch indices :return: output - valid step loss """ x, y = val_batch logits = self.forward(x) loss = self.cross_entropy_loss(logits, y) return {"val_step_loss": loss} def validation_epoch_end(self, outputs): """ Computes average validation accuracy :param outputs: outputs after every epoch end :return: output - average valid loss """ avg_loss = torch.stack([x["val_step_loss"] for x in outputs]).mean() self.log("val_loss", avg_loss, sync_dist=True) def test_step(self, test_batch, batch_idx): """ Performs test and computes the accuracy of the model :param test_batch: Batch data :param batch_idx: Batch indices :return: output - Testing accuracy """ x, y = test_batch output = self.forward(x) _, y_hat = torch.max(output, dim=1) test_acc = accuracy(y_hat.cpu(), y.cpu()) return {"test_acc": test_acc} def test_epoch_end(self, outputs): """ Computes average test accuracy score :param outputs: outputs after every epoch end :return: output - average test loss """ avg_test_acc = torch.stack([x["test_acc"] for x in outputs]).mean() self.log("avg_test_acc", avg_test_acc) def configure_optimizers(self): """ Initializes the optimizer and learning rate scheduler :return: output - Initialized optimizer and scheduler """ self.optimizer = torch.optim.Adam(self.parameters(), lr=self.args["lr"]) self.scheduler = { "scheduler": torch.optim.lr_scheduler.ReduceLROnPlateau( self.optimizer, mode="min", factor=0.2, patience=2, min_lr=1e-6, verbose=True, ), "monitor": "val_loss", } return [self.optimizer], [self.scheduler] if __name__ == "__main__": parser = ArgumentParser(description="PyTorch Autolog Mnist Example") # Early stopping parameters parser.add_argument( "--es_monitor", type=str, default="val_loss", help="Early stopping monitor parameter", ) parser.add_argument( "--es_mode", type=str, default="min", help="Early stopping mode parameter" ) parser.add_argument( "--es_verbose", type=bool, default=True, help="Early stopping verbose parameter" ) parser.add_argument( "--es_patience", type=int, default=3, help="Early stopping patience parameter" ) parser = pl.Trainer.add_argparse_args(parent_parser=parser) parser = LightningMNISTClassifier.add_model_specific_args(parent_parser=parser) mlflow.pytorch.autolog() args = parser.parse_args() dict_args = vars(args) if "accelerator" in dict_args: if dict_args["accelerator"] == "None": dict_args["accelerator"] = None model = LightningMNISTClassifier(**dict_args) dm = MNISTDataModule(**dict_args) dm.setup(stage="fit") early_stopping = EarlyStopping( monitor=dict_args["es_monitor"], mode=dict_args["es_mode"], verbose=dict_args["es_verbose"], patience=dict_args["es_patience"], ) checkpoint_callback = ModelCheckpoint( dirpath=os.getcwd(), save_top_k=1, verbose=True, monitor="val_loss", mode="min" ) lr_logger = LearningRateMonitor() trainer = pl.Trainer.from_argparse_args( args, callbacks=[lr_logger, early_stopping, checkpoint_callback], checkpoint_callback=True, ) trainer.fit(model, dm) trainer.test()
# # 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 # pylint: disable=unused-argument # pylint: disable=abstract-method import os from argparse import ArgumentParser import torch import mlflow.pytorch import pytorch_lightning as pl from torch.nn import functional as F from torchvision import datasets from torchvision import transforms from torch.utils.data import DataLoader from torch.utils.data import random_split from pytorch_lightning.callbacks import ModelCheckpoint from pytorch_lightning.callbacks import LearningRateMonitor from pytorch_lightning.metrics.functional import accuracy from pytorch_lightning.callbacks.early_stopping import EarlyStopping class MNISTDataModule(pl.LightningDataModule): def __init__(self, **kwargs): """ Initialization of inherited lightning data module """ super(MNISTDataModule, self).__init__() self.df_train = None self.df_val = None self.df_test = None self.train_data_loader = None self.val_data_loader = None self.test_data_loader = None self.args = kwargs # transforms for images self.transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))] ) def setup(self, stage=None): """ Downloads the data, parse it and split the data into train, test, validation data :param stage: Stage - training or testing """ self.df_train = datasets.MNIST( "dataset", download=True, train=True, transform=self.transform ) self.df_train, self.df_val = random_split(self.df_train, [55000, 5000]) self.df_test = datasets.MNIST( "dataset", download=True, train=False, transform=self.transform ) def create_data_loader(self, df): """ Generic data loader function :param df: Input tensor :return: Returns the constructed dataloader """ return DataLoader( df, batch_size=self.args["batch_size"], num_workers=self.args["num_workers"], ) def train_dataloader(self): """ :return: output - Train data loader for the given input """ return self.create_data_loader(self.df_train) def val_dataloader(self): """ :return: output - Validation data loader for the given input """ return self.create_data_loader(self.df_val) def test_dataloader(self): """ :return: output - Test data loader for the given input """ return self.create_data_loader(self.df_test) class LightningMNISTClassifier(pl.LightningModule): def __init__(self, **kwargs): """ Initializes the network """ super(LightningMNISTClassifier, self).__init__() # mnist images are (1, 28, 28) (channels, width, height) self.optimizer = None self.scheduler = None self.layer_1 = torch.nn.Linear(28 * 28, 128) self.layer_2 = torch.nn.Linear(128, 256) self.layer_3 = torch.nn.Linear(256, 10) self.args = kwargs @staticmethod def add_model_specific_args(parent_parser): parser = ArgumentParser(parents=[parent_parser], add_help=False) parser.add_argument( "--batch_size", type=int, default=64, metavar="N", help="input batch size for training (default: 64)", ) parser.add_argument( "--num_workers", type=int, default=3, metavar="N", help="number of workers (default: 3)", ) parser.add_argument( "--lr", type=float, default=0.001, metavar="LR", help="learning rate (default: 0.001)", ) return parser def forward(self, x): """ :param x: Input data :return: output - mnist digit label for the input image """ batch_size = x.size()[0] # (b, 1, 28, 28) -> (b, 1*28*28) x = x.view(batch_size, -1) # layer 1 (b, 1*28*28) -> (b, 128) x = self.layer_1(x) x = torch.relu(x) # layer 2 (b, 128) -> (b, 256) x = self.layer_2(x) x = torch.relu(x) # layer 3 (b, 256) -> (b, 10) x = self.layer_3(x) # probability distribution over labels x = torch.log_softmax(x, dim=1) return x def cross_entropy_loss(self, logits, labels): """ Initializes the loss function :return: output - Initialized cross entropy loss function """ return F.nll_loss(logits, labels) def training_step(self, train_batch, batch_idx): """ Training the data as batches and returns training loss on each batch :param train_batch: Batch data :param batch_idx: Batch indices :return: output - Training loss """ x, y = train_batch logits = self.forward(x) loss = self.cross_entropy_loss(logits, y) return {"loss": loss} def validation_step(self, val_batch, batch_idx): """ Performs validation of data in batches :param val_batch: Batch data :param batch_idx: Batch indices :return: output - valid step loss """ x, y = val_batch logits = self.forward(x) loss = self.cross_entropy_loss(logits, y) return {"val_step_loss": loss} def validation_epoch_end(self, outputs): """ Computes average validation accuracy :param outputs: outputs after every epoch end :return: output - average valid loss """ avg_loss = torch.stack([x["val_step_loss"] for x in outputs]).mean() self.log("val_loss", avg_loss, sync_dist=True) def test_step(self, test_batch, batch_idx): """ Performs test and computes the accuracy of the model :param test_batch: Batch data :param batch_idx: Batch indices :return: output - Testing accuracy """ x, y = test_batch output = self.forward(x) _, y_hat = torch.max(output, dim=1) test_acc = accuracy(y_hat.cpu(), y.cpu()) return {"test_acc": test_acc} def test_epoch_end(self, outputs): """ Computes average test accuracy score :param outputs: outputs after every epoch end :return: output - average test loss """ avg_test_acc = torch.stack([x["test_acc"] for x in outputs]).mean() self.log("avg_test_acc", avg_test_acc) def configure_optimizers(self): """ Initializes the optimizer and learning rate scheduler :return: output - Initialized optimizer and scheduler """ self.optimizer = torch.optim.Adam(self.parameters(), lr=self.args["lr"]) self.scheduler = { "scheduler": torch.optim.lr_scheduler.ReduceLROnPlateau( self.optimizer, mode="min", factor=0.2, patience=2, min_lr=1e-6, verbose=True, ), "monitor": "val_loss", } return [self.optimizer], [self.scheduler] if __name__ == "__main__": parser = ArgumentParser(description="PyTorch Autolog Mnist Example") # Early stopping parameters parser.add_argument( "--es_monitor", type=str, default="val_loss", help="Early stopping monitor parameter", ) parser.add_argument( "--es_mode", type=str, default="min", help="Early stopping mode parameter" ) parser.add_argument( "--es_verbose", type=bool, default=True, help="Early stopping verbose parameter" ) parser.add_argument( "--es_patience", type=int, default=3, help="Early stopping patience parameter" ) parser = pl.Trainer.add_argparse_args(parent_parser=parser) parser = LightningMNISTClassifier.add_model_specific_args(parent_parser=parser) mlflow.pytorch.autolog() args = parser.parse_args() dict_args = vars(args) if "accelerator" in dict_args: if dict_args["accelerator"] == "None": dict_args["accelerator"] = None model = LightningMNISTClassifier(**dict_args) dm = MNISTDataModule(**dict_args) dm.setup(stage="fit") early_stopping = EarlyStopping( monitor=dict_args["es_monitor"], mode=dict_args["es_mode"], verbose=dict_args["es_verbose"], patience=dict_args["es_patience"], ) checkpoint_callback = ModelCheckpoint( dirpath=os.getcwd(), save_top_k=1, verbose=True, monitor="val_loss", mode="min" ) lr_logger = LearningRateMonitor() trainer = pl.Trainer.from_argparse_args( args, callbacks=[lr_logger, early_stopping, checkpoint_callback], checkpoint_callback=True, ) trainer.fit(model, dm) trainer.test()
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.lightgbm # read in data cancer = load_breast_cancer() # type: ignore (incomplete sklearn types) dt = lgb.basic.Dataset(cancer.data, label=cancer.target) # type: ignore # specify parameters via map param = { "num_leaves": 31, "eta": 0.1, "num_iterations": 20, "objective": "softmax", "num_class": 2, } cancer_model = FrameworkTestModel( name="cancer", model=lgb.train(param, dt), configurations=[ Config( test_inputs={ "predict": [ Input( input_args=[np.array([cancer.data[0]])], expected=lambda out: np.isclose( out, [[0.8152496, 0.1847504]] ).all(), ), Input( input_args=[np.array([cancer.data[1]])], expected=lambda out: np.isclose( out, [[0.92220132, 0.07779868]] ).all(), ), ], }, ), Config( test_inputs={ "predict": [ Input( input_args=[pd.DataFrame([cancer.data[0]])], expected=lambda out: np.isclose( out, [[0.8152496, 0.1847504]] ).all(), ), Input( input_args=[pd.DataFrame([cancer.data[1]])], expected=lambda out: np.isclose( out, [[0.92220132, 0.07779868]] ).all(), ), ], }, ), ], ) models: list[FrameworkTestModel] = [cancer_model]
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.define class FrameworkTestModelConfiguration: test_inputs: dict[str, list[FrameworkTestModelInput]] load_kwargs: dict[str, t.Any] = attr.Factory(dict) check_model: t.Callable[[t.Any, Resource], None] = lambda _, __: None @attr.define class FrameworkTestModelInput: input_args: list[t.Any] expected: t.Any | t.Callable[[t.Any], bool] input_kwargs: dict[str, t.Any] = attr.Factory(dict) preprocess: t.Callable[[t.Any], t.Any] = lambda v: v def check_output(self, outp: t.Any): if isinstance(self.expected, t.Callable): assert self.expected( outp ), f"Output from model call ({', '.join(map(str, self.input_args))}, **{self.input_kwargs}) is not as expected" else: assert ( outp == self.expected ), f"Output from model call ({', '.join(map(str, self.input_args))}, **{self.input_kwargs}) is not as expected"
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 . import FrameworkTestModelConfiguration as Config framework = bentoml.xgboost # read in data cancer = load_breast_cancer() # type: ignore (incomplete sklearn types) dt = xgb.DMatrix(cancer.data, label=cancer.target) # type: ignore # specify parameters via map param = {"max_depth": 3, "eta": 0.3, "objective": "multi:softprob", "num_class": 2} def check_model(bst: xgb.Booster, resource: Resource): config = json.loads(bst.save_config()) if resource.nvidia_gpu is not None and resource.nvidia_gpu > 0: assert config["learner"]["generic_param"]["nthread"] == str(1) elif resource.cpu is not None and resource.cpu > 0: assert config["learner"]["generic_param"]["nthread"] == str(int(resource.cpu)) def close_to(expected): def check_output(out): return np.isclose(out, expected).all() return check_output cancer_model = FrameworkTestModel( name="cancer", model=xgb.train(param, dt), configurations=[ Config( test_inputs={ "predict": [ Input( input_args=[np.array([cancer.data[0]])], expected=close_to([[0.87606, 0.123939]]), preprocess=xgb.DMatrix, ), Input( input_args=[np.array([cancer.data[1]])], expected=close_to([[0.97558, 0.0244234]]), preprocess=xgb.DMatrix, ), ], }, check_model=check_model, ), Config( test_inputs={ "predict": [ Input( input_args=[pd.DataFrame([cancer.data[0]])], expected=close_to([[0.87606, 0.123939]]), preprocess=xgb.DMatrix, ), Input( input_args=[pd.DataFrame([cancer.data[1]])], expected=close_to([[0.97558, 0.0244234]]), preprocess=xgb.DMatrix, ), ], }, check_model=check_model, ), ], ) models: list[FrameworkTestModel] = [cancer_model]
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): return self.linear(x) def make_pytorch_lightning_linear_model_class(): import pytorch_lightning as pl class LightningLinearModel(pl.LightningModule): def __init__(self): super().__init__() self.linear = nn.Linear(5, 1, bias=False) torch.nn.init.ones_(self.linear.weight) def forward(self, x): return self.linear(x) return LightningLinearModel def predict_df(model: nn.Module, df: pd.DataFrame): input_data = df.to_numpy().astype(np.float32) input_tensor = torch.from_numpy(input_data) return model(input_tensor).unsqueeze(dim=0).item() class LinearModelWithBatchAxis(nn.Module): def __init__(self): super(LinearModelWithBatchAxis, self).__init__() self.linear = nn.Linear(5, 1, bias=False) torch.nn.init.ones_(self.linear.weight) def forward(self, x, batch_axis=0): if batch_axis == 1: x = x.permute([1, 0]) res = self.linear(x) if batch_axis == 1: res = res.permute([0, 1]) return res class ExtendedModel(nn.Module): def __init__(self, D_in, H, D_out): """ In the constructor we instantiate two nn.Linear modules and assign them as member variables. """ super(ExtendedModel, self).__init__() self.linear1 = nn.Linear(D_in, H) self.linear2 = nn.Linear(H, D_out) def forward(self, x, bias=0.0): """ In the forward function we accept a Tensor of input data and an optional bias """ h_relu = self.linear1(x).clamp(min=0) y_pred = self.linear2(h_relu) return y_pred + bias
# ============================================================================== # 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ==============================================================================
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.Variable(units, name="units") def call(self, inputs, training=False): if training: return inputs * self.units else: return inputs def get_config(self): config = super(CustomLayer, self).get_config() config.update({"units": self.units.numpy()}) return config def KerasSequentialModel() -> keras.models.Model: net = keras.models.Sequential( ( keras.layers.Dense( units=1, input_shape=(5,), use_bias=False, kernel_initializer=keras.initializers.Ones(), ), ) ) opt = keras.optimizers.Adam(0.002, 0.5) net.compile(optimizer=opt, loss="binary_crossentropy", metrics=["accuracy"]) return net def KerasNLPModel() -> keras.models.Model: from tensorflow.keras.layers.experimental.preprocessing import TextVectorization def custom_standardization(input_data: str) -> tf.Tensor: lowercase = tf.strings.lower(input_data) stripped_html = tf.strings.regex_replace(lowercase, "<br />", " ") return tf.strings.regex_replace( stripped_html, "[%s]" % re.escape(string.punctuation), "" ) max_features = 20000 embedding_dims = 50 vectorize_layer = TextVectorization( standardize=custom_standardization, max_tokens=max_features, output_mode="int", output_sequence_length=400, ) # A text input with preprocessing layers text_input = keras.Input(shape=(1,), dtype=tf.string, name="text") x = vectorize_layer(text_input) x = keras.layers.Embedding(max_features + 1, embedding_dims)(x) x = keras.layers.Dropout(0.2)(x) # Conv1D + global max pooling x = keras.layers.Conv1D(128, 7, padding="valid", activation="relu", strides=1)(x) x = keras.layers.GlobalMaxPooling1D()(x) # We add a vanilla hidden layer: x = keras.layers.Dense(128, activation="relu")(x) x = keras.layers.Dropout(0.2)(x) # We project onto a single unit output layer, and squash it with a sigmoid: predictions = keras.layers.Dense(1, activation="sigmoid", name="predictions")(x) model = keras.Model(text_input, predictions) model.compile(loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"]) return model class NativeModel(tf.Module): def __init__(self): super().__init__() self.weights = np.asfarray([[1.0], [1.0], [1.0], [1.0], [1.0]]) self.dense = lambda inputs: tf.matmul(inputs, self.weights) @tf.function( input_signature=[tf.TensorSpec(shape=[1, 5], dtype=tf.float64, name="inputs")] ) def __call__(self, inputs): return self.dense(inputs) class NativeRaggedModel(NativeModel): @tf.function( input_signature=[ tf.RaggedTensorSpec(tf.TensorShape([None, None]), tf.float64, 1, tf.int64) ] ) def __call__(self, inputs): inputs = inputs.to_tensor(shape=[None, 5], default_value=0) return self.dense(inputs) class MultiInputModel(tf.Module): def __init__(self): super().__init__() self.weights = np.asfarray([[1.0], [1.0], [1.0], [1.0], [1.0]]) self.dense = lambda tensor: tf.matmul(tensor, self.weights) @tf.function( input_signature=[ tf.TensorSpec(shape=[1, 5], dtype=tf.float64, name="x1"), tf.TensorSpec(shape=[1, 5], dtype=tf.float64, name="x2"), tf.TensorSpec(shape=(), dtype=tf.float64, name="factor"), ] ) def __call__(self, x1: tf.Tensor, x2: tf.Tensor, factor: tf.Tensor): return self.dense(x1 + x2 * factor)
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": 0.05743, "mean concavity": 0.03614, "mean concave points": 0.2016, "mean symmetry": 0.05977, "mean fractal dimension": 0.3077, "radius error": 1.621, "texture error": 2.240, "perimeter error": 20.20, "area error": 20.02, "smoothness error": 0.006543, "compactness error": 0.02148, "concavity error": 0.02991, "concave points error": 0.01045, "symmetry error": 0.01844, "fractal dimension error": 0.002690, "worst radius": 12.76, "worst texture": 32.04, "worst perimeter": 83.69, "worst area": 489.5, "worst smoothness": 0.1303, "worst compactness": 0.1696, "worst concavity": 0.1927, "worst concave points": 0.07485, "worst symmetry": 0.2965, "worst fractal dimension": 0.07662, } test_df = pd.DataFrame([test_data]) ModelWithData = namedtuple("ModelWithData", ["model", "data"]) def sklearn_model_data(clf=KNeighborsClassifier, num_data=4) -> ModelWithData: model = clf() iris = load_iris() X = iris.data[:, :num_data] Y = iris.target model.fit(X, Y) return ModelWithData(model=model, data=X)
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, -0.03475696, 0.02682186, -0.37171335, -0.21419304, -0.33569506, 0.10143217, -0.21172912, ] ] ) class LinearModel(nn.Layer): def __init__(self): super(LinearModel, self).__init__() self.fc = nn.Linear(IN_FEATURES, OUT_FEATURES) @paddle.jit.to_static(input_spec=[InputSpec(shape=[IN_FEATURES], dtype="float32")]) def forward(self, x): return self.fc(x)
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 bentoml.io import NumpyNdarray from bentoml.io import PandasDataFrame from bentoml._internal.types import FileLike from bentoml._internal.types import JSONSerializable py_model = bentoml.picklable_model.get("py_model.case-1.e2e").to_runner() svc = bentoml.Service( name="general_workflow_service.case-1.e2e", runners=[py_model], ) @svc.api(input=JSON(), output=JSON()) async def echo_json(json_obj: JSONSerializable) -> JSONSerializable: batch_ret = await py_model.echo_json.async_run([json_obj]) return batch_ret[0] @svc.api(input=JSON(), output=JSON()) def echo_json_sync(json_obj: JSONSerializable) -> JSONSerializable: batch_ret = py_model.echo_json.run([json_obj]) return batch_ret[0] class _Schema(pydantic.BaseModel): name: str endpoints: t.List[str] @svc.api( input=JSON(pydantic_model=_Schema), output=JSON(), ) async def echo_json_enforce_structure(json_obj: JSONSerializable) -> JSONSerializable: batch_ret = await py_model.echo_json.async_run([json_obj]) return batch_ret[0] @svc.api(input=JSON(), output=JSON()) async def echo_obj(obj: JSONSerializable) -> JSONSerializable: return await py_model.echo_obj.async_run(obj) @svc.api( input=NumpyNdarray(shape=(2, 2), enforce_shape=True), output=NumpyNdarray(shape=(2, 2)), ) async def predict_ndarray_enforce_shape( inp: "np.ndarray[t.Any, np.dtype[t.Any]]", ) -> "np.ndarray[t.Any, np.dtype[t.Any]]": assert inp.shape == (2, 2) return await py_model.predict_ndarray.async_run(inp) @svc.api( input=NumpyNdarray(dtype="uint8", enforce_dtype=True), output=NumpyNdarray(dtype="str"), ) async def predict_ndarray_enforce_dtype( inp: "np.ndarray[t.Any, np.dtype[t.Any]]", ) -> "np.ndarray[t.Any, np.dtype[t.Any]]": assert inp.dtype == np.dtype("uint8") return await py_model.predict_ndarray.async_run(inp) @svc.api( input=PandasDataFrame(dtype={"col1": "int64"}, orient="records"), output=PandasDataFrame(), ) async def predict_dataframe(df: "pd.DataFrame") -> "pd.DataFrame": assert df["col1"].dtype == "int64" output = await py_model.predict_dataframe.async_run(df) dfo = pd.DataFrame() dfo["col1"] = output assert isinstance(dfo, pd.DataFrame) return dfo @svc.api(input=File(), output=File()) async def predict_file(f: FileLike[bytes]) -> bytes: batch_ret = await py_model.predict_file.async_run([f]) return batch_ret[0] @svc.api(input=Image(), output=Image(mime_type="image/bmp")) async def echo_image(f: PILImage) -> "np.ndarray[t.Any, np.dtype[t.Any]]": assert isinstance(f, PILImage) return np.array(f) # type: ignore[arg-type] @svc.api( input=Multipart(original=Image(), compared=Image()), output=Multipart(img1=Image(), img2=Image()), ) async def predict_multi_images( original: t.Dict[str, Image], compared: t.Dict[str, Image] ): output_array = await py_model.predict_multi_ndarray.async_run( np.array(original), np.array(compared) ) img = fromarray(output_array) return dict(img1=img, img2=img) # customise the service from starlette.types import Send from starlette.types import Scope from starlette.types import ASGIApp from starlette.types import Receive from starlette.requests import Request class AllowPingMiddleware: def __init__( self, app: ASGIApp, ) -> None: self.app = app async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: if scope["type"] == "http": req = Request(scope, receive) if req.url.path == "/ping": scope["path"] = "/livez" await self.app(scope, receive, send) return svc.add_asgi_middleware(AllowPingMiddleware) # type: ignore[arg-type] from fastapi import FastAPI fastapi_app = FastAPI() @fastapi_app.get("/hello") def hello(): return {"Hello": "World"} svc.mount_asgi_app(fastapi_app)
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": {"batchable": False}, "echo_multi_ndarray": {"batchable": True}, "predict_ndarray": {"batchable": True}, "predict_multi_ndarray": {"batchable": True}, "predict_dataframe": {"batchable": True}, }, ) if __name__ == "__main__": train()
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] @classmethod def echo_json(cls, input_datas: JSONSerializable) -> JSONSerializable: return input_datas @classmethod def echo_obj(cls, input_datas: t.Any) -> t.Any: return input_datas def echo_multi_ndarray( self, *input_arr: "np.ndarray[t.Any, np.dtype[t.Any]]", ) -> t.Tuple["np.ndarray[t.Any, np.dtype[t.Any]]", ...]: return input_arr def predict_ndarray( self, arr: "np.ndarray[t.Any, np.dtype[t.Any]]", ) -> "np.ndarray[t.Any, np.dtype[t.Any]]": assert isinstance(arr, np.ndarray) return arr * 2 def predict_multi_ndarray( self, arr1: "np.ndarray[t.Any, np.dtype[t.Any]]", arr2: "np.ndarray[t.Any, np.dtype[t.Any]]", ) -> "np.ndarray[t.Any, np.dtype[t.Any]]": assert isinstance(arr1, np.ndarray) assert isinstance(arr2, np.ndarray) return (arr1 + arr2) // 2 def predict_dataframe(self, df: "pd.DataFrame") -> "pd.DataFrame": assert isinstance(df, pd.DataFrame) output = df[["col1"]] * 2 # type: ignore assert isinstance(output, pd.DataFrame) return output
# 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("uint8")) img.save(str(img_file_)) return str(img_file_) @pytest.fixture() def bin_file(tmpdir) -> str: bin_file_ = tmpdir.join("bin_file.bin") with open(bin_file_, "wb") as of: of.write("Γ’".encode("gb18030")) return str(bin_file_) def pytest_configure(config): # pylint: disable=unused-argument import sys import subprocess cmd = f"{sys.executable} {os.path.join(os.getcwd(), 'train.py')}" subprocess.run(cmd, shell=True, check=True) # use the local bentoml package in development os.environ["BENTOML_BUNDLE_LOCAL_BUILD"] = "True" @pytest.fixture(scope="session", autouse=True) def clean_context(): stack = contextlib.ExitStack() yield stack stack.close() @pytest.fixture( params=[ "server_config_default.yml", "server_config_cors_enabled.yml", ], scope="session", ) def server_config_file(request): return request.param @pytest.fixture( params=[ # "dev", "standalone", "docker", "distributed", ], scope="session", ) def deployment_mode(request) -> str: return request.param @pytest.fixture(scope="session") def host( deployment_mode: str, server_config_file: str, clean_context: contextlib.ExitStack, ) -> t.Generator[str, None, None]: if ( (psutil.WINDOWS or psutil.MACOS) and os.environ.get("GITHUB_ACTION") and deployment_mode == "docker" ): pytest.skip( "due to GitHub Action's limitation, docker deployment is not supported on " "windows/macos. But you can still run this test on macos/windows locally." ) if not psutil.LINUX and deployment_mode == "distributed": pytest.skip("distributed deployment is only supported on Linux") from bentoml.testing.server import host_bento with host_bento( "service:svc", config_file=server_config_file, deployment_mode=deployment_mode, clean_context=clean_context, ) as host: yield host
# 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 img_file(tmpdir): import PIL.Image img_file_ = tmpdir.join("test_img.bmp") img = PIL.Image.fromarray(np.random.randint(255, size=(10, 10, 3)).astype("uint8")) img.save(str(img_file_)) return str(img_file_) @pytest.fixture() def bin_file(tmpdir): bin_file_ = tmpdir.join("bin_file.bin") with open(bin_file_, "wb") as of: of.write("Γ’".encode("gb18030")) return str(bin_file_) @pytest.mark.asyncio async def test_numpy(host): await async_request( "POST", f"http://{host}/predict_ndarray_enforce_shape", headers={"Content-Type": "application/json"}, data="[[1,2],[3,4]]", assert_status=200, assert_data=b"[[2, 4], [6, 8]]", ) await async_request( "POST", f"http://{host}/predict_ndarray_enforce_shape", headers={"Content-Type": "application/json"}, data="[1,2,3,4]", assert_status=400, ) await async_request( "POST", f"http://{host}/predict_ndarray_enforce_dtype", headers={"Content-Type": "application/json"}, data="[[2,1],[4,3]]", assert_status=200, assert_data=b'[["4", "2"], ["8", "6"]]', ) await async_request( "POST", f"http://{host}/predict_ndarray_enforce_dtype", headers={"Content-Type": "application/json"}, data='[["2f",1],[4,3]]', assert_status=400, ) @pytest.mark.asyncio async def test_json(host): ORIGIN = "http://bentoml.ai" await async_request( "POST", f"http://{host}/echo_json", headers=(("Content-Type", "application/json"), ("Origin", ORIGIN)), data='"hi"', assert_status=200, assert_data=b'"hi"', ) await async_request( "POST", f"http://{host}/echo_json_sync", headers=(("Content-Type", "application/json"), ("Origin", ORIGIN)), data='"hi"', assert_status=200, assert_data=b'"hi"', ) await async_request( "POST", f"http://{host}/echo_json_enforce_structure", headers=(("Content-Type", "application/json"), ("Origin", ORIGIN)), data='{"name":"test","endpoints":["predict","health"]}', assert_status=200, assert_data=b'{"name":"test","endpoints":["predict","health"]}', ) @pytest.mark.asyncio async def test_obj(host): for obj in [1, 2.2, "str", [1, 2, 3], {"a": 1, "b": 2}]: obj_str = json.dumps(obj, separators=(",", ":")) await async_request( "POST", f"http://{host}/echo_obj", headers=(("Content-Type", "application/json"),), data=obj_str, assert_status=200, assert_data=obj_str.encode("utf-8"), ) @pytest.mark.asyncio async def test_pandas(host): import pandas as pd ORIGIN = "http://bentoml.ai" df = pd.DataFrame([[101]], columns=["col1"]) await async_request( "POST", f"http://{host}/predict_dataframe", headers=(("Content-Type", "application/json"), ("Origin", ORIGIN)), data=df.to_json(orient="records"), assert_status=200, assert_data=b'[{"col1":202}]', ) # pyarrow only support python 3.7+ if sys.version_info >= (3, 7): await async_request( "POST", f"http://{host}/predict_dataframe", headers=(("Content-Type", "application/octet-stream"), ("Origin", ORIGIN)), data=df.to_parquet(), assert_status=200, assert_data=b'[{"col1":202}]', ) await async_request( "POST", f"http://{host}/predict_dataframe", headers=(("Content-Type", "text/csv"), ("Origin", ORIGIN)), data=df.to_csv(), assert_status=200, assert_data=b'[{"col1":202}]', ) @pytest.mark.asyncio async def test_file(host, bin_file): # Test File as binary with open(str(bin_file), "rb") as f: b = f.read() await async_request( "POST", f"http://{host}/predict_file", data=b, headers={"Content-Type": "application/octet-stream"}, assert_data=b"\x810\x899", ) # Test File as multipart binary form = aiohttp.FormData() form.add_field("file", b, content_type="application/octet-stream") await async_request( "POST", f"http://{host}/predict_file", data=form, assert_data=b"\x810\x899", ) # Test Exception await async_request( "POST", f"http://{host}/predict_file", data=b, headers={"Content-Type": "application/pdf"}, assert_status=500, ) @pytest.mark.asyncio async def test_image(host, img_file): import PIL.Image with open(str(img_file), "rb") as f1: img_bytes = f1.read() status, headers, body = await async_request( "POST", f"http://{host}/echo_image", data=img_bytes, headers={"Content-Type": "image/bmp"}, ) assert status == 200 assert headers["Content-Type"] == "image/bmp" bio = io.BytesIO(body) bio.name = "test.bmp" img = PIL.Image.open(bio) array1 = np.array(img) array2 = PIL.Image.open(img_file) np.testing.assert_array_almost_equal(array1, array2) await async_request( "POST", f"http://{host}/echo_image", data=img_bytes, headers={"Content-Type": "application/json"}, assert_status=400, ) # Test Exception with open(str(img_file), "rb") as f1: b = f1.read() await async_request( "POST", f"http://{host}/echo_image", data=b, headers={"Content-Type": "application/pdf"}, assert_status=400, ) # SklearnRunner is not suppose to take multiple arguments # TODO: move e2e tests to use a new bentoml.PickleModel module @pytest.mark.skip @pytest.mark.asyncio async def test_multipart_image_io(host, img_file): import PIL.Image from starlette.datastructures import UploadFile with open(img_file, "rb") as f1: with open(img_file, "rb") as f2: form = aiohttp.FormData() form.add_field("original", f1.read(), content_type="image/bmp") form.add_field("compared", f2.read(), content_type="image/bmp") status, headers, body = await async_request( "POST", f"http://{host}/predict_multi_images", data=form, ) assert status == 200 form = await parse_multipart_form(headers=headers, body=body) for _, v in form.items(): assert isinstance(v, UploadFile) img = PIL.Image.open(v.file) assert np.array(img).shape == (10, 10, 3)
# 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_start = time.time() req_count = 10 tasks = tuple( pytest.async_request( "POST", f"http://{host}/echo_with_delay", headers=(("Content-Type", "application/json"),), data=data, timeout=30, assert_status=200, assert_data=data.encode(), ) for i in range(req_count) ) await asyncio.gather(*tasks) assert time.time() - time_start < 12 @pytest.mark.skipif(not psutil.POSIX, reason="production server only works on POSIX") @pytest.mark.asyncio async def test_fast_server(host): A, B = 0.0002, 0.01 data = '{"a": %s, "b": %s}' % (A, B) req_count = 100 tasks = tuple( pytest.async_request( "POST", f"http://{host}/echo_with_delay", headers=(("Content-Type", "application/json"),), data=data, assert_status=lambda i: i in (200, 429), ) for i in range(req_count) ) await asyncio.gather(*tasks) time_start = time.time() req_count = 200 tasks = tuple( pytest.async_request( "POST", f"http://{host}/echo_with_delay", headers=(("Content-Type", "application/json"),), data=data, timeout=30, assert_status=200, assert_data=data.encode(), ) for i in range(req_count) ) await asyncio.gather(*tasks) assert time.time() - time_start < 2 @pytest.mark.skipif(not psutil.POSIX, reason="production server only works on POSIX") @pytest.mark.asyncio async def test_batch_size_limit(host): A, B = 0.0002, 0.01 data = '{"a": %s, "b": %s}' % (A, B) # test for max_batch_size=None tasks = tuple( pytest.async_request( "POST", f"http://{host}/echo_batch_size", headers=(("Content-Type", "application/json"),), data=data, assert_status=lambda i: i in (200, 429), ) for _ in range(100) ) await asyncio.gather(*tasks) await asyncio.sleep(1) batch_bucket = [] tasks = tuple( pytest.async_request( "POST", f"http://{host}/echo_batch_size", headers=(("Content-Type", "application/json"),), data=data, assert_status=200, assert_data=lambda d: ( d == b"429: Too Many Requests" or batch_bucket.append(int(d.decode())) or True ), ) for _ in range(50) ) await asyncio.gather(*tasks) # batch size could be dynamic because of the bentoml_config.yml # microbatch.max_batch_size=Null assert any(b > 1 for b in batch_bucket), batch_bucket """
# 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, _, _ = await async_request("GET", f"http://{host}/healthz") assert status == 200 status, _, _ = await async_request("GET", f"http://{host}/livez") assert status == 200 status, _, _ = await async_request("GET", f"http://{host}/ping") assert status == 200 status, _, body = await async_request("GET", f"http://{host}/hello") assert status == 200 assert b'{"Hello":"World"}' == body status, _, _ = await async_request("GET", f"http://{host}/docs.json") assert status == 200 status, _, _ = await async_request("GET", f"http://{host}/readyz") assert status == 200 status, _, body = await async_request("GET", f"http://{host}/metrics") assert status == 200 assert body @pytest.mark.asyncio async def test_cors(host: str, server_config_file: str) -> None: ORIGIN = "http://bentoml.ai" status, headers, body = await async_request( "OPTIONS", f"http://{host}/echo_json", headers={ "Content-Type": "application/json", "Origin": ORIGIN, "Access-Control-Request-Method": "POST", "Access-Control-Request-Headers": "Content-Type", }, ) if server_config_file == "server_config_cors_enabled.yml": assert status == 200 else: assert status != 200 status, headers, body = await async_request( "POST", f"http://{host}/echo_json", headers={"Content-Type": "application/json", "Origin": ORIGIN}, data='"hi"', ) if server_config_file == "server_config_cors_enabled.yml": assert status == 200 assert body == b'"hi"' assert headers["Access-Control-Allow-Origin"] in ("*", ORIGIN) assert "Content-Length" in headers.get("Access-Control-Expose-Headers", []) assert "Server" not in headers.get("Access-Control-Expect-Headers", []) else: assert status == 200 assert headers.get("Access-Control-Allow-Origin") not in ("*", ORIGIN) assert "Content-Length" not in headers.get("Access-Control-Expose-Headers", []) """ @pytest.since_bentoml_version("0.11.0+0") @pytest.mark.asyncio async def test_customized_route(host): CUSTOM_ROUTE = "$~!@%^&*()_-+=[]\\|;:,./predict" def path_in_docs(response_body): d = json.loads(response_body.decode()) return f"/{CUSTOM_ROUTE}" in d['paths'] await async_request( "GET", f"http://{host}/docs.json", headers=(("Content-Type", "application/json"),), assert_data=path_in_docs, ) await async_request( "POST", f"http://{host}/{CUSTOM_ROUTE}", headers=(("Content-Type", "application/json"),), data=json.dumps("hello"), assert_data=bytes('"hello"', 'ascii'), ) @pytest.mark.asyncio async def test_customized_request_schema(host): def has_customized_schema(doc_bytes): json_str = doc_bytes.decode() return "field1" in json_str await async_request( "GET", f"http://{host}/docs.json", headers=(("Content-Type", "application/json"),), assert_data=has_customized_schema, ) @pytest.mark.asyncio @pytest.mark.parametrize( "metrics", [ pytest.param( '_mb_request_duration_seconds_count', marks=pytest.mark.skipif( psutil.MACOS, reason="microbatch metrics is not shown in MacOS tests" ), ), pytest.param( '_mb_request_total', marks=pytest.mark.skipif( psutil.MACOS, reason="microbatch metrics is not shown in MacOS tests" ), ), '_request_duration_seconds_bucket', ], ) async def test_api_server_metrics(host, metrics): await async_request( "POST", f"http://{host}/echo_json", data='"hi"', ) await async_request( "GET", f"http://{host}/metrics", assert_status=200, assert_data=lambda d: metrics in d.decode(), ) """
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__ # -- General configuration --------------------------------------------------- source_suffix = [".rst", ".md"] # See https://github.com/readthedocs/readthedocs.org/issues/2149 master_doc = "index" # Sphinx extensions extensions = [ "sphinxext.opengraph", "sphinx.ext.autodoc", "sphinx.ext.autosectionlabel", "sphinx.ext.napoleon", "sphinx.ext.todo", "sphinx.ext.viewcode", "sphinx.ext.ifconfig", "sphinx_click.ext", "sphinx_copybutton", "sphinx_design", "sphinx_issues", "sphinxcontrib.spelling", "myst_parser", "sphinx_inline_tabs", ] # Plugin Configurations: napoleon_include_private_with_doc = False napoleon_numpy_docstring = False napoleon_include_special_with_doc = False autosectionlabel_prefix_document = True autosectionlabel_maxdepth = 10 ogp_site_url = "http://docs.bentoml.org" ogp_image = "https://docs.bentoml.org/en/latest/_images/bentoml-readme-header.jpeg" ogp_site_name = "BentoML Documentation" ogp_use_first_image = True issues_default_group_project = "bentoml/bentoml" todo_include_todos = True autodoc_typehints = "description" autodoc_typehints_description_target = "documented" # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] # The name of the Pygments (syntax highlighting) style to use. pygments_style = "zenburn" pygments_dark_style = "monokai" myst_enable_extensions = ["colon_fence"] # Remove the prompt when copying examples copybutton_prompt_text = r">>> |\.\.\.|» |$ |% " copybutton_prompt_is_regexp = True # -- Options for HTML output ------------------------------------------------- html_theme = "furo" html_theme_options = { "light_css_variables": { "color-brand-primary": "#44a4c6 ", "color-brand-content": "#44a4c6 ", }, "dark_css_variables": { "color-brand-primary": "#c9378a ", "color-brand-content": "#c9378a ", }, "source_repository": "https://github.com/bentoml/bentoml/", "source_branch": "main", "source_directory": "docs/source/", "footer_icons": [ { "name": "GitHub", "url": "https://github.com/bentoml/bentoml", "html": " 🍱 ", "class": "", }, ], } html_title = "BentoML" html_logo = "_static/img/logo.svg" html_static_path = ["_static"] html_css_files = ["css/custom.css"] html_js_files = ["js/custom.js"] html_show_sphinx = False html_favicon = "_static/img/favicon-32x32.ico" # Private dictionary for spell checker spelling_word_list_filename = ["bentoml_wordlist.txt"] # mock any heavy imports, eg: imports from frameworks library autodoc_mock_imports = [ "catboost", "coremltools", "detectron2", "detectron2.config", "detectron2.modeling", "detectron2.checkpoint", "torch", "torchvision", "torchtext", "easyocr", "evalml", "fastai", "fasttext", "mxnet", "mxnet.gluon", "h2o", "h2o.model", "tensorflow", "tensorflow.keras", "tensorflow.python.client", "tensorflow.python.training.tracking.tracking", "tensorflow_hub", "keras", "trax", "flax", "jax", "lightgbm", "mlflow", "mlflow.pyfunc", "mlflow.tracking.artifact_utils", "onnx", "onnxruntime", "PyRuntime", "paddle", "paddle.nn", "paddle.inference", "paddle.fluid", "paddlehub", "paddlehub.module.manager", "paddlehub.server.server", "pycaret", "pycaret.internal.tabular", "pyspark", "pytorch", "torch.nn.parallel", "pytorch_lightning", "sklearn", "joblib", "spacy", "spacy.util", "thinc.util", "thinc.backends", "statsmodels", "statsmodels.api", "statsmodels.tools.parallel", "transformers", "transformers.file_utils", "xgboost", ]
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( f'The "{__name__}.save" method is being deprecated. Use "{__name__}.save_model" instead' ) return save_model(tag, *args, **kwargs) def load(tag, *args, **kwargs): logger.warning( f'The "{__name__}.load" method is being deprecated. Use "{__name__}.load_model" instead' ) return load_model(tag, *args, **kwargs) def load_runner(tag, *args, **kwargs): if len(args) != 0 or len(kwargs) != 0: logger.error( f'The "{__name__}.load_runner" method is being deprecated. "load_runner" arguments will be ignored. Use `{__name__}.get("{tag}").to_runner()` instead' ) else: logger.warning( f'The "{__name__}.load_runner" method is being deprecated. Use `{__name__}.get("{tag}").to_runner()` instead' ) return get(tag).to_runner() __all__ = ["load_model", "save_model", "get", "get_runnable"]
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 import ModelContext from ._internal.models import ModelOptions from ._internal.utils.analytics import track from ._internal.utils.analytics import ModelSaveEvent from ._internal.configuration.containers import BentoMLContainer if TYPE_CHECKING: from ._internal.models import ModelStore from ._internal.models.model import ModelSignaturesType @inject def list( # pylint: disable=redefined-builtin tag: t.Optional[t.Union[Tag, str]] = None, *, _model_store: "ModelStore" = Provide[BentoMLContainer.model_store], ) -> t.List["Model"]: return _model_store.list(tag) @inject def get( tag: t.Union[Tag, str], *, _model_store: "ModelStore" = Provide[BentoMLContainer.model_store], ) -> "Model": return _model_store.get(tag) @inject def delete( tag: t.Union[Tag, str], *, _model_store: "ModelStore" = Provide[BentoMLContainer.model_store], ): _model_store.delete(tag) @inject def import_model( path: str, input_format: t.Optional[str] = None, *, protocol: t.Optional[str] = None, user: t.Optional[str] = None, passwd: t.Optional[str] = None, params: t.Optional[t.Dict[str, str]] = None, subpath: t.Optional[str] = None, _model_store: "ModelStore" = Provide[BentoMLContainer.model_store], ) -> Model: """ Import a bento model exported with :code:`bentoml.models.export_model`. To import a model saved with a framework, see the :code:`save` function under the relevant framework, e.g. :code:`bentoml.sklearn.save`. Examples: .. code-block:: python # imports 'my_model' from '/path/to/folder/my_model.bentomodel' bentoml.models.import_model('/path/to/folder/my_model.bentomodel') # imports 'my_model' from '/path/to/folder/my_model.tar.gz' # currently supported formats are tar.gz ('gz'), tar.xz ('xz'), tar.bz2 ('bz2'), and zip bentoml.models.import_model('/path/to/folder/my_model.tar.gz') # treats 'my_model.ext' as a gzipped tarfile bentoml.models.import_model('/path/to/folder/my_model.ext', 'gz') # imports 'my_model', which is stored as an uncompressed folder, from '/path/to/folder/my_model/' bentoml.models.import_model('/path/to/folder/my_model', 'folder') # imports 'my_model' from the S3 bucket 'my_bucket', path 'folder/my_model.bentomodel' # requires `fs-s3fs <https://pypi.org/project/fs-s3fs/>`_ ('pip install fs-s3fs') bentoml.models.import_model('s3://my_bucket/folder/my_model.bentomodel') bentoml.models.import_model('my_bucket/folder/my_model.bentomodel', protocol='s3') bentoml.models.import_model('my_bucket', protocol='s3', subpath='folder/my_model.bentomodel') bentoml.models.import_model('my_bucket', protocol='s3', subpath='folder/my_model.bentomodel', user='<AWS access key>', passwd='<AWS secret key>', params={'acl': 'public-read', 'cache-control': 'max-age=2592000,public'}) For a more comprehensive description of what each of the keyword arguments (:code:`protocol`, :code:`user`, :code:`passwd`, :code:`params`, and :code:`subpath`) mean, see the `FS URL documentation <https://docs.pyfilesystem.org/en/latest/openers.html>`_. Args: tag: the tag of the model to export path: can be one of two things: * a folder on the local filesystem * an `FS URL <https://docs.pyfilesystem.org/en/latest/openers.html>`_, for example :code:`'s3://my_bucket/folder/my_model.bentomodel'` protocol: (expert) The FS protocol to use when exporting. Some example protocols are :code:`'ftp'`, :code:`'s3'`, and :code:`'userdata'` user: (expert) the username used for authentication if required, e.g. for FTP passwd: (expert) the username used for authentication if required, e.g. for FTP params: (expert) a map of parameters to be passed to the FS used for export, e.g. :code:`{'proxy': 'myproxy.net'}` for setting a proxy for FTP subpath: (expert) the path inside the FS that the model should be exported to _model_store: the model store to save the model to Returns: Model: the imported model """ return Model.import_from( path, input_format, protocol=protocol, user=user, passwd=passwd, params=params, subpath=subpath, ).save(_model_store) @inject def export_model( tag: t.Union[Tag, str], path: str, output_format: t.Optional[str] = None, *, protocol: t.Optional[str] = None, user: t.Optional[str] = None, passwd: t.Optional[str] = None, params: t.Optional[t.Dict[str, str]] = None, subpath: t.Optional[str] = None, _model_store: "ModelStore" = Provide[BentoMLContainer.model_store], ) -> str: """ Export a BentoML model. Examples: .. code-block:: python # exports 'my_model' to '/path/to/folder/my_model-version.bentomodel' in BentoML's default format bentoml.models.export_model('my_model:latest', '/path/to/folder') # note that folders can only be passed if exporting to the local filesystem; otherwise the # full path, including the desired filename, must be passed # exports 'my_model' to '/path/to/folder/my_model.bentomodel' in BentoML's default format bentoml.models.export_model('my_model:latest', '/path/to/folder/my_model') bentoml.models.export_model('my_model:latest', '/path/to/folder/my_model.bentomodel') # exports 'my_model' to '/path/to/folder/my_model.tar.gz in gzip format # currently supported formats are tar.gz ('gz'), tar.xz ('xz'), tar.bz2 ('bz2'), and zip bentoml.models.export_model('my_model:latest', '/path/to/folder/my_model.tar.gz') bentoml.models.export_model('my_model:latest', '/path/to/folder/my_model.tar.gz', 'gz') # exports 'my_model' to '/path/to/folder/my_model/ as a folder bentoml.models.export_model('my_model:latest', '/path/to/folder/my_model', 'folder') # exports 'my_model' to the S3 bucket 'my_bucket' as 'folder/my_model-version.bentomodel' bentoml.models.export_model('my_model:latest', 's3://my_bucket/folder') bentoml.models.export_model('my_model:latest', 'my_bucket/folder', protocol='s3') bentoml.models.export_model('my_model:latest', 'my_bucket', protocol='s3', subpath='folder') bentoml.models.export_model('my_model:latest', 'my_bucket', protocol='s3', subpath='folder', user='<AWS access key>', passwd='<AWS secret key>', params={'acl': 'public-read', 'cache-control': 'max-age=2592000,public'}) For a more comprehensive description of what each of the keyword arguments (:code:`protocol`, :code:`user`, :code:`passwd`, :code:`params`, and :code:`subpath`) mean, see the `FS URL documentation <https://docs.pyfilesystem.org/en/latest/openers.html>`_. Args: tag: the tag of the model to export path: can be one of two things: * a folder on the local filesystem * an `FS URL <https://docs.pyfilesystem.org/en/latest/openers.html>`_, for example, :code:`'s3://my_bucket/folder/my_model.bentomodel'` protocol: (expert) The FS protocol to use when exporting. Some example protocols are :code:`'ftp'`, :code:`'s3'`, and :code:`'userdata'`. user: (expert) the username used for authentication if required, e.g. for FTP passwd: (expert) the username used for authentication if required, e.g. for FTP params: (expert) a map of parameters to be passed to the FS used for export, e.g. :code:`{'proxy': 'myproxy.net'}` for setting a proxy for FTP subpath: (expert) the path inside the FS that the model should be exported to _model_store: the model store to get the model to save from Returns: str: A representation of the path that the model was exported to. If it was exported to the local filesystem, this will be the OS path to the exported model. Otherwise, it will be an FS URL. """ model = get(tag, _model_store=_model_store) return model.export( path, output_format, protocol=protocol, user=user, passwd=passwd, params=params, subpath=subpath, ) def push( tag: t.Union[Tag, str], *, _model_store: "ModelStore" = Provide[BentoMLContainer.model_store], ): raise NotImplementedError def pull( tag: t.Union[Tag, str], *, _model_store: "ModelStore" = Provide[BentoMLContainer.model_store], ) -> Model: raise NotImplementedError @inject @contextmanager def create( name: str, *, module: str = "", api_version: str | None = None, signatures: ModelSignaturesType, labels: dict[str, t.Any] | None = None, options: ModelOptions | None = None, custom_objects: dict[str, t.Any] | None = None, metadata: dict[str, t.Any] | None = None, context: ModelContext, _model_store: ModelStore = Provide[BentoMLContainer.model_store], ) -> t.Generator[Model, None, None]: options = ModelOptions() if options is None else options api_version = "v1" if api_version is None else api_version res = Model.create( name, module=module, api_version=api_version, labels=labels, signatures=signatures, options=options, custom_objects=custom_objects, metadata=metadata, context=context, ) try: yield res finally: res.flush() res.save(_model_store) track( ModelSaveEvent( module=res.info.module, model_size_in_kb=calc_dir_size(res.path_of("/")) / 1024, ), ) __all__ = [ "list", "get", "delete", "import_model", "export_model", "push", "pull", "ModelContext", "ModelOptions", ]
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 ModelOptions # type: ignore # noqa logger = logging.getLogger(__name__) def save(tag, *args, **kwargs): logger.warning( f'The "{__name__}.save" method is being deprecated. Use "{__name__}.save_model" instead' ) return save_model(tag, *args, **kwargs) def load(tag, *args, **kwargs): logger.warning( f'The "{__name__}.load" method is being deprecated. Use "{__name__}.load_model" instead' ) return load_model(tag, *args, **kwargs) def load_runner(tag, *args, **kwargs): if len(args) != 0 or len(kwargs) != 0: logger.error( f'The "{__name__}.load_runner" method is being deprecated. "load_runner" arguments will be ignored. Use `{__name__}.get("{tag}").to_runner()` instead' ) else: logger.warning( f'The "{__name__}.load_runner" method is being deprecated. Use `{__name__}.get("{tag}").to_runner()` instead' ) return get(tag).to_runner() __all__ = ["load_model", "save_model", "get", "get_runnable"]
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 = logging.getLogger(__name__) def save(tag, *args, **kwargs): logger.warning( f'The "{__name__}.save" method is being deprecated. Use "{__name__}.save_model" instead' ) return save_model(tag, *args, **kwargs) def load(tag, *args, **kwargs): logger.warning( f'The "{__name__}.load" method is being deprecated. Use "{__name__}.load_model" instead' ) return load_model(tag, *args, **kwargs) def load_runner(tag, *args, **kwargs): if len(args) != 0 or len(kwargs) != 0: logger.error( f'The "{__name__}.load_runner" method is being deprecated. "load_runner" arguments will be ignored. Use `{__name__}.get("{tag}").to_runner()` instead' ) else: logger.warning( f'The "{__name__}.load_runner" method is being deprecated. Use `{__name__}.get("{tag}").to_runner()` instead' ) return get(tag).to_runner() __all__ = ["get", "load_model", "save_model", "get_runnable"]
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 ._internal.io_descriptors.pandas import PandasSeries from ._internal.io_descriptors.pandas import PandasDataFrame from ._internal.io_descriptors.multipart import Multipart __all__ = [ "File", "Image", "IODescriptor", "JSON", "Multipart", "NumpyNdarray", "PandasDataFrame", "PandasSeries", "Text", ]
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 .bentos import list # pylint: disable=W0622 from .bentos import pull from .bentos import push from .bentos import delete from .bentos import export_bento from .bentos import import_bento # BentoML built-in types from ._internal.tag import Tag from ._internal.bento import Bento from ._internal.models import Model from ._internal.runner import Runner from ._internal.runner import Runnable from ._internal.context import InferenceApiContext as Context from ._internal.service import Service from ._internal.yatai_client import YataiClient from ._internal.service.loader import load # Framework specific modules are lazily loaded upon import if TYPE_CHECKING: from bentoml import h2o from bentoml import flax from bentoml import onnx from bentoml import gluon from bentoml import keras from bentoml import spacy from bentoml import mlflow from bentoml import paddle from bentoml import easyocr from bentoml import pycaret from bentoml import pytorch from bentoml import sklearn from bentoml import xgboost from bentoml import catboost from bentoml import lightgbm from bentoml import onnxmlir from bentoml import detectron from bentoml import tensorflow from bentoml import statsmodels from bentoml import torchscript from bentoml import transformers from bentoml import tensorflow_v1 from bentoml import picklable_model from bentoml import pytorch_lightning else: from ._internal.utils import LazyLoader as _LazyLoader catboost = _LazyLoader("bentoml.catboost", globals(), "bentoml.catboost") detectron = _LazyLoader("bentoml.detectron", globals(), "bentoml.detectron") easyocr = _LazyLoader("bentoml.easyocr", globals(), "bentoml.easyocr") flax = _LazyLoader("bentoml.flax", globals(), "bentoml.flax") gluon = _LazyLoader("bentoml.gluon", globals(), "bentoml.gluon") h2o = _LazyLoader("bentoml.h2o", globals(), "bentoml.h2o") lightgbm = _LazyLoader("bentoml.lightgbm", globals(), "bentoml.lightgbm") mlflow = _LazyLoader("bentoml.mlflow", globals(), "bentoml.mlflow") onnx = _LazyLoader("bentoml.onnx", globals(), "bentoml.onnx") onnxmlir = _LazyLoader("bentoml.onnxmlir", globals(), "bentoml.onnxmlir") keras = _LazyLoader("bentoml.keras", globals(), "bentoml.keras") paddle = _LazyLoader("bentoml.paddle", globals(), "bentoml.paddle") pycaret = _LazyLoader("bentoml.pycaret", globals(), "bentoml.pycaret") pytorch = _LazyLoader("bentoml.pytorch", globals(), "bentoml.pytorch") pytorch_lightning = _LazyLoader( "bentoml.pytorch_lightning", globals(), "bentoml.pytorch_lightning" ) sklearn = _LazyLoader("bentoml.sklearn", globals(), "bentoml.sklearn") picklable_model = _LazyLoader( "bentoml.picklable_model", globals(), "bentoml.picklable_model" ) spacy = _LazyLoader("bentoml.spacy", globals(), "bentoml.spacy") statsmodels = _LazyLoader("bentoml.statsmodels", globals(), "bentoml.statsmodels") tensorflow = _LazyLoader("bentoml.tensorflow", globals(), "bentoml.tensorflow") tensorflow_v1 = _LazyLoader( "bentoml.tensorflow_v1", globals(), "bentoml.tensorflow_v1" ) torchscript = _LazyLoader("bentoml.torchscript", globals(), "bentoml.torchscript") transformers = _LazyLoader( "bentoml.transformers", globals(), "bentoml.transformers" ) xgboost = _LazyLoader("bentoml.xgboost", globals(), "bentoml.xgboost") __all__ = [ "__version__", "Context", "Service", "models", "Tag", "Model", "Runner", "Runnable", "YataiClient", # Yatai REST API Client # bento APIs "list", "get", "delete", "import_bento", "export_bento", "load", "push", "pull", "Bento", # Framework specific modules "catboost", "detectron", "easyocr", "flax", "gluon", "h2o", "lightgbm", "mlflow", "onnx", "onnxmlir", "paddle", "picklable_model", "pycaret", "pytorch", "pytorch_lightning", "keras", "sklearn", "spacy", "statsmodels", "tensorflow", "tensorflow_v1", "torchscript", "transformers", "xgboost", ]
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 ModelOptions # type: ignore # noqa logger = logging.getLogger(__name__) def save(tag, *args, **kwargs): logger.warning( f'The "{__name__}.save" method is being deprecated. Use "{__name__}.save_model" instead' ) return save_model(tag, *args, **kwargs) def load(tag, *args, **kwargs): logger.warning( f'The "{__name__}.load" method is being deprecated. Use "{__name__}.load_model" instead' ) return load_model(tag, *args, **kwargs) def load_runner(tag, *args, **kwargs): if len(args) != 0 or len(kwargs) != 0: logger.error( f'The "{__name__}.load_runner" method is being deprecated. "load_runner" arguments will be ignored. Use `{__name__}.get("{tag}").to_runner()` instead' ) else: logger.warning( f'The "{__name__}.load_runner" method is being deprecated. Use `{__name__}.get("{tag}").to_runner()` instead' ) return get(tag).to_runner() __all__ = ["get", "load_model", "save_model", "get_runnable"]
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 from ._internal.tag import Tag from ._internal.bento import Bento from ._internal.utils import resolve_user_filepath from ._internal.bento.build_config import BentoBuildConfig from ._internal.configuration.containers import BentoMLContainer if TYPE_CHECKING: from ._internal.bento import BentoStore from ._internal.types import PathType from ._internal.models import ModelStore logger = logging.getLogger(__name__) BENTOML_FIGLET = """ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ•—β–‘β–‘β–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–‘β–ˆβ–ˆβ–ˆβ•—β–‘β–‘β–‘β–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•—β–‘β–‘β–‘β–‘β–‘ β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β•β•β•β–ˆβ–ˆβ–ˆβ–ˆβ•—β–‘β–ˆβ–ˆβ•‘β•šβ•β•β–ˆβ–ˆβ•”β•β•β•β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ•—β–‘β–ˆβ–ˆβ–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘β–‘β–‘β–‘β–‘β–‘ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•¦β•β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–‘β–‘β–ˆβ–ˆβ•”β–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘β–‘β–‘β–‘β–ˆβ–ˆβ•‘β–‘β–‘β–‘β–ˆβ–ˆβ•‘β–‘β–‘β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β–ˆβ–ˆβ–ˆβ–ˆβ•”β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘β–‘β–‘β–‘β–‘β–‘ β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β•β–‘β–‘β–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ–ˆβ–ˆβ•‘β–‘β–‘β–‘β–ˆβ–ˆβ•‘β–‘β–‘β–‘β–ˆβ–ˆβ•‘β–‘β–‘β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘β–‘β–‘β–‘β–‘β–‘ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•¦β•β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘β–‘β•šβ–ˆβ–ˆβ–ˆβ•‘β–‘β–‘β–‘β–ˆβ–ˆβ•‘β–‘β–‘β–‘β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ•‘β–‘β•šβ•β•β–‘β–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β•šβ•β•β•β•β•β•β–‘β•šβ•β•β•β•β•β•β•β•šβ•β•β–‘β–‘β•šβ•β•β•β–‘β–‘β–‘β•šβ•β•β–‘β–‘β–‘β–‘β•šβ•β•β•β•β•β–‘β•šβ•β•β–‘β–‘β–‘β–‘β–‘β•šβ•β•β•šβ•β•β•β•β•β•β• """ @inject def list( # pylint: disable=redefined-builtin tag: t.Optional[t.Union[Tag, str]] = None, _bento_store: "BentoStore" = Provide[BentoMLContainer.bento_store], ) -> "t.List[Bento]": return _bento_store.list(tag) @inject def get( tag: t.Union[Tag, str], *, _bento_store: "BentoStore" = Provide[BentoMLContainer.bento_store], ) -> Bento: return _bento_store.get(tag) @inject def delete( tag: t.Union[Tag, str], *, _bento_store: "BentoStore" = Provide[BentoMLContainer.bento_store], ): _bento_store.delete(tag) @inject def import_bento( path: str, input_format: t.Optional[str] = None, *, protocol: t.Optional[str] = None, user: t.Optional[str] = None, passwd: t.Optional[str] = None, params: t.Optional[t.Dict[str, str]] = None, subpath: t.Optional[str] = None, _bento_store: "BentoStore" = Provide[BentoMLContainer.bento_store], ) -> Bento: """ Import a bento. Examples: .. code-block:: python # imports 'my_bento' from '/path/to/folder/my_bento.bento' bentoml.import_bento('/path/to/folder/my_bento.bento') # imports 'my_bento' from '/path/to/folder/my_bento.tar.gz' # currently supported formats are tar.gz ('gz'), tar.xz ('xz'), tar.bz2 ('bz2'), and zip bentoml.import_bento('/path/to/folder/my_bento.tar.gz') # treats 'my_bento.ext' as a gzipped tarfile bentoml.import_bento('/path/to/folder/my_bento.ext', 'gz') # imports 'my_bento', which is stored as an uncompressed folder, from '/path/to/folder/my_bento/' bentoml.import_bento('/path/to/folder/my_bento', 'folder') # imports 'my_bento' from the S3 bucket 'my_bucket', path 'folder/my_bento.bento' # requires `fs-s3fs <https://pypi.org/project/fs-s3fs/>`_ ('pip install fs-s3fs') bentoml.import_bento('s3://my_bucket/folder/my_bento.bento') bentoml.import_bento('my_bucket/folder/my_bento.bento', protocol='s3') bentoml.import_bento('my_bucket', protocol='s3', subpath='folder/my_bento.bento') bentoml.import_bento('my_bucket', protocol='s3', subpath='folder/my_bento.bento', user='<AWS access key>', passwd='<AWS secret key>', params={'acl': 'public-read', 'cache-control': 'max-age=2592000,public'}) For a more comprehensive description of what each of the keyword arguments (:code:`protocol`, :code:`user`, :code:`passwd`, :code:`params`, and :code:`subpath`) mean, see the `FS URL documentation <https://docs.pyfilesystem.org/en/latest/openers.html>`_. Args: tag: the tag of the bento to export path: can be one of two things: * a folder on the local filesystem * an `FS URL <https://docs.pyfilesystem.org/en/latest/openers.html>`_, for example :code:`'s3://my_bucket/folder/my_bento.bento'` protocol: (expert) The FS protocol to use when exporting. Some example protocols are :code:`'ftp'`, :code:`'s3'`, and :code:`'userdata'` user: (expert) the username used for authentication if required, e.g. for FTP passwd: (expert) the username used for authentication if required, e.g. for FTP params: (expert) a map of parameters to be passed to the FS used for export, e.g. :code:`{'proxy': 'myproxy.net'}` for setting a proxy for FTP subpath: (expert) the path inside the FS that the bento should be exported to _bento_store: the bento store to save the bento to Returns: Bento: the imported bento """ return Bento.import_from( path, input_format, protocol=protocol, user=user, passwd=passwd, params=params, subpath=subpath, ).save(_bento_store) @inject def export_bento( tag: t.Union[Tag, str], path: str, output_format: t.Optional[str] = None, *, protocol: t.Optional[str] = None, user: t.Optional[str] = None, passwd: t.Optional[str] = None, params: t.Optional[t.Dict[str, str]] = None, subpath: t.Optional[str] = None, _bento_store: "BentoStore" = Provide[BentoMLContainer.bento_store], ) -> str: """ Export a bento. Examples: .. code-block:: python # exports 'my_bento' to '/path/to/folder/my_bento-version.bento' in BentoML's default format bentoml.export_bento('my_bento:latest', '/path/to/folder') # note that folders can only be passed if exporting to the local filesystem; otherwise the # full path, including the desired filename, must be passed # exports 'my_bento' to '/path/to/folder/my_bento.bento' in BentoML's default format bentoml.export_bento('my_bento:latest', '/path/to/folder/my_bento') bentoml.export_bento('my_bento:latest', '/path/to/folder/my_bento.bento') # exports 'my_bento' to '/path/to/folder/my_bento.tar.gz' in gzip format # currently supported formats are tar.gz ('gz'), tar.xz ('xz'), tar.bz2 ('bz2'), and zip bentoml.export_bento('my_bento:latest', '/path/to/folder/my_bento.tar.gz') # outputs a gzipped tarfile as 'my_bento.ext' bentoml.export_bento('my_bento:latest', '/path/to/folder/my_bento.ext', 'gz') # exports 'my_bento' to '/path/to/folder/my_bento/' as a folder bentoml.export_bento('my_bento:latest', '/path/to/folder/my_bento', 'folder') # exports 'my_bento' to the S3 bucket 'my_bucket' as 'folder/my_bento-version.bento' bentoml.export_bento('my_bento:latest', 's3://my_bucket/folder') bentoml.export_bento('my_bento:latest', 'my_bucket/folder', protocol='s3') bentoml.export_bento('my_bento:latest', 'my_bucket', protocol='s3', subpath='folder') bentoml.export_bento('my_bento:latest', 'my_bucket', protocol='s3', subpath='folder', user='<AWS access key>', passwd='<AWS secret key>', params={'acl': 'public-read', 'cache-control': 'max-age=2592000,public'}) For a more comprehensive description of what each of the keyword arguments (:code:`protocol`, :code:`user`, :code:`passwd`, :code:`params`, and :code:`subpath`) mean, see the `FS URL documentation <https://docs.pyfilesystem.org/en/latest/openers.html>`_. Args: tag: the tag of the Bento to export path: can be one of two things: * a folder on the local filesystem * an `FS URL <https://docs.pyfilesystem.org/en/latest/openers.html>`_ * for example, :code:`'s3://my_bucket/folder/my_bento.bento'` protocol: (expert) The FS protocol to use when exporting. Some example protocols are :code:`'ftp'`, :code:`'s3'`, and :code:`'userdata'` user: (expert) the username used for authentication if required, e.g. for FTP passwd: (expert) the username used for authentication if required, e.g. for FTP params: (expert) a map of parameters to be passed to the FS used for export, e.g. :code:`{'proxy': 'myproxy.net'}` for setting a proxy for FTP subpath: (expert) the path inside the FS that the bento should be exported to _bento_store: save Bento created to this BentoStore Returns: str: A representation of the path that the Bento was exported to. If it was exported to the local filesystem, this will be the OS path to the exported Bento. Otherwise, it will be an FS URL. """ bento = get(tag, _bento_store=_bento_store) return bento.export( path, output_format, protocol=protocol, user=user, passwd=passwd, params=params, subpath=subpath, ) @inject def push( tag: t.Union[Tag, str], *, _bento_store: "BentoStore" = Provide[BentoMLContainer.bento_store], ): raise NotImplementedError @inject def pull( tag: t.Union[Tag, str], *, _bento_store: "BentoStore" = Provide[BentoMLContainer.bento_store], ): raise NotImplementedError @inject def build( service: str, *, labels: t.Optional[t.Dict[str, str]] = None, description: t.Optional[str] = None, include: t.Optional[t.List[str]] = None, exclude: t.Optional[t.List[str]] = None, docker: t.Optional[t.Dict[str, t.Any]] = None, python: t.Optional[t.Dict[str, t.Any]] = None, conda: t.Optional[t.Dict[str, t.Any]] = None, version: t.Optional[str] = None, build_ctx: t.Optional[str] = None, _bento_store: "BentoStore" = Provide[BentoMLContainer.bento_store], _model_store: "ModelStore" = Provide[BentoMLContainer.model_store], ) -> "Bento": """ User-facing API for building a Bento. The available build options are identical to the keys of a valid 'bentofile.yaml' file. This API will not respect any 'bentofile.yaml' files. Build options should instead be provided via function call parameters. Args: service: import str for finding the bentoml.Service instance build target labels: optional immutable labels for carrying contextual info description: optional description string in markdown format include: list of file paths and patterns specifying files to include in Bento, default is all files under build_ctx, beside the ones excluded from the exclude parameter or a :code:`.bentoignore` file for a given directory exclude: list of file paths and patterns to exclude from the final Bento archive docker: dictionary for configuring Bento's containerization process, see details in :class:`bentoml._internal.bento.build_config.DockerOptions` python: dictionary for configuring Bento's python dependencies, see details in :class:`bentoml._internal.bento.build_config.PythonOptions` conda: dictionary for configuring Bento's conda dependencies, see details in :class:`bentoml._internal.bento.build_config.CondaOptions` version: Override the default auto generated version str build_ctx: Build context directory, when used as _bento_store: save Bento created to this BentoStore _model_store: pull Models required from this ModelStore Returns: Bento: a Bento instance representing the materialized Bento saved in BentoStore Example: .. code-block:: import bentoml bentoml.build( service="fraud_detector.py:svc", version="any_version_label", # override default version generator description=open("README.md").read(), include=['*'], exclude=[], # files to exclude can also be specified with a .bentoignore file labels={ "foo": "bar", "team": "abc" }, python=dict( packages=["tensorflow", "numpy"], # requirements_txt="./requirements.txt", index_url="http://<api token>:@mycompany.com/pypi/simple", trusted_host=["mycompany.com"], find_links=['thirdparty..'], extra_index_url=["..."], pip_args="ANY ADDITIONAL PIP INSTALL ARGS", wheels=["./wheels/*"], lock_packages=True, ), docker=dict( distro="amazonlinux2", setup_script="setup_docker_container.sh", python_version="3.8", ), ) """ # noqa: LN001 build_config = BentoBuildConfig( service=service, description=description, labels=labels, include=include, exclude=exclude, docker=docker, # type: ignore python=python, # type: ignore conda=conda, # type: ignore ) bento = Bento.create( build_config=build_config, version=version, build_ctx=build_ctx, ).save(_bento_store) logger.info(BENTOML_FIGLET) logger.info(f"Successfully built {bento}") return bento @inject def build_bentofile( bentofile: str = "bentofile.yaml", *, version: t.Optional[str] = None, build_ctx: t.Optional[str] = None, _bento_store: "BentoStore" = Provide[BentoMLContainer.bento_store], _model_store: "ModelStore" = Provide[BentoMLContainer.model_store], ) -> "Bento": """ Build a Bento base on options specified in a bentofile.yaml file. By default, this function will look for a `bentofile.yaml` file in current working directory. Args: bentofile: The file path to build config yaml file version: Override the default auto generated version str build_ctx: Build context directory, when used as _bento_store: save Bento created to this BentoStore _model_store: pull Models required from this ModelStore """ try: bentofile = resolve_user_filepath(bentofile, build_ctx) except FileNotFoundError: raise InvalidArgument(f'bentofile "{bentofile}" not found') with open(bentofile, "r", encoding="utf-8") as f: build_config = BentoBuildConfig.from_yaml(f) bento = Bento.create( build_config=build_config, version=version, build_ctx=build_ctx, ).save(_bento_store) logger.info(BENTOML_FIGLET) logger.info(f"Successfully built {bento}") return bento @inject def containerize( tag: Tag | str, docker_image_tag: str | None = None, *, add_host: dict[str, str] | None = None, allow: t.List[str] | None = None, build_args: dict[str, str] | None = None, build_context: dict[str, str] | None = None, builder: str | None = None, cache_from: str | t.List[str] | dict[str, str] | None = None, cache_to: str | t.List[str] | dict[str, str] | None = None, cgroup_parent: str | None = None, iidfile: PathType | None = None, labels: dict[str, str] | None = None, load: bool = True, metadata_file: PathType | None = None, network: str | None = None, no_cache: bool = False, no_cache_filter: t.List[str] | None = None, output: str | dict[str, str] | None = None, platform: str | t.List[str] | None = None, progress: t.Literal["auto", "tty", "plain"] = "auto", pull: bool = False, push: bool = False, quiet: bool = False, secrets: str | t.List[str] | None = None, shm_size: str | int | None = None, rm: bool = False, ssh: str | None = None, target: str | None = None, ulimit: str | None = None, _bento_store: "BentoStore" = Provide[BentoMLContainer.bento_store], ) -> bool: from bentoml._internal.utils import buildx env = {"DOCKER_BUILDKIT": "1", "DOCKER_SCAN_SUGGEST": "false"} # run health check whether buildx is install locally buildx.health() bento = _bento_store.get(tag) if docker_image_tag is None: docker_image_tag = str(bento.tag) dockerfile_path = os.path.join("env", "docker", "Dockerfile") logger.info(f"Building docker image for {bento}...") try: buildx.build( subprocess_env=env, cwd=bento.path, file=dockerfile_path, tags=docker_image_tag, add_host=add_host, allow=allow, build_args=build_args, build_context=build_context, builder=builder, cache_from=cache_from, cache_to=cache_to, cgroup_parent=cgroup_parent, iidfile=iidfile, labels=labels, load=load, metadata_file=metadata_file, network=network, no_cache=no_cache, no_cache_filter=no_cache_filter, output=output, platform=platform, progress=progress, pull=pull, push=push, quiet=quiet, secrets=secrets, shm_size=shm_size, rm=rm, ssh=ssh, target=target, ulimit=ulimit, ) except subprocess.CalledProcessError as e: logger.error(f"Failed building docker image: {e}") if platform != "linux/amd64": logger.debug( f"""If you run into the following error: "failed to solve: pull access denied, repository does not exist or may require authorization: server message: insufficient_scope: authorization failed". This means Docker doesn't have context of your build platform {platform}. By default BentoML will set target build platform to the current machine platform via `uname -m`. Try again by specifying to build x86_64 (amd64) platform: bentoml containerize {str(bento.tag)} --platform linux/amd64""" ) return False else: logger.info(f'Successfully built docker image "{docker_image_tag}"') return True __all__ = [ "list", "get", "delete", "import_bento", "export_bento", "push", "pull", "build", "build_bentofile", "containerize", ]
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, *args, **kwargs): logger.warning( f'The "{__name__}.save" method is being deprecated. Use "{__name__}.save_model" instead' ) return save_model(tag, *args, **kwargs) def load(tag, *args, **kwargs): logger.warning( f'The "{__name__}.load" method is being deprecated. Use "{__name__}.load_model" instead' ) return load_model(tag, *args, **kwargs) def load_runner(tag, *args, **kwargs): if len(args) != 0 or len(kwargs) != 0: logger.error( f'The "{__name__}.load_runner" method is being deprecated. "load_runner" arguments will be ignored. Use `{__name__}.get("{tag}").to_runner()` instead' ) else: logger.warning( f'The "{__name__}.load_runner" method is being deprecated. Use `{__name__}.get("{tag}").to_runner()` instead' ) return get(tag).to_runner() __all__ = ["load_model", "save_model", "get", "get_runnable"]
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( f'The "{__name__}.save" method is being deprecated. Use "{__name__}.save_model" instead' ) return save_model(tag, *args, **kwargs) def load(tag, *args, **kwargs): logger.warning( f'The "{__name__}.load" method is being deprecated. Use "{__name__}.load_model" instead' ) return load_model(tag, *args, **kwargs) def load_runner(tag, *args, **kwargs): if len(args) != 0 or len(kwargs) != 0: logger.error( f'The "{__name__}.load_runner" method is being deprecated. "load_runner" arguments will be ignored. Use `{__name__}.get("{tag}").to_runner()` instead' ) else: logger.warning( f'The "{__name__}.load_runner" method is being deprecated. Use `{__name__}.get("{tag}").to_runner()` instead' ) return get(tag).to_runner() __all__ = ["load_model", "save_model", "get", "get_runnable"]
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.message = message super().__init__(message) class StateException(Exception): """ Raise when the state of an object is not valid """ error_code = HTTPStatus.BAD_REQUEST class RemoteException(BentoMLException): """ Raise when known exceptions happened in remote process """ def __init__(self, message: str, payload: BentoMLException | None = None): self.payload = payload super().__init__(message) class InvalidArgument(BentoMLException): """ Raise when BentoML received unexpected/invalid arguments from CLI arguments, HTTP Request, or python API function parameters """ error_code = HTTPStatus.BAD_REQUEST class InternalServerError(BentoMLException): """ Raise when BentoML received valid arguments from CLI arguments, HTTP Request, or python API function parameters, but got internal issues while processing. * Note to BentoML org developers: raise this exception only when exceptions happend in the users' code (runner or service) and want to surface it to the user. """ class APIDeprecated(BentoMLException): """ Raise when trying to use deprecated APIs of BentoML """ class BadInput(InvalidArgument): """Raise when API server receiving bad input request""" error_code = HTTPStatus.BAD_REQUEST class NotFound(BentoMLException): """ Raise when specified resource or name not found """ error_code = HTTPStatus.NOT_FOUND class TooManyRequests(BentoMLException): """ Raise when incoming requests exceeds the capacity of a server """ error_code = HTTPStatus.TOO_MANY_REQUESTS class BentoMLConfigException(BentoMLException): """Raise when BentoML is mis-configured or when required configuration is missing""" class MissingDependencyException(BentoMLException): """ Raise when BentoML component failed to load required dependency - some BentoML components has dependency that is optional to the library itself. For example, when using SklearnModel, the scikit-learn module is required although BentoML does not require scikit-learn to be a dependency when installed """ class CLIException(BentoMLException): """Raise when CLI encounters an issue""" class YataiRESTApiClientError(BentoMLException): pass class ImportServiceError(BentoMLException): pass
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): logger.warning( f'The "{__name__}.save" method is being deprecated. Use "{__name__}.save_model" instead' ) return save_model(tag, *args, **kwargs) def load(tag, *args, **kwargs): logger.warning( f'The "{__name__}.load" method is being deprecated. Use "{__name__}.load_model" instead' ) return load_model(tag, *args, **kwargs) def load_runner(tag, *args, **kwargs): if len(args) != 0 or len(kwargs) != 0: logger.error( f'The "{__name__}.load_runner" method is being deprecated. "load_runner" arguments will be ignored. Use `{__name__}.get("{tag}").to_runner()` instead' ) else: logger.warning( f'The "{__name__}.load_runner" method is being deprecated. Use `{__name__}.get("{tag}").to_runner()` instead' ) return get(tag).to_runner() __all__ = ["load_model", "save_model", "get", "get_runnable"]
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( f'The "{__name__}.save" method is being deprecated. Use "{__name__}.save_model" instead' ) return save_model(tag, *args, **kwargs) def load(tag, *args, **kwargs): logger.warning( f'The "{__name__}.load" method is being deprecated. Use "{__name__}.load_model" instead' ) return load_model(tag, *args, **kwargs) def load_runner(tag, *args, **kwargs): if len(args) != 0 or len(kwargs) != 0: logger.error( f'The "{__name__}.load_runner" method is being deprecated. "load_runner" arguments will be ignored. Use `{__name__}.get("{tag}").to_runner()` instead' ) else: logger.warning( f'The "{__name__}.load_runner" method is being deprecated. Use `{__name__}.get("{tag}").to_runner()` instead' ) return get(tag).to_runner() __all__ = ["load_model", "save_model", "get", "get_runnable"]
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( f'The "{__name__}.save" method is being deprecated. Use "{__name__}.save_model" instead' ) return save_model(tag, *args, **kwargs) def load(tag, *args, **kwargs): logger.warning( f'The "{__name__}.load" method is being deprecated. Use "{__name__}.load_model" instead' ) return load_model(tag, *args, **kwargs) def load_runner(tag, *args, **kwargs): if len(args) != 0 or len(kwargs) != 0: logger.error( f'The "{__name__}.load_runner" method is being deprecated. "load_runner" arguments will be ignored. Use `{__name__}.get("{tag}").to_runner()` instead' ) else: logger.warning( f'The "{__name__}.load_runner" method is being deprecated. Use `{__name__}.get("{tag}").to_runner()` instead' ) return get(tag).to_runner() __all__ = ["load_model", "get_runnable", "save_model", "get"]
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()()