superduperdb.ext.llm package#

Submodules#

superduperdb.ext.llm.base module#

class superduperdb.ext.llm.base.BaseLLMAPI(identifier: str, artifacts: dc.InitVar[t.Optional[t.Dict]] = None, prompt_template: str = '{input}', prompt_func: ~typing.Callable | None = None, max_batch_size: int | None = 4, inference_kwargs: dict = <factory>, api_url: str = '', *, datatype: EncoderArg = None, output_schema: t.Optional[Schema] = None, flatten: bool = False, preprocess: t.Optional[t.Callable] = None, postprocess: t.Optional[t.Callable] = None, collate_fn: t.Optional[t.Callable] = None, batch_predict: bool = False, takes_context: bool = False, metrics: t.Sequence[t.Union[str, Metric, None]] = (), model_update_kwargs: t.Dict = <factory>, validation_sets: t.Optional[t.Sequence[t.Union[str, Dataset]]] = None, predict_X: t.Optional[str] = None, predict_select: t.Optional[CompoundSelect] = None, predict_max_chunk_size: t.Optional[int] = None, predict_kwargs: t.Optional[t.Dict] = None)[source]#

Bases: _BaseLLM

Parameters:
  • api_url – The URL for the API.

  • prompt_template – The template to use for the prompt.

  • prompt_func – The function to use for the prompt.

  • max_batch_size – The maximum batch size to use for batch generation.

  • inference_kwargs – Parameters used during inference.

_batch_generate(prompts: List[str], **kwargs: Any) List[str][source]#

Base method to batch generate text from a list of prompts using multi-threading. Handles exceptions in _generate method.

_generate_wrapper(prompt: str, **kwargs: Any) str[source]#

Wrapper for the _generate method to handle exceptions.

api_url: str = ''#
init()[source]#
class superduperdb.ext.llm.base.BaseLLMModel(identifier: str = '', artifacts: dc.InitVar[t.Optional[t.Dict]] = None, prompt_template: str = '{input}', prompt_func: ~typing.Callable | None = None, max_batch_size: int | None = 4, inference_kwargs: dict = <factory>, model_name: str = '', on_ray: bool = False, ray_address: str | None = None, ray_config: dict = <factory>, *, datatype: EncoderArg = None, output_schema: t.Optional[Schema] = None, flatten: bool = False, preprocess: t.Optional[t.Callable] = None, postprocess: t.Optional[t.Callable] = None, collate_fn: t.Optional[t.Callable] = None, batch_predict: bool = False, takes_context: bool = False, metrics: t.Sequence[t.Union[str, Metric, None]] = (), model_update_kwargs: t.Dict = <factory>, validation_sets: t.Optional[t.Sequence[t.Union[str, Dataset]]] = None, predict_X: t.Optional[str] = None, predict_select: t.Optional[CompoundSelect] = None, predict_max_chunk_size: t.Optional[int] = None, predict_kwargs: t.Optional[t.Dict] = None)[source]#

Bases: _BaseLLM

Parameters:
  • model_name – The name of the model to use.

  • on_ray – Whether to run the model on Ray.

  • ray_config – The Ray config to use.

  • ray_addredd – The address of the ray cluster.

  • prompt_template – The template to use for the prompt.

  • prompt_func – The function to use for the prompt.

  • max_batch_size – The maximum batch size to use for batch generation.

  • inference_kwargs – Parameters used during inference.

identifier: str = ''#
model_name: str = ''#
on_ray: bool = False#
ray_address: str | None = None#
ray_config: dict#
class superduperdb.ext.llm.base.BaseOpenAI(identifier: str = '', artifacts: dc.InitVar[t.Optional[t.Dict]] = None, prompt_template: str = '{input}', prompt_func: ~typing.Callable | None = None, max_batch_size: int | None = 4, inference_kwargs: dict = <factory>, api_url: str = '', openai_api_base: str = 'https://api.openai.com/v1', openai_api_key: str | None = None, model_name: str = 'gpt-3.5-turbo', chat: bool = True, system_prompt: str | None = None, user_role: str = 'user', system_role: str = 'system', *, datatype: EncoderArg = None, output_schema: t.Optional[Schema] = None, flatten: bool = False, preprocess: t.Optional[t.Callable] = None, postprocess: t.Optional[t.Callable] = None, collate_fn: t.Optional[t.Callable] = None, batch_predict: bool = False, takes_context: bool = False, metrics: t.Sequence[t.Union[str, Metric, None]] = (), model_update_kwargs: t.Dict = <factory>, validation_sets: t.Optional[t.Sequence[t.Union[str, Dataset]]] = None, predict_X: t.Optional[str] = None, predict_select: t.Optional[CompoundSelect] = None, predict_max_chunk_size: t.Optional[int] = None, predict_kwargs: t.Optional[t.Dict] = None)[source]#

Bases: BaseLLMAPI

Parameters:
  • openai_api_base – The base URL for the OpenAI API.

  • openai_api_key – The API key to use for the OpenAI API.

  • model_name – The name of the model to use.

  • chat – Whether to use the chat API or the completion API. Defaults to False.

  • system_prompt – The prompt to use for the system.

  • user_role – The role to use for the user.

  • system_role – The role to use for the system.

  • prompt_template – The template to use for the prompt.

  • prompt_func – The function to use for the prompt.

  • max_batch_size – The maximum batch size to use for batch generation.

  • inference_kwargs – Parameters used during inference.

_chat_generate(content: str, **kwargs: Any) str[source]#

Generate a completion for a given prompt with chat format. :param prompt: The prompt to generate a completion for. :param kwargs: Any additional arguments to pass to the API.

_prompt_generate(prompt: str, **kwargs: Any) str[source]#

Generate a completion for a given prompt with prompt format.

chat: bool = True#
identifier: str = ''#
init()[source]#
model_name: str = 'gpt-3.5-turbo'#
openai_api_base: str = 'https://api.openai.com/v1'#
openai_api_key: str | None = None#
system_prompt: str | None = None#
system_role: str = 'system'#
user_role: str = 'user'#
class superduperdb.ext.llm.base._BaseLLM(identifier: str, artifacts: dc.InitVar[t.Optional[t.Dict]] = None, prompt_template: str = '{input}', prompt_func: ~typing.Callable | None = None, max_batch_size: int | None = 4, inference_kwargs: dict = <factory>, *, datatype: EncoderArg = None, output_schema: t.Optional[Schema] = None, flatten: bool = False, preprocess: t.Optional[t.Callable] = None, postprocess: t.Optional[t.Callable] = None, collate_fn: t.Optional[t.Callable] = None, batch_predict: bool = False, takes_context: bool = False, metrics: t.Sequence[t.Union[str, Metric, None]] = (), model_update_kwargs: t.Dict = <factory>, validation_sets: t.Optional[t.Sequence[t.Union[str, Dataset]]] = None, predict_X: t.Optional[str] = None, predict_select: t.Optional[CompoundSelect] = None, predict_max_chunk_size: t.Optional[int] = None, predict_kwargs: t.Optional[t.Dict] = None)[source]#

Bases: Component, _Predictor

Parameters:
  • prompt_template – The template to use for the prompt.

  • prompt_func – The function to use for the prompt.

  • max_batch_size – The maximum batch size to use for batch generation.

  • inference_kwargs – Parameters used during inference.

_batch_generate(prompts: List[str], **kwargs: Any) List[str][source]#

Base method to batch generate text from a list of prompts. If the model can run batch generation efficiently, pls override this method.

get_kwargs(func, *kwargs_list)[source]#

Get kwargs and object attributes that are in the function signature :param func (Callable): function to get kwargs for :param kwargs (list of dict): kwargs to filter

inference_kwargs: dict#
abstract init()[source]#
max_batch_size: int | None = 4#
post_create(db: Datalayer) None[source]#

Called after the first time this component is created. Generally used if self.version is important in this logic.

Parameters:

db – the db that creates the component

prompt_func: Callable | None = None#
prompt_template: str = '{input}'#
to_call(X, *args, **kwargs)[source]#

The method to use to call prediction. Should be implemented by the child class.

superduperdb.ext.llm.model module#

class superduperdb.ext.llm.model.LLM(identifier: str = '', artifacts: dc.InitVar[t.Optional[t.Dict]] = None, object: ~transformers.trainer.Trainer | None = None, model_name_or_path: str = 'facebook/opt-125m', bits: int | None = None, adapter_id: str | None = None, model_kwargs: ~typing.Dict = <factory>, tokenizer_kwargs: ~typing.Dict = <factory>, prompt_template: str = '{input}', prompt_func: ~typing.Callable | None = None, *, datatype: EncoderArg = None, output_schema: t.Optional[Schema] = None, flatten: bool = False, preprocess: t.Optional[t.Callable] = None, postprocess: t.Optional[t.Callable] = None, collate_fn: t.Optional[t.Callable] = None, batch_predict: bool = False, takes_context: bool = False, metrics: t.Sequence[t.Union[str, Metric, None]] = (), model_update_kwargs: dict = <factory>, validation_sets: t.Optional[t.Sequence[t.Union[str, Dataset]]] = None, predict_X: t.Optional[str] = None, predict_select: t.Optional[CompoundSelect] = None, predict_max_chunk_size: t.Optional[int] = None, predict_kwargs: t.Optional[t.Dict] = None, model_to_device_method: t.Optional[str] = None, metric_values: t.Optional[t.Dict] = <factory>, predict_method: t.Optional[str] = None, device: str = 'cpu', preferred_devices: t.Union[None, t.Sequence[str]] = ('cuda', 'mps', 'cpu'), training_configuration: t.Union[str, _TrainingConfiguration, None] = None, train_X: t.Optional[str] = None, train_y: t.Optional[str] = None, train_select: t.Optional[CompoundSelect] = None)[source]#

Bases: Model

LLM model based on transformers library. Parameters: : param identifier: model identifier : param model_name_or_path: model name or path : param bits: quantization bits, [4, 8], default is None : param adapter_id: adapter id, default is None

Add a adapter to the base model for inference. When model_name_or_path, bits, model_kwargs, tokenizer_kwargs are the same, will share the same base model and tokenizer cache.

: param model_kwargs: model kwargs,

all the kwargs will pass to transformers.AutoModelForCausalLM.from_pretrained

: param tokenizer_kwagrs: tokenizer kwargs,

all the kwargs will pass to transformers.AutoTokenizer.from_pretrained

: param prompt_template: prompt template, default is “{input}” : param prompt_func: prompt function, default is None

_base_generate(X: Any, **kwargs)[source]#

Generate text. Can overwrite this method to support more inference methods.

_generate(X: Any, adapter_name=None, **kwargs)[source]#

Private method for Model.to_call method. Support inference by multi-lora adapters.

adapter_id: str | None = None#
add_adapter(model_id, adapter_name: str)[source]#
bits: int | None = None#
get_compute_metrics(metrics)[source]#
get_datasets(X, y, db, select, db_validation_sets: Sequence[str | Dataset] | None = None, data_prefetch: bool = False, prefetch_size: int = 10000)[source]#
identifier: str = ''#
init()[source]#
init_model_and_tokenizer()[source]#
model_kwargs: Dict#
model_name_or_path: str = 'facebook/opt-125m'#
object: Trainer | None = None#
post_create(db: Datalayer) None[source]#

Called after the first time this component is created. Generally used if self.version is important in this logic.

Parameters:

db – the db that creates the component

prompt_func: Callable | None = None#
prompt_template: str = '{input}'#
tokenizer_kwargs: Dict#

superduperdb.ext.llm.openai module#

class superduperdb.ext.llm.openai.OpenAI(identifier: str = '', artifacts: dc.InitVar[t.Optional[t.Dict]] = None, prompt_template: str = '{input}', prompt_func: ~typing.Callable | None = None, max_batch_size: int | None = 4, inference_kwargs: dict = <factory>, api_url: str = '', openai_api_base: str = 'https://api.openai.com/v1', openai_api_key: str | None = None, model_name: str = 'gpt-3.5-turbo', chat: bool = True, system_prompt: str | None = None, user_role: str = 'user', system_role: str = 'system', *, datatype: EncoderArg = None, output_schema: t.Optional[Schema] = None, flatten: bool = False, preprocess: t.Optional[t.Callable] = None, postprocess: t.Optional[t.Callable] = None, collate_fn: t.Optional[t.Callable] = None, batch_predict: bool = False, takes_context: bool = False, metrics: t.Sequence[t.Union[str, Metric, None]] = (), model_update_kwargs: t.Dict = <factory>, validation_sets: t.Optional[t.Sequence[t.Union[str, Dataset]]] = None, predict_X: t.Optional[str] = None, predict_select: t.Optional[CompoundSelect] = None, predict_max_chunk_size: t.Optional[int] = None, predict_kwargs: t.Optional[t.Dict] = None)[source]#

Bases: BaseOpenAI

OpenAI chat completion predictor.

Parameters:
  • openai_api_base – The base URL for the OpenAI API.

  • openai_api_key – The API key to use for the OpenAI API.

  • model_name – The name of the model to use.

  • chat – Whether to use the chat API or the completion API. Defaults to False.

  • system_prompt – The prompt to use for the system.

  • user_role – The role to use for the user.

  • system_role – The role to use for the system.

  • prompt_template – The template to use for the prompt.

  • prompt_func – The function to use for the prompt.

  • max_batch_size – The maximum batch size to use for batch generation.

  • inference_kwargs – Parameters used during inference.

__post_init__(artifacts)[source]#

Set model name.

superduperdb.ext.llm.training module#

class superduperdb.ext.llm.training.LLMCallback(cfg: Config | None = None, identifier: str | None = None, db: Datalayer | None = None, llm: LLM | None = None)[source]#

Bases: TrainerCallback

check_init()[source]#
on_save(args, state, control, **kwargs)[source]#

Event called after a checkpoint save.

class superduperdb.ext.llm.training.LLMTrainingArguments(output_dir: str, overwrite_output_dir: bool = False, do_train: bool = False, do_eval: bool = False, do_predict: bool = False, evaluation_strategy: ~transformers.trainer_utils.IntervalStrategy | str = 'no', prediction_loss_only: bool = False, per_device_train_batch_size: int = 8, per_device_eval_batch_size: int = 8, per_gpu_train_batch_size: int | None = None, per_gpu_eval_batch_size: int | None = None, gradient_accumulation_steps: int = 1, eval_accumulation_steps: int | None = None, eval_delay: float | None = 0, learning_rate: float = 5e-05, weight_decay: float = 0.0, adam_beta1: float = 0.9, adam_beta2: float = 0.999, adam_epsilon: float = 1e-08, max_grad_norm: float = 1.0, num_train_epochs: float = 3.0, max_steps: int = -1, lr_scheduler_type: ~transformers.trainer_utils.SchedulerType | str = 'linear', lr_scheduler_kwargs: ~typing.Dict | None = <factory>, warmup_ratio: float = 0.0, warmup_steps: int = 0, log_level: str | None = 'passive', log_level_replica: str | None = 'warning', log_on_each_node: bool = True, logging_dir: str | None = None, logging_strategy: ~transformers.trainer_utils.IntervalStrategy | str = 'steps', logging_first_step: bool = False, logging_steps: float = 500, logging_nan_inf_filter: bool = True, save_strategy: ~transformers.trainer_utils.IntervalStrategy | str = 'steps', save_steps: float = 500, save_total_limit: int | None = None, save_safetensors: bool | None = True, save_on_each_node: bool = False, save_only_model: bool = False, no_cuda: bool = False, use_cpu: bool = False, use_mps_device: bool = False, seed: int = 42, data_seed: int | None = None, jit_mode_eval: bool = False, use_ipex: bool = False, bf16: bool = False, fp16: bool = False, fp16_opt_level: str = 'O1', half_precision_backend: str = 'auto', bf16_full_eval: bool = False, fp16_full_eval: bool = False, tf32: bool | None = None, local_rank: int = -1, ddp_backend: str | None = None, tpu_num_cores: int | None = None, tpu_metrics_debug: bool = False, debug: str | ~typing.List[~transformers.debug_utils.DebugOption] = '', dataloader_drop_last: bool = False, eval_steps: float | None = None, dataloader_num_workers: int = 0, past_index: int = -1, run_name: str | None = None, disable_tqdm: bool | None = None, remove_unused_columns: bool | None = True, label_names: ~typing.List[str] | None = None, load_best_model_at_end: bool | None = False, metric_for_best_model: str | None = None, greater_is_better: bool | None = None, ignore_data_skip: bool = False, fsdp: ~typing.List[~transformers.trainer_utils.FSDPOption] | str | None = '', fsdp_min_num_params: int = 0, fsdp_config: str | None = None, fsdp_transformer_layer_cls_to_wrap: str | None = None, deepspeed: str | None = None, label_smoothing_factor: float = 0.0, optim: ~transformers.training_args.OptimizerNames | str = 'adamw_torch', optim_args: str | None = None, adafactor: bool = False, group_by_length: bool = False, length_column_name: str | None = 'length', report_to: ~typing.List[str] | None = None, ddp_find_unused_parameters: bool | None = None, ddp_bucket_cap_mb: int | None = None, ddp_broadcast_buffers: bool | None = None, dataloader_pin_memory: bool = True, dataloader_persistent_workers: bool = False, skip_memory_metrics: bool = True, use_legacy_prediction_loop: bool = False, push_to_hub: bool = False, resume_from_checkpoint: str | None = None, hub_model_id: str | None = None, hub_strategy: ~transformers.trainer_utils.HubStrategy | str = 'every_save', hub_token: str | None = None, hub_private_repo: bool = False, hub_always_push: bool = False, gradient_checkpointing: bool = False, gradient_checkpointing_kwargs: dict | None = None, include_inputs_for_metrics: bool = False, fp16_backend: str = 'auto', push_to_hub_model_id: str | None = None, push_to_hub_organization: str | None = None, push_to_hub_token: str | None = None, mp_parameters: str = '', auto_find_batch_size: bool = False, full_determinism: bool = False, torchdynamo: str | None = None, ray_scope: str | None = 'last', ddp_timeout: int | None = 1800, torch_compile: bool = False, torch_compile_backend: str | None = None, torch_compile_mode: str | None = None, dispatch_batches: bool | None = None, split_batches: bool | None = False, include_tokens_per_second: bool | None = False, include_num_input_tokens_seen: bool | None = False, neftune_noise_alpha: float = None, use_lora: bool = True, lora_r: int = 8, lora_alpha: int = 16, lora_dropout: float = 0.05, lora_target_modules: ~typing.List[str] | None = None, lora_bias: ~typing.Literal['none', 'all', 'lora_only'] = 'none', bits: int | None = None, max_length: int = 512, log_to_db: bool = False)[source]#

Bases: TrainingArguments

LLM Training Arguments. Inherits from transformers.TrainingArguments.

TrainingArguments is the subset of the arguments we use in our example scripts which relate to the training loop itself.

Using [HfArgumentParser] we can turn this class into [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the command line.

Parameters:
  • output_dir (str) – The output directory where the model predictions and checkpoints will be written.

  • overwrite_output_dir (bool, optional, defaults to False) – If True, overwrite the content of the output directory. Use this to continue training if output_dir points to a checkpoint directory.

  • do_train (bool, optional, defaults to False) – Whether to run training or not. This argument is not directly used by [Trainer], it’s intended to be used by your training/evaluation scripts instead. See the [example scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details.

  • do_eval (bool, optional) – Whether to run evaluation on the validation set or not. Will be set to True if evaluation_strategy is different from “no”. This argument is not directly used by [Trainer], it’s intended to be used by your training/evaluation scripts instead. See the [example scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details.

  • do_predict (bool, optional, defaults to False) – Whether to run predictions on the test set or not. This argument is not directly used by [Trainer], it’s intended to be used by your training/evaluation scripts instead. See the [example scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details.

  • evaluation_strategy (str or [~trainer_utils.IntervalStrategy], optional, defaults to “no”) –

    The evaluation strategy to adopt during training. Possible values are:

    • ”no”: No evaluation is done during training.

    • ”steps”: Evaluation is done (and logged) every eval_steps.

    • ”epoch”: Evaluation is done at the end of each epoch.

  • prediction_loss_only (bool, optional, defaults to False) – When performing evaluation and generating predictions, only returns the loss.

  • per_device_train_batch_size (int, optional, defaults to 8) – The batch size per GPU/XPU/TPU/MPS/NPU core/CPU for training.

  • per_device_eval_batch_size (int, optional, defaults to 8) – The batch size per GPU/XPU/TPU/MPS/NPU core/CPU for evaluation.

  • gradient_accumulation_steps (int, optional, defaults to 1) –

    Number of updates steps to accumulate the gradients for, before performing a backward/update pass.

    <Tip warning={true}>

    When using gradient accumulation, one step is counted as one step with backward pass. Therefore, logging, evaluation, save will be conducted every gradient_accumulation_steps * xxx_step training examples.

    </Tip>

  • eval_accumulation_steps (int, optional) – Number of predictions steps to accumulate the output tensors for, before moving the results to the CPU. If left unset, the whole predictions are accumulated on GPU/NPU/TPU before being moved to the CPU (faster but requires more memory).

  • eval_delay (float, optional) – Number of epochs or steps to wait for before the first evaluation can be performed, depending on the evaluation_strategy.

  • learning_rate (float, optional, defaults to 5e-5) – The initial learning rate for [AdamW] optimizer.

  • weight_decay (float, optional, defaults to 0) – The weight decay to apply (if not zero) to all layers except all bias and LayerNorm weights in [AdamW] optimizer.

  • adam_beta1 (float, optional, defaults to 0.9) – The beta1 hyperparameter for the [AdamW] optimizer.

  • adam_beta2 (float, optional, defaults to 0.999) – The beta2 hyperparameter for the [AdamW] optimizer.

  • adam_epsilon (float, optional, defaults to 1e-8) – The epsilon hyperparameter for the [AdamW] optimizer.

  • max_grad_norm (float, optional, defaults to 1.0) – Maximum gradient norm (for gradient clipping).

  • num_train_epochs (float, optional, defaults to 3.0) – Total number of training epochs to perform (if not an integer, will perform the decimal part percents of the last epoch before stopping training).

  • max_steps (int, optional, defaults to -1) – If set to a positive number, the total number of training steps to perform. Overrides num_train_epochs. For a finite dataset, training is reiterated through the dataset (if all data is exhausted) until max_steps is reached.

  • lr_scheduler_type (str or [SchedulerType], optional, defaults to “linear”) – The scheduler type to use. See the documentation of [SchedulerType] for all possible values.

  • lr_scheduler_kwargs (‘dict’, optional, defaults to {}) – The extra arguments for the lr_scheduler. See the documentation of each scheduler for possible values.

  • warmup_ratio (float, optional, defaults to 0.0) – Ratio of total training steps used for a linear warmup from 0 to learning_rate.

  • warmup_steps (int, optional, defaults to 0) – Number of steps used for a linear warmup from 0 to learning_rate. Overrides any effect of warmup_ratio.

  • log_level (str, optional, defaults to passive) – Logger log level to use on the main process. Possible choices are the log levels as strings: ‘debug’, ‘info’, ‘warning’, ‘error’ and ‘critical’, plus a ‘passive’ level which doesn’t set anything and keeps the current log level for the Transformers library (which will be “warning” by default).

  • log_level_replica (str, optional, defaults to “warning”) – Logger log level to use on replicas. Same choices as log_level

  • log_on_each_node (bool, optional, defaults to True) – In multinode distributed training, whether to log using log_level once per node, or only on the main node.

  • logging_dir (str, optional) – [TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to output_dir/runs/**CURRENT_DATETIME_HOSTNAME**.

  • logging_strategy (str or [~trainer_utils.IntervalStrategy], optional, defaults to “steps”) –

    The logging strategy to adopt during training. Possible values are:

    • ”no”: No logging is done during training.

    • ”epoch”: Logging is done at the end of each epoch.

    • ”steps”: Logging is done every logging_steps.

  • logging_first_step (bool, optional, defaults to False) – Whether to log and evaluate the first global_step or not.

  • logging_steps (int or float, optional, defaults to 500) – Number of update steps between two logs if logging_strategy=”steps”. Should be an integer or a float in range [0,1). If smaller than 1, will be interpreted as ratio of total training steps.

  • logging_nan_inf_filter (bool, optional, defaults to True) –

    Whether to filter nan and inf losses for logging. If set to True the loss of every step that is nan or inf is filtered and the average loss of the current logging window is taken instead.

    <Tip>

    logging_nan_inf_filter only influences the logging of loss values, it does not change the behavior the gradient is computed or applied to the model.

    </Tip>

  • save_strategy (str or [~trainer_utils.IntervalStrategy], optional, defaults to “steps”) –

    The checkpoint save strategy to adopt during training. Possible values are:

    • ”no”: No save is done during training.

    • ”epoch”: Save is done at the end of each epoch.

    • ”steps”: Save is done every save_steps.

  • save_steps (int or float, optional, defaults to 500) – Number of updates steps before two checkpoint saves if save_strategy=”steps”. Should be an integer or a float in range [0,1). If smaller than 1, will be interpreted as ratio of total training steps.

  • save_total_limit (int, optional) – If a value is passed, will limit the total amount of checkpoints. Deletes the older checkpoints in output_dir. When load_best_model_at_end is enabled, the “best” checkpoint according to metric_for_best_model will always be retained in addition to the most recent ones. For example, for save_total_limit=5 and load_best_model_at_end, the four last checkpoints will always be retained alongside the best model. When save_total_limit=1 and load_best_model_at_end, it is possible that two checkpoints are saved: the last one and the best one (if they are different).

  • save_safetensors (bool, optional, defaults to True) – Use [safetensors](https://huggingface.co/docs/safetensors) saving and loading for state dicts instead of default torch.load and torch.save.

  • save_on_each_node (bool, optional, defaults to False) –

    When doing multi-node distributed training, whether to save models and checkpoints on each node, or only on the main one.

    This should not be activated when the different nodes use the same storage as the files will be saved with the same names for each node.

  • save_only_model (bool, optional, defaults to False) – When checkpointing, whether to only save the model, or also the optimizer, scheduler & rng state. Note that when this is true, you won’t be able to resume training from checkpoint. This enables you to save storage by not storing the optimizer, scheduler & rng state. You can only load the model using from_pretrained with this option set to True.

  • use_cpu (bool, optional, defaults to False) – Whether or not to use cpu. If set to False, we will use cuda or mps device if available.

  • seed (int, optional, defaults to 42) – Random seed that will be set at the beginning of training. To ensure reproducibility across runs, use the [~Trainer.model_init] function to instantiate the model if it has some randomly initialized parameters.

  • data_seed (int, optional) – Random seed to be used with data samplers. If not set, random generators for data sampling will use the same seed as seed. This can be used to ensure reproducibility of data sampling, independent of the model seed.

  • jit_mode_eval (bool, optional, defaults to False) – Whether or not to use PyTorch jit trace for inference.

  • use_ipex (bool, optional, defaults to False) – Use Intel extension for PyTorch when it is available. [IPEX installation](https://github.com/intel/intel-extension-for-pytorch).

  • bf16 (bool, optional, defaults to False) – Whether to use bf16 16-bit (mixed) precision training instead of 32-bit training. Requires Ampere or higher NVIDIA architecture or using CPU (use_cpu) or Ascend NPU. This is an experimental API and it may change.

  • fp16 (bool, optional, defaults to False) – Whether to use fp16 16-bit (mixed) precision training instead of 32-bit training.

  • fp16_opt_level (str, optional, defaults to ‘O1’) – For fp16 training, Apex AMP optimization level selected in [‘O0’, ‘O1’, ‘O2’, and ‘O3’]. See details on the [Apex documentation](https://nvidia.github.io/apex/amp).

  • fp16_backend (str, optional, defaults to “auto”) – This argument is deprecated. Use half_precision_backend instead.

  • half_precision_backend (str, optional, defaults to “auto”) – The backend to use for mixed precision training. Must be one of “auto”, “apex”, “cpu_amp”. “auto” will use CPU/CUDA AMP or APEX depending on the PyTorch version detected, while the other choices will force the requested backend.

  • bf16_full_eval (bool, optional, defaults to False) – Whether to use full bfloat16 evaluation instead of 32-bit. This will be faster and save memory but can harm metric values. This is an experimental API and it may change.

  • fp16_full_eval (bool, optional, defaults to False) – Whether to use full float16 evaluation instead of 32-bit. This will be faster and save memory but can harm metric values.

  • tf32 (bool, optional) – Whether to enable the TF32 mode, available in Ampere and newer GPU architectures. The default value depends on PyTorch’s version default of torch.backends.cuda.matmul.allow_tf32. For more details please refer to the [TF32](https://huggingface.co/docs/transformers/performance#tf32) documentation. This is an experimental API and it may change.

  • local_rank (int, optional, defaults to -1) – Rank of the process during distributed training.

  • ddp_backend (str, optional) – The backend to use for distributed training. Must be one of “nccl”, “mpi”, “ccl”, “gloo”, “hccl”.

  • tpu_num_cores (int, optional) – When training on TPU, the number of TPU cores (automatically passed by launcher script).

  • dataloader_drop_last (bool, optional, defaults to False) – Whether to drop the last incomplete batch (if the length of the dataset is not divisible by the batch size) or not.

  • eval_steps (int or float, optional) – Number of update steps between two evaluations if evaluation_strategy=”steps”. Will default to the same value as logging_steps if not set. Should be an integer or a float in range [0,1). If smaller than 1, will be interpreted as ratio of total training steps.

  • dataloader_num_workers (int, optional, defaults to 0) – Number of subprocesses to use for data loading (PyTorch only). 0 means that the data will be loaded in the main process.

  • past_index (int, optional, defaults to -1) – Some models like [TransformerXL](../model_doc/transformerxl) or [XLNet](../model_doc/xlnet) can make use of the past hidden states for their predictions. If this argument is set to a positive int, the Trainer will use the corresponding output (usually index 2) as the past state and feed it to the model at the next training step under the keyword argument mems.

  • run_name (str, optional) – A descriptor for the run. Typically used for [wandb](https://www.wandb.com/) and [mlflow](https://www.mlflow.org/) logging.

  • disable_tqdm (bool, optional) – Whether or not to disable the tqdm progress bars and table of metrics produced by [~notebook.NotebookTrainingTracker] in Jupyter Notebooks. Will default to True if the logging level is set to warn or lower (default), False otherwise.

  • remove_unused_columns (bool, optional, defaults to True) – Whether or not to automatically remove the columns unused by the model forward method.

  • label_names (List[str], optional) –

    The list of keys in your dictionary of inputs that correspond to the labels.

    Will eventually default to the list of argument names accepted by the model that contain the word “label”, except if the model used is one of the XxxForQuestionAnswering in which case it will also include the [“start_positions”, “end_positions”] keys.

  • load_best_model_at_end (bool, optional, defaults to False) –

    Whether or not to load the best model found during training at the end of training. When this option is enabled, the best checkpoint will always be saved. See [save_total_limit](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments.save_total_limit) for more.

    <Tip>

    When set to True, the parameters save_strategy needs to be the same as evaluation_strategy, and in the case it is “steps”, save_steps must be a round multiple of eval_steps.

    </Tip>

  • metric_for_best_model (str, optional) –

    Use in conjunction with load_best_model_at_end to specify the metric to use to compare two different models. Must be the name of a metric returned by the evaluation with or without the prefix “eval_”. Will default to “loss” if unspecified and load_best_model_at_end=True (to use the evaluation loss).

    If you set this value, greater_is_better will default to True. Don’t forget to set it to False if your metric is better when lower.

  • greater_is_better (bool, optional) –

    Use in conjunction with load_best_model_at_end and metric_for_best_model to specify if better models should have a greater metric or not. Will default to:

    • True if metric_for_best_model is set to a value that isn’t “loss” or “eval_loss”.

    • False if metric_for_best_model is not set, or set to “loss” or “eval_loss”.

  • ignore_data_skip (bool, optional, defaults to False) – When resuming training, whether or not to skip the epochs and batches to get the data loading at the same stage as in the previous training. If set to True, the training will begin faster (as that skipping step can take a long time) but will not yield the same results as the interrupted training would have.

  • fsdp (bool, str or list of [~trainer_utils.FSDPOption], optional, defaults to ‘’) –

    Use PyTorch Distributed Parallel Training (in distributed training only).

    A list of options along the following:

    • ”full_shard”: Shard parameters, gradients and optimizer states.

    • ”shard_grad_op”: Shard optimizer states and gradients.

    • ”hybrid_shard”: Apply FULL_SHARD within a node, and replicate parameters across nodes.

    • ”hybrid_shard_zero2”: Apply SHARD_GRAD_OP within a node, and replicate parameters across nodes.

    • ”offload”: Offload parameters and gradients to CPUs (only compatible with “full_shard” and “shard_grad_op”).

    • ”auto_wrap”: Automatically recursively wrap layers with FSDP using default_auto_wrap_policy.

  • fsdp_config (str or dict, optional) –

    Config to be used with fsdp (Pytorch Distributed Parallel Training). The value is either a location of fsdp json config file (e.g., fsdp_config.json) or an already loaded json file as dict.

    A List of config and its options:
    • min_num_params (int, optional, defaults to 0):

      FSDP’s minimum number of parameters for Default Auto Wrapping. (useful only when fsdp field is passed).

    • transformer_layer_cls_to_wrap (List[str], optional):

      List of transformer layer class names (case-sensitive) to wrap, e.g, BertLayer, GPTJBlock, T5Block …. (useful only when fsdp flag is passed).

    • backward_prefetch (str, optional)

      FSDP’s backward prefetch mode. Controls when to prefetch next set of parameters (useful only when fsdp field is passed).

      A list of options along the following:

      • ”backward_pre” : Prefetches the next set of parameters before the current set of parameter’s gradient

        computation.

      • ”backward_post” : This prefetches the next set of parameters after the current set of parameter’s

        gradient computation.

    • forward_prefetch (bool, optional, defaults to False)
      FSDP’s forward prefetch mode (useful only when fsdp field is passed).

      If “True”, then FSDP explicitly prefetches the next upcoming all-gather while executing in the forward pass.

    • limit_all_gathers (bool, optional, defaults to False)
      FSDP’s limit_all_gathers (useful only when fsdp field is passed).

      If “True”, FSDP explicitly synchronizes the CPU thread to prevent too many in-flight all-gathers.

    • use_orig_params (bool, optional, defaults to True)

      If “True”, allows non-uniform requires_grad during init, which means support for interspersed frozen and trainable paramteres. Useful in cases such as parameter-efficient fine-tuning. Please refer this [blog](https://dev-discuss.pytorch.org/t/rethinking-pytorch-fully-sharded-data-parallel-fsdp-from-first-principles/1019

    • sync_module_states (bool, optional, defaults to True)

      If “True”, each individually wrapped FSDP unit will broadcast module parameters from rank 0 to ensure they are the same across all ranks after initialization

    • activation_checkpointing (bool, optional, defaults to False):

      If “True”, activation checkpointing is a technique to reduce memory usage by clearing activations of certain layers and recomputing them during a backward pass. Effectively, this trades extra computation time for reduced memory usage.

    • xla (bool, optional, defaults to False):

      Whether to use PyTorch/XLA Fully Sharded Data Parallel Training. This is an experimental feature and its API may evolve in the future.

    • xla_fsdp_settings (dict, optional)

      The value is a dictionary which stores the XLA FSDP wrapping parameters.

      For a complete list of options, please see [here]( https://github.com/pytorch/xla/blob/master/torch_xla/distributed/fsdp/xla_fully_sharded_data_parallel.py).

    • xla_fsdp_grad_ckpt (bool, optional, defaults to False):

      Will use gradient checkpointing over each nested XLA FSDP wrapped layer. This setting can only be used when the xla flag is set to true, and an auto wrapping policy is specified through fsdp_min_num_params or fsdp_transformer_layer_cls_to_wrap.

  • deepspeed (str or dict, optional) – Use [Deepspeed](https://github.com/microsoft/deepspeed). This is an experimental feature and its API may evolve in the future. The value is either the location of DeepSpeed json config file (e.g., ds_config.json) or an already loaded json file as a dict

  • label_smoothing_factor (float, optional, defaults to 0.0) – The label smoothing factor to use. Zero means no label smoothing, otherwise the underlying onehot-encoded labels are changed from 0s and 1s to label_smoothing_factor/num_labels and 1 - label_smoothing_factor + label_smoothing_factor/num_labels respectively.

  • debug (str or list of [~debug_utils.DebugOption], optional, defaults to “”) –

    Enable one or more debug features. This is an experimental feature.

    Possible options are:

    • ”underflow_overflow”: detects overflow in model’s input/outputs and reports the last frames that led to the event

    • ”tpu_metrics_debug”: print debug metrics on TPU

    The options should be separated by whitespaces.

  • optim (str or [training_args.OptimizerNames], optional, defaults to “adamw_torch”) – The optimizer to use: adamw_hf, adamw_torch, adamw_torch_fused, adamw_apex_fused, adamw_anyprecision or adafactor.

  • optim_args (str, optional) – Optional arguments that are supplied to AnyPrecisionAdamW.

  • group_by_length (bool, optional, defaults to False) – Whether or not to group together samples of roughly the same length in the training dataset (to minimize padding applied and be more efficient). Only useful if applying dynamic padding.

  • length_column_name (str, optional, defaults to “length”) – Column name for precomputed lengths. If the column exists, grouping by length will use these values rather than computing them on train startup. Ignored unless group_by_length is True and the dataset is an instance of Dataset.

  • report_to (str or List[str], optional, defaults to “all”) – The list of integrations to report the results and logs to. Supported platforms are “azure_ml”, “clearml”, “codecarbon”, “comet_ml”, “dagshub”, “dvclive”, “flyte”, “mlflow”, “neptune”, “tensorboard”, and “wandb”. Use “all” to report to all integrations installed, “none” for no integrations.

  • ddp_find_unused_parameters (bool, optional) – When using distributed training, the value of the flag find_unused_parameters passed to DistributedDataParallel. Will default to False if gradient checkpointing is used, True otherwise.

  • ddp_bucket_cap_mb (int, optional) – When using distributed training, the value of the flag bucket_cap_mb passed to DistributedDataParallel.

  • ddp_broadcast_buffers (bool, optional) – When using distributed training, the value of the flag broadcast_buffers passed to DistributedDataParallel. Will default to False if gradient checkpointing is used, True otherwise.

  • dataloader_pin_memory (bool, optional, defaults to True) – Whether you want to pin memory in data loaders or not. Will default to True.

  • dataloader_persistent_workers (bool, optional, defaults to False) – If True, the data loader will not shut down the worker processes after a dataset has been consumed once. This allows to maintain the workers Dataset instances alive. Can potentially speed up training, but will increase RAM usage. Will default to False.

  • skip_memory_metrics (bool, optional, defaults to True) – Whether to skip adding of memory profiler reports to metrics. This is skipped by default because it slows down the training and evaluation speed.

  • push_to_hub (bool, optional, defaults to False) –

    Whether or not to push the model to the Hub every time the model is saved. If this is activated, output_dir will begin a git directory synced with the repo (determined by hub_model_id) and the content will be pushed each time a save is triggered (depending on your save_strategy). Calling [~Trainer.save_model] will also trigger a push.

    <Tip warning={true}>

    If output_dir exists, it needs to be a local clone of the repository to which the [Trainer] will be pushed.

    </Tip>

  • resume_from_checkpoint (str, optional) – The path to a folder with a valid checkpoint for your model. This argument is not directly used by [Trainer], it’s intended to be used by your training/evaluation scripts instead. See the [example scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details.

  • hub_model_id (str, optional) –

    The name of the repository to keep in sync with the local output_dir. It can be a simple model ID in which case the model will be pushed in your namespace. Otherwise it should be the whole repository name, for instance “user_name/model”, which allows you to push to an organization you are a member of with “organization_name/model”. Will default to user_name/output_dir_name with output_dir_name being the name of output_dir.

    Will default to the name of output_dir.

  • hub_strategy (str or [~trainer_utils.HubStrategy], optional, defaults to “every_save”) –

    Defines the scope of what is pushed to the Hub and when. Possible values are:

    • ”end”: push the model, its configuration, the tokenizer (if passed along to the [Trainer]) and a draft of a model card when the [~Trainer.save_model] method is called.

    • ”every_save”: push the model, its configuration, the tokenizer (if passed along to the [Trainer]) and a draft of a model card each time there is a model save. The pushes are asynchronous to not block training, and in case the save are very frequent, a new push is only attempted if the previous one is finished. A last push is made with the final model at the end of training.

    • ”checkpoint”: like “every_save” but the latest checkpoint is also pushed in a subfolder named last-checkpoint, allowing you to resume training easily with trainer.train(resume_from_checkpoint=”last-checkpoint”).

    • ”all_checkpoints”: like “checkpoint” but all checkpoints are pushed like they appear in the output folder (so you will get one checkpoint folder per folder in your final repository)

  • hub_token (str, optional) – The token to use to push the model to the Hub. Will default to the token in the cache folder obtained with huggingface-cli login.

  • hub_private_repo (bool, optional, defaults to False) – If True, the Hub repo will be set to private.

  • hub_always_push (bool, optional, defaults to False) – Unless this is True, the Trainer will skip pushing a checkpoint when the previous push is not finished.

  • gradient_checkpointing (bool, optional, defaults to False) – If True, use gradient checkpointing to save memory at the expense of slower backward pass.

  • gradient_checkpointing_kwargs (dict, optional, defaults to None) – Key word arguments to be passed to the gradient_checkpointing_enable method.

  • include_inputs_for_metrics (bool, optional, defaults to False) – Whether or not the inputs will be passed to the compute_metrics function. This is intended for metrics that need inputs, predictions and references for scoring calculation in Metric class.

  • auto_find_batch_size (bool, optional, defaults to False) – Whether to find a batch size that will fit into memory automatically through exponential decay, avoiding CUDA Out-of-Memory errors. Requires accelerate to be installed (pip install accelerate)

  • full_determinism (bool, optional, defaults to False) – If True, [enable_full_determinism] is called instead of [set_seed] to ensure reproducible results in distributed training. Important: this will negatively impact the performance, so only use it for debugging.

  • torchdynamo (str, optional) – If set, the backend compiler for TorchDynamo. Possible choices are “eager”, “aot_eager”, “inductor”, “nvfuser”, “aot_nvfuser”, “aot_cudagraphs”, “ofi”, “fx2trt”, “onnxrt” and “ipex”.

  • ray_scope (str, optional, defaults to “last”) – The scope to use when doing hyperparameter search with Ray. By default, “last” will be used. Ray will then use the last checkpoint of all trials, compare those, and select the best one. However, other options are also available. See the [Ray documentation]( https://docs.ray.io/en/latest/tune/api_docs/analysis.html#ray.tune.ExperimentAnalysis.get_best_trial) for more options.

  • ddp_timeout (int, optional, defaults to 1800) – The timeout for torch.distributed.init_process_group calls, used to avoid GPU socket timeouts when performing slow operations in distributed runnings. Please refer the [PyTorch documentation] (https://pytorch.org/docs/stable/distributed.html#torch.distributed.init_process_group) for more information.

  • use_mps_device (bool, optional, defaults to False) – This argument is deprecated.`mps` device will be used if it is available similar to cuda device.

  • torch_compile (bool, optional, defaults to False) –

    Whether or not to compile the model using PyTorch 2.0 [torch.compile](https://pytorch.org/get-started/pytorch-2.0/).

    This will use the best defaults for the [torch.compile API](https://pytorch.org/docs/stable/generated/torch.compile.html?highlight=torch+compile#torch.compile). You can customize the defaults with the argument torch_compile_backend and torch_compile_mode but we don’t guarantee any of them will work as the support is progressively rolled in in PyTorch.

    This flag and the whole compile API is experimental and subject to change in future releases.

  • torch_compile_backend (str, optional) –

    The backend to use in torch.compile. If set to any value, torch_compile will be set to True.

    Refer to the PyTorch doc for possible values and note that they may change across PyTorch versions.

    This flag is experimental and subject to change in future releases.

  • torch_compile_mode (str, optional) –

    The mode to use in torch.compile. If set to any value, torch_compile will be set to True.

    Refer to the PyTorch doc for possible values and note that they may change across PyTorch versions.

    This flag is experimental and subject to change in future releases.

  • split_batches (bool, optional) –

    Whether or not the accelerator should split the batches yielded by the dataloaders across the devices during distributed training. If

    set to True, the actual batch size used will be the same on any kind of distributed processes, but it must be a

    round multiple of the number of processes you are using (such as GPUs).

  • include_tokens_per_second (bool, optional) –

    Whether or not to compute the number of tokens per second per device for training speed metrics.

    This will iterate over the entire training dataloader once beforehand,

    and will slow down the entire process.

  • include_num_input_tokens_seen (bool, optional) –

    Whether or not to track the number of input tokens seen throughout training.

    May be slower in distributed training as gather operations must be called.

  • neftune_noise_alpha (Optional[float]) – If not None, this will activate NEFTune noise embeddings. This can drastically improve model performance for instruction fine-tuning. Check out the [original paper](https://arxiv.org/abs/2310.05914) and the [original code](https://github.com/neelsjain/NEFTune). Support transformers PreTrainedModel and also PeftModel from peft.

  • use_lora (bool, optional, defaults to True) – Whether to use LoRA training.

  • lora_r (int, optional, defaults to 8) – Lora R dimension.

  • lora_alpha (int, optional, defaults to 16) – Lora alpha.

  • lora_dropout (float, optional, defaults to 0.05) – Lora dropout.

  • lora_target_modules (List[str], optional, defaults to None) – Lora target modules. If None, will be automatically inferred.

  • lora_bias (str, optional, defaults to “none”) – Lora bias.

  • max_length (int, optional, defaults to 512) – Maximum source sequence length during training.

  • log_to_db (bool, optional, defaults to True) –

    Log training to db. If True, will log checkpoint to superduperdb,

    but need ray cluster can access to db.

    If can’t access to db, please set it to False.

bits: int | None = None#
build()[source]#
log_to_db: bool = False#
lora_alpha: int = 16#
lora_bias: Literal['none', 'all', 'lora_only'] = 'none'#
lora_dropout: float = 0.05#
lora_r: int = 8#
lora_target_modules: List[str] | None = None#
max_length: int = 512#
use_lora: bool = True#
superduperdb.ext.llm.training.create_quantization_config(config: LLMTrainingArguments)[source]#

Create quantization config for LLM training.

superduperdb.ext.llm.training.get_lora_target_modules(model, bits)[source]#

Find the LoRA target modules in the model.

superduperdb.ext.llm.training.handle_ray_results(db, llm, results)[source]#

Handle the ray results. Will save the checkpoint to db if db and llm provided.

superduperdb.ext.llm.training.prepare_lora_training(model, config: LLMTrainingArguments)[source]#

Prepare LoRA training for the model. Get the LoRA target modules and convert the model to peft model.

superduperdb.ext.llm.training.ray_train(training_args: LLMTrainingArguments, train_dataset: Dataset, eval_datasets: Dataset | Dict[str, Dataset], model_kwargs: dict, tokenizer_kwargs: dict, trainer_prepare_func: Callable | None = None, callbacks=None, **kwargs)[source]#

Base training function for LLM model. :param training_args: training Arguments, see LLMTrainingArguments :param train_dataset: training dataset,

can be huggingface datasets.Dataset or ray.data.Dataset

Parameters:
  • eval_datasets – evaluation dataset, can be a dict of datasets

  • model_kwargs – model kwargs for AutoModelForCausalLM

  • tokenizer_kwargs – tokenizer kwargs for AutoTokenizer

  • trainer_prepare_func – function to prepare trainer This function will be called after the trainer is created, we can add some custom settings to the trainer

  • callbacks – list of callbacks will be added to the trainer

  • **kwargs

    other kwargs for Trainer All the kwargs will be passed to Trainer, make sure the Trainer support these kwargs

superduperdb.ext.llm.training.tokenize(tokenizer, example, X, y)[source]#

Function to tokenize the example.

superduperdb.ext.llm.training.train(training_config: dict, train_dataset: Dataset, eval_datasets: Dataset | Dict[str, Dataset], model_kwargs: dict, tokenizer_kwargs: dict, X: str | None = None, y: str | None = None, db: Datalayer | None = None, llm: LLM | None = None, on_ray: bool | None = False, ray_address: str | None = None, ray_configs: dict | None = None, **kwargs)[source]#

Train LLM model on specified dataset. The training process can be run on these following modes: - Local node without ray, but only support single GPU - Local node with ray, support multi-nodes and multi-GPUs - Remote node with ray, support multi-nodes and multi-GPUs

If run locally, will use train_func to train the model.

Can log the training process to db if db and llm provided. Will reuse the db and llm from the current process.

If run on ray, will use ray_train to train the model.

Can log the training process to db if db and llm provided. Will rebuild the db and llm for the new process that can access to db. The ray cluster must can access to db.

Parameters: :param training_config: training config for LLMTrainingArguments :param train_dataset: training dataset :param eval_datasets: evaluation dataset, can be a dict of datasets :param model_kwargs: model kwargs for AutoModelForCausalLM :param tokenizer_kwargs: tokenizer kwargs for AutoTokenizer :param X: column name for input :param y: column name for output :param db: datalayer, used for creating LLMCallback :param llm: llm model, used for creating LLMCallback :param on_ray: whether to use ray, if True, will use ray_train :param ray_address: ray address, if not None, will run on ray cluster :param ray_configs: ray configs, must provide if using ray

superduperdb.ext.llm.training.train_func(training_args: LLMTrainingArguments, train_dataset: Dataset, eval_datasets: Dataset | Dict[str, Dataset], model_kwargs: dict, tokenizer_kwargs: dict, trainer_prepare_func: Callable | None = None, callbacks=None, **kwargs)[source]#

Base training function for LLM model. :param training_args: training Arguments, see LLMTrainingArguments :param train_dataset: training dataset,

can be huggingface datasets.Dataset or ray.data.Dataset

Parameters:
  • eval_datasets – evaluation dataset, can be a dict of datasets

  • model_kwargs – model kwargs for AutoModelForCausalLM

  • tokenizer_kwargs – tokenizer kwargs for AutoTokenizer

  • trainer_prepare_func – function to prepare trainer This function will be called after the trainer is created, we can add some custom settings to the trainer

  • callbacks – list of callbacks will be added to the trainer

  • **kwargs

    other kwargs for Trainer All the kwargs will be passed to Trainer, make sure the Trainer support these kwargs

superduperdb.ext.llm.utils module#

class superduperdb.ext.llm.utils.Prompter(prompt_template: str = '{input}', prompt_func: Callable | None = None)[source]#

Bases: object

prompt_func: Callable | None = None#
prompt_template: str = '{input}'#

superduperdb.ext.llm.vllm module#

class superduperdb.ext.llm.vllm.VllmAPI(identifier: str, artifacts: dc.InitVar[t.Optional[t.Dict]] = None, prompt_template: str = '{input}', prompt_func: ~typing.Callable | None = None, max_batch_size: int | None = 4, inference_kwargs: dict = <factory>, api_url: str = '', *, datatype: EncoderArg = None, output_schema: t.Optional[Schema] = None, flatten: bool = False, preprocess: t.Optional[t.Callable] = None, postprocess: t.Optional[t.Callable] = None, collate_fn: t.Optional[t.Callable] = None, batch_predict: bool = False, takes_context: bool = False, metrics: t.Sequence[t.Union[str, Metric, None]] = (), model_update_kwargs: t.Dict = <factory>, validation_sets: t.Optional[t.Sequence[t.Union[str, Dataset]]] = None, predict_X: t.Optional[str] = None, predict_select: t.Optional[CompoundSelect] = None, predict_max_chunk_size: t.Optional[int] = None, predict_kwargs: t.Optional[t.Dict] = None)[source]#

Bases: BaseLLMAPI

Wrapper for requesting the vLLM API service (API Server format, started by vllm.entrypoints.api_server)

Parameters:
  • api_url – The URL for the API.

  • prompt_template – The template to use for the prompt.

  • prompt_func – The function to use for the prompt.

  • max_batch_size – The maximum batch size to use for batch generation.

  • inference_kwargs – Parameters used during inference.

public_api(beta): This API is in beta and may change before becoming stable.

_generate(prompt: str, **kwargs) str[source]#

Batch generate text from a prompt.

build_post_data(prompt: str, **kwargs: dict[str, Any]) dict[str, Any][source]#
class superduperdb.ext.llm.vllm.VllmModel(identifier: str = '', artifacts: dc.InitVar[t.Optional[t.Dict]] = None, prompt_template: str = '{input}', prompt_func: ~typing.Callable | None = None, max_batch_size: int | None = 4, inference_kwargs: dict = <factory>, model_name: str = '', on_ray: bool = False, ray_address: str | None = None, ray_config: dict = <factory>, tensor_parallel_size: int = 1, trust_remote_code: bool = True, vllm_kwargs: dict = <factory>, *, datatype: EncoderArg = None, output_schema: t.Optional[Schema] = None, flatten: bool = False, preprocess: t.Optional[t.Callable] = None, postprocess: t.Optional[t.Callable] = None, collate_fn: t.Optional[t.Callable] = None, batch_predict: bool = False, takes_context: bool = False, metrics: t.Sequence[t.Union[str, Metric, None]] = (), model_update_kwargs: t.Dict = <factory>, validation_sets: t.Optional[t.Sequence[t.Union[str, Dataset]]] = None, predict_X: t.Optional[str] = None, predict_select: t.Optional[CompoundSelect] = None, predict_max_chunk_size: t.Optional[int] = None, predict_kwargs: t.Optional[t.Dict] = None)[source]#

Bases: BaseLLMModel

Load a large language model from VLLM.

Parameters:
  • model_name – The name of the model to use.

  • trust_remote_code – Whether to trust remote code.

  • dtype – The data type to use.

  • model_name – The name of the model to use.

  • on_ray – Whether to run the model on Ray.

  • ray_config – The Ray config to use.

  • ray_addredd – The address of the ray cluster.

  • prompt_template – The template to use for the prompt.

  • prompt_func – The function to use for the prompt.

  • max_batch_size – The maximum batch size to use for batch generation.

  • inference_kwargs – Parameters used during inference.

public_api(beta): This API is in beta and may change before becoming stable.

init()[source]#
tensor_parallel_size: int = 1#
trust_remote_code: bool = True#
vllm_kwargs: dict#

Module contents#

class superduperdb.ext.llm.BaseLLMAPI(identifier: str, artifacts: dc.InitVar[t.Optional[t.Dict]] = None, prompt_template: str = '{input}', prompt_func: ~typing.Callable | None = None, max_batch_size: int | None = 4, inference_kwargs: dict = <factory>, api_url: str = '', *, datatype: EncoderArg = None, output_schema: t.Optional[Schema] = None, flatten: bool = False, preprocess: t.Optional[t.Callable] = None, postprocess: t.Optional[t.Callable] = None, collate_fn: t.Optional[t.Callable] = None, batch_predict: bool = False, takes_context: bool = False, metrics: t.Sequence[t.Union[str, Metric, None]] = (), model_update_kwargs: t.Dict = <factory>, validation_sets: t.Optional[t.Sequence[t.Union[str, Dataset]]] = None, predict_X: t.Optional[str] = None, predict_select: t.Optional[CompoundSelect] = None, predict_max_chunk_size: t.Optional[int] = None, predict_kwargs: t.Optional[t.Dict] = None)[source]#

Bases: _BaseLLM

Parameters:
  • api_url – The URL for the API.

  • prompt_template – The template to use for the prompt.

  • prompt_func – The function to use for the prompt.

  • max_batch_size – The maximum batch size to use for batch generation.

  • inference_kwargs – Parameters used during inference.

_batch_generate(prompts: List[str], **kwargs: Any) List[str][source]#

Base method to batch generate text from a list of prompts using multi-threading. Handles exceptions in _generate method.

_generate_wrapper(prompt: str, **kwargs: Any) str[source]#

Wrapper for the _generate method to handle exceptions.

api_url: str = ''#
identifier: str#
inference_kwargs: dict#
init()[source]#
model_update_kwargs: t.Dict#
class superduperdb.ext.llm.BaseLLMModel(identifier: str = '', artifacts: dc.InitVar[t.Optional[t.Dict]] = None, prompt_template: str = '{input}', prompt_func: ~typing.Callable | None = None, max_batch_size: int | None = 4, inference_kwargs: dict = <factory>, model_name: str = '', on_ray: bool = False, ray_address: str | None = None, ray_config: dict = <factory>, *, datatype: EncoderArg = None, output_schema: t.Optional[Schema] = None, flatten: bool = False, preprocess: t.Optional[t.Callable] = None, postprocess: t.Optional[t.Callable] = None, collate_fn: t.Optional[t.Callable] = None, batch_predict: bool = False, takes_context: bool = False, metrics: t.Sequence[t.Union[str, Metric, None]] = (), model_update_kwargs: t.Dict = <factory>, validation_sets: t.Optional[t.Sequence[t.Union[str, Dataset]]] = None, predict_X: t.Optional[str] = None, predict_select: t.Optional[CompoundSelect] = None, predict_max_chunk_size: t.Optional[int] = None, predict_kwargs: t.Optional[t.Dict] = None)[source]#

Bases: _BaseLLM

Parameters:
  • model_name – The name of the model to use.

  • on_ray – Whether to run the model on Ray.

  • ray_config – The Ray config to use.

  • ray_addredd – The address of the ray cluster.

  • prompt_template – The template to use for the prompt.

  • prompt_func – The function to use for the prompt.

  • max_batch_size – The maximum batch size to use for batch generation.

  • inference_kwargs – Parameters used during inference.

identifier: str = ''#
inference_kwargs: dict#
model_name: str = ''#
model_update_kwargs: t.Dict#
on_ray: bool = False#
ray_address: str | None = None#
ray_config: dict#
class superduperdb.ext.llm.BaseOpenAI(identifier: str = '', artifacts: dc.InitVar[t.Optional[t.Dict]] = None, prompt_template: str = '{input}', prompt_func: ~typing.Callable | None = None, max_batch_size: int | None = 4, inference_kwargs: dict = <factory>, api_url: str = '', openai_api_base: str = 'https://api.openai.com/v1', openai_api_key: str | None = None, model_name: str = 'gpt-3.5-turbo', chat: bool = True, system_prompt: str | None = None, user_role: str = 'user', system_role: str = 'system', *, datatype: EncoderArg = None, output_schema: t.Optional[Schema] = None, flatten: bool = False, preprocess: t.Optional[t.Callable] = None, postprocess: t.Optional[t.Callable] = None, collate_fn: t.Optional[t.Callable] = None, batch_predict: bool = False, takes_context: bool = False, metrics: t.Sequence[t.Union[str, Metric, None]] = (), model_update_kwargs: t.Dict = <factory>, validation_sets: t.Optional[t.Sequence[t.Union[str, Dataset]]] = None, predict_X: t.Optional[str] = None, predict_select: t.Optional[CompoundSelect] = None, predict_max_chunk_size: t.Optional[int] = None, predict_kwargs: t.Optional[t.Dict] = None)[source]#

Bases: BaseLLMAPI

Parameters:
  • openai_api_base – The base URL for the OpenAI API.

  • openai_api_key – The API key to use for the OpenAI API.

  • model_name – The name of the model to use.

  • chat – Whether to use the chat API or the completion API. Defaults to False.

  • system_prompt – The prompt to use for the system.

  • user_role – The role to use for the user.

  • system_role – The role to use for the system.

  • prompt_template – The template to use for the prompt.

  • prompt_func – The function to use for the prompt.

  • max_batch_size – The maximum batch size to use for batch generation.

  • inference_kwargs – Parameters used during inference.

_chat_generate(content: str, **kwargs: Any) str[source]#

Generate a completion for a given prompt with chat format. :param prompt: The prompt to generate a completion for. :param kwargs: Any additional arguments to pass to the API.

_prompt_generate(prompt: str, **kwargs: Any) str[source]#

Generate a completion for a given prompt with prompt format.

chat: bool = True#
identifier: str = ''#
inference_kwargs: dict#
init()[source]#
model_name: str = 'gpt-3.5-turbo'#
model_update_kwargs: t.Dict#
openai_api_base: str = 'https://api.openai.com/v1'#
openai_api_key: str | None = None#
system_prompt: str | None = None#
system_role: str = 'system'#
user_role: str = 'user'#
class superduperdb.ext.llm.LLM(identifier: str = '', artifacts: dc.InitVar[t.Optional[t.Dict]] = None, object: ~transformers.trainer.Trainer | None = None, model_name_or_path: str = 'facebook/opt-125m', bits: int | None = None, adapter_id: str | None = None, model_kwargs: ~typing.Dict = <factory>, tokenizer_kwargs: ~typing.Dict = <factory>, prompt_template: str = '{input}', prompt_func: ~typing.Callable | None = None, *, datatype: EncoderArg = None, output_schema: t.Optional[Schema] = None, flatten: bool = False, preprocess: t.Optional[t.Callable] = None, postprocess: t.Optional[t.Callable] = None, collate_fn: t.Optional[t.Callable] = None, batch_predict: bool = False, takes_context: bool = False, metrics: t.Sequence[t.Union[str, Metric, None]] = (), model_update_kwargs: dict = <factory>, validation_sets: t.Optional[t.Sequence[t.Union[str, Dataset]]] = None, predict_X: t.Optional[str] = None, predict_select: t.Optional[CompoundSelect] = None, predict_max_chunk_size: t.Optional[int] = None, predict_kwargs: t.Optional[t.Dict] = None, model_to_device_method: t.Optional[str] = None, metric_values: t.Optional[t.Dict] = <factory>, predict_method: t.Optional[str] = None, device: str = 'cpu', preferred_devices: t.Union[None, t.Sequence[str]] = ('cuda', 'mps', 'cpu'), training_configuration: t.Union[str, _TrainingConfiguration, None] = None, train_X: t.Optional[str] = None, train_y: t.Optional[str] = None, train_select: t.Optional[CompoundSelect] = None)[source]#

Bases: Model

LLM model based on transformers library. Parameters: : param identifier: model identifier : param model_name_or_path: model name or path : param bits: quantization bits, [4, 8], default is None : param adapter_id: adapter id, default is None

Add a adapter to the base model for inference. When model_name_or_path, bits, model_kwargs, tokenizer_kwargs are the same, will share the same base model and tokenizer cache.

: param model_kwargs: model kwargs,

all the kwargs will pass to transformers.AutoModelForCausalLM.from_pretrained

: param tokenizer_kwagrs: tokenizer kwargs,

all the kwargs will pass to transformers.AutoTokenizer.from_pretrained

: param prompt_template: prompt template, default is “{input}” : param prompt_func: prompt function, default is None

_base_generate(X: Any, **kwargs)[source]#

Generate text. Can overwrite this method to support more inference methods.

_generate(X: Any, adapter_name=None, **kwargs)[source]#

Private method for Model.to_call method. Support inference by multi-lora adapters.

adapter_id: str | None = None#
add_adapter(model_id, adapter_name: str)[source]#
bits: int | None = None#
get_compute_metrics(metrics)[source]#
get_datasets(X, y, db, select, db_validation_sets: Sequence[str | Dataset] | None = None, data_prefetch: bool = False, prefetch_size: int = 10000)[source]#
identifier: str = ''#
init()[source]#
init_model_and_tokenizer()[source]#
metric_values: t.Optional[t.Dict]#
model_kwargs: Dict#
model_name_or_path: str = 'facebook/opt-125m'#
model_update_kwargs: dict#
object: Trainer | None = None#
post_create(db: Datalayer) None[source]#

Called after the first time this component is created. Generally used if self.version is important in this logic.

Parameters:

db – the db that creates the component

prompt_func: Callable | None = None#
prompt_template: str = '{input}'#
tokenizer_kwargs: Dict#
superduperdb.ext.llm.LLMTrainingConfiguration(output_dir: str, overwrite_output_dir: bool = False, do_train: bool = False, do_eval: bool = False, do_predict: bool = False, evaluation_strategy: ~transformers.trainer_utils.IntervalStrategy | str = 'no', prediction_loss_only: bool = False, per_device_train_batch_size: int = 8, per_device_eval_batch_size: int = 8, per_gpu_train_batch_size: int | None = None, per_gpu_eval_batch_size: int | None = None, gradient_accumulation_steps: int = 1, eval_accumulation_steps: int | None = None, eval_delay: float | None = 0, learning_rate: float = 5e-05, weight_decay: float = 0.0, adam_beta1: float = 0.9, adam_beta2: float = 0.999, adam_epsilon: float = 1e-08, max_grad_norm: float = 1.0, num_train_epochs: float = 3.0, max_steps: int = -1, lr_scheduler_type: ~transformers.trainer_utils.SchedulerType | str = 'linear', lr_scheduler_kwargs: ~typing.Dict | None = <factory>, warmup_ratio: float = 0.0, warmup_steps: int = 0, log_level: str | None = 'passive', log_level_replica: str | None = 'warning', log_on_each_node: bool = True, logging_dir: str | None = None, logging_strategy: ~transformers.trainer_utils.IntervalStrategy | str = 'steps', logging_first_step: bool = False, logging_steps: float = 500, logging_nan_inf_filter: bool = True, save_strategy: ~transformers.trainer_utils.IntervalStrategy | str = 'steps', save_steps: float = 500, save_total_limit: int | None = None, save_safetensors: bool | None = True, save_on_each_node: bool = False, save_only_model: bool = False, no_cuda: bool = False, use_cpu: bool = False, use_mps_device: bool = False, seed: int = 42, data_seed: int | None = None, jit_mode_eval: bool = False, use_ipex: bool = False, bf16: bool = False, fp16: bool = False, fp16_opt_level: str = 'O1', half_precision_backend: str = 'auto', bf16_full_eval: bool = False, fp16_full_eval: bool = False, tf32: bool | None = None, local_rank: int = -1, ddp_backend: str | None = None, tpu_num_cores: int | None = None, tpu_metrics_debug: bool = False, debug: str | ~typing.List[~transformers.debug_utils.DebugOption] = '', dataloader_drop_last: bool = False, eval_steps: float | None = None, dataloader_num_workers: int = 0, past_index: int = -1, run_name: str | None = None, disable_tqdm: bool | None = None, remove_unused_columns: bool | None = True, label_names: ~typing.List[str] | None = None, load_best_model_at_end: bool | None = False, metric_for_best_model: str | None = None, greater_is_better: bool | None = None, ignore_data_skip: bool = False, fsdp: ~typing.List[~transformers.trainer_utils.FSDPOption] | str | None = '', fsdp_min_num_params: int = 0, fsdp_config: str | None = None, fsdp_transformer_layer_cls_to_wrap: str | None = None, deepspeed: str | None = None, label_smoothing_factor: float = 0.0, optim: ~transformers.training_args.OptimizerNames | str = 'adamw_torch', optim_args: str | None = None, adafactor: bool = False, group_by_length: bool = False, length_column_name: str | None = 'length', report_to: ~typing.List[str] | None = None, ddp_find_unused_parameters: bool | None = None, ddp_bucket_cap_mb: int | None = None, ddp_broadcast_buffers: bool | None = None, dataloader_pin_memory: bool = True, dataloader_persistent_workers: bool = False, skip_memory_metrics: bool = True, use_legacy_prediction_loop: bool = False, push_to_hub: bool = False, resume_from_checkpoint: str | None = None, hub_model_id: str | None = None, hub_strategy: ~transformers.trainer_utils.HubStrategy | str = 'every_save', hub_token: str | None = None, hub_private_repo: bool = False, hub_always_push: bool = False, gradient_checkpointing: bool = False, gradient_checkpointing_kwargs: dict | None = None, include_inputs_for_metrics: bool = False, fp16_backend: str = 'auto', push_to_hub_model_id: str | None = None, push_to_hub_organization: str | None = None, push_to_hub_token: str | None = None, mp_parameters: str = '', auto_find_batch_size: bool = False, full_determinism: bool = False, torchdynamo: str | None = None, ray_scope: str | None = 'last', ddp_timeout: int | None = 1800, torch_compile: bool = False, torch_compile_backend: str | None = None, torch_compile_mode: str | None = None, dispatch_batches: bool | None = None, split_batches: bool | None = False, include_tokens_per_second: bool | None = False, include_num_input_tokens_seen: bool | None = False, neftune_noise_alpha: float = None, use_lora: bool = True, lora_r: int = 8, lora_alpha: int = 16, lora_dropout: float = 0.05, lora_target_modules: ~typing.List[str] | None = None, lora_bias: ~typing.Literal['none', 'all', 'lora_only'] = 'none', bits: int | None = None, max_length: int = 512, log_to_db: bool = False) None#

LLM Training Arguments. Inherits from transformers.TrainingArguments.

TrainingArguments is the subset of the arguments we use in our example scripts which relate to the training loop itself.

Using [HfArgumentParser] we can turn this class into [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the command line.

Parameters:
  • output_dir (str) – The output directory where the model predictions and checkpoints will be written.

  • overwrite_output_dir (bool, optional, defaults to False) – If True, overwrite the content of the output directory. Use this to continue training if output_dir points to a checkpoint directory.

  • do_train (bool, optional, defaults to False) – Whether to run training or not. This argument is not directly used by [Trainer], it’s intended to be used by your training/evaluation scripts instead. See the [example scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details.

  • do_eval (bool, optional) – Whether to run evaluation on the validation set or not. Will be set to True if evaluation_strategy is different from “no”. This argument is not directly used by [Trainer], it’s intended to be used by your training/evaluation scripts instead. See the [example scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details.

  • do_predict (bool, optional, defaults to False) – Whether to run predictions on the test set or not. This argument is not directly used by [Trainer], it’s intended to be used by your training/evaluation scripts instead. See the [example scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details.

  • evaluation_strategy (str or [~trainer_utils.IntervalStrategy], optional, defaults to “no”) –

    The evaluation strategy to adopt during training. Possible values are:

    • ”no”: No evaluation is done during training.

    • ”steps”: Evaluation is done (and logged) every eval_steps.

    • ”epoch”: Evaluation is done at the end of each epoch.

  • prediction_loss_only (bool, optional, defaults to False) – When performing evaluation and generating predictions, only returns the loss.

  • per_device_train_batch_size (int, optional, defaults to 8) – The batch size per GPU/XPU/TPU/MPS/NPU core/CPU for training.

  • per_device_eval_batch_size (int, optional, defaults to 8) – The batch size per GPU/XPU/TPU/MPS/NPU core/CPU for evaluation.

  • gradient_accumulation_steps (int, optional, defaults to 1) –

    Number of updates steps to accumulate the gradients for, before performing a backward/update pass.

    <Tip warning={true}>

    When using gradient accumulation, one step is counted as one step with backward pass. Therefore, logging, evaluation, save will be conducted every gradient_accumulation_steps * xxx_step training examples.

    </Tip>

  • eval_accumulation_steps (int, optional) – Number of predictions steps to accumulate the output tensors for, before moving the results to the CPU. If left unset, the whole predictions are accumulated on GPU/NPU/TPU before being moved to the CPU (faster but requires more memory).

  • eval_delay (float, optional) – Number of epochs or steps to wait for before the first evaluation can be performed, depending on the evaluation_strategy.

  • learning_rate (float, optional, defaults to 5e-5) – The initial learning rate for [AdamW] optimizer.

  • weight_decay (float, optional, defaults to 0) – The weight decay to apply (if not zero) to all layers except all bias and LayerNorm weights in [AdamW] optimizer.

  • adam_beta1 (float, optional, defaults to 0.9) – The beta1 hyperparameter for the [AdamW] optimizer.

  • adam_beta2 (float, optional, defaults to 0.999) – The beta2 hyperparameter for the [AdamW] optimizer.

  • adam_epsilon (float, optional, defaults to 1e-8) – The epsilon hyperparameter for the [AdamW] optimizer.

  • max_grad_norm (float, optional, defaults to 1.0) – Maximum gradient norm (for gradient clipping).

  • num_train_epochs (float, optional, defaults to 3.0) – Total number of training epochs to perform (if not an integer, will perform the decimal part percents of the last epoch before stopping training).

  • max_steps (int, optional, defaults to -1) – If set to a positive number, the total number of training steps to perform. Overrides num_train_epochs. For a finite dataset, training is reiterated through the dataset (if all data is exhausted) until max_steps is reached.

  • lr_scheduler_type (str or [SchedulerType], optional, defaults to “linear”) – The scheduler type to use. See the documentation of [SchedulerType] for all possible values.

  • lr_scheduler_kwargs (‘dict’, optional, defaults to {}) – The extra arguments for the lr_scheduler. See the documentation of each scheduler for possible values.

  • warmup_ratio (float, optional, defaults to 0.0) – Ratio of total training steps used for a linear warmup from 0 to learning_rate.

  • warmup_steps (int, optional, defaults to 0) – Number of steps used for a linear warmup from 0 to learning_rate. Overrides any effect of warmup_ratio.

  • log_level (str, optional, defaults to passive) – Logger log level to use on the main process. Possible choices are the log levels as strings: ‘debug’, ‘info’, ‘warning’, ‘error’ and ‘critical’, plus a ‘passive’ level which doesn’t set anything and keeps the current log level for the Transformers library (which will be “warning” by default).

  • log_level_replica (str, optional, defaults to “warning”) – Logger log level to use on replicas. Same choices as log_level

  • log_on_each_node (bool, optional, defaults to True) – In multinode distributed training, whether to log using log_level once per node, or only on the main node.

  • logging_dir (str, optional) – [TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to output_dir/runs/**CURRENT_DATETIME_HOSTNAME**.

  • logging_strategy (str or [~trainer_utils.IntervalStrategy], optional, defaults to “steps”) –

    The logging strategy to adopt during training. Possible values are:

    • ”no”: No logging is done during training.

    • ”epoch”: Logging is done at the end of each epoch.

    • ”steps”: Logging is done every logging_steps.

  • logging_first_step (bool, optional, defaults to False) – Whether to log and evaluate the first global_step or not.

  • logging_steps (int or float, optional, defaults to 500) – Number of update steps between two logs if logging_strategy=”steps”. Should be an integer or a float in range [0,1). If smaller than 1, will be interpreted as ratio of total training steps.

  • logging_nan_inf_filter (bool, optional, defaults to True) –

    Whether to filter nan and inf losses for logging. If set to True the loss of every step that is nan or inf is filtered and the average loss of the current logging window is taken instead.

    <Tip>

    logging_nan_inf_filter only influences the logging of loss values, it does not change the behavior the gradient is computed or applied to the model.

    </Tip>

  • save_strategy (str or [~trainer_utils.IntervalStrategy], optional, defaults to “steps”) –

    The checkpoint save strategy to adopt during training. Possible values are:

    • ”no”: No save is done during training.

    • ”epoch”: Save is done at the end of each epoch.

    • ”steps”: Save is done every save_steps.

  • save_steps (int or float, optional, defaults to 500) – Number of updates steps before two checkpoint saves if save_strategy=”steps”. Should be an integer or a float in range [0,1). If smaller than 1, will be interpreted as ratio of total training steps.

  • save_total_limit (int, optional) – If a value is passed, will limit the total amount of checkpoints. Deletes the older checkpoints in output_dir. When load_best_model_at_end is enabled, the “best” checkpoint according to metric_for_best_model will always be retained in addition to the most recent ones. For example, for save_total_limit=5 and load_best_model_at_end, the four last checkpoints will always be retained alongside the best model. When save_total_limit=1 and load_best_model_at_end, it is possible that two checkpoints are saved: the last one and the best one (if they are different).

  • save_safetensors (bool, optional, defaults to True) – Use [safetensors](https://huggingface.co/docs/safetensors) saving and loading for state dicts instead of default torch.load and torch.save.

  • save_on_each_node (bool, optional, defaults to False) –

    When doing multi-node distributed training, whether to save models and checkpoints on each node, or only on the main one.

    This should not be activated when the different nodes use the same storage as the files will be saved with the same names for each node.

  • save_only_model (bool, optional, defaults to False) – When checkpointing, whether to only save the model, or also the optimizer, scheduler & rng state. Note that when this is true, you won’t be able to resume training from checkpoint. This enables you to save storage by not storing the optimizer, scheduler & rng state. You can only load the model using from_pretrained with this option set to True.

  • use_cpu (bool, optional, defaults to False) – Whether or not to use cpu. If set to False, we will use cuda or mps device if available.

  • seed (int, optional, defaults to 42) – Random seed that will be set at the beginning of training. To ensure reproducibility across runs, use the [~Trainer.model_init] function to instantiate the model if it has some randomly initialized parameters.

  • data_seed (int, optional) – Random seed to be used with data samplers. If not set, random generators for data sampling will use the same seed as seed. This can be used to ensure reproducibility of data sampling, independent of the model seed.

  • jit_mode_eval (bool, optional, defaults to False) – Whether or not to use PyTorch jit trace for inference.

  • use_ipex (bool, optional, defaults to False) – Use Intel extension for PyTorch when it is available. [IPEX installation](https://github.com/intel/intel-extension-for-pytorch).

  • bf16 (bool, optional, defaults to False) – Whether to use bf16 16-bit (mixed) precision training instead of 32-bit training. Requires Ampere or higher NVIDIA architecture or using CPU (use_cpu) or Ascend NPU. This is an experimental API and it may change.

  • fp16 (bool, optional, defaults to False) – Whether to use fp16 16-bit (mixed) precision training instead of 32-bit training.

  • fp16_opt_level (str, optional, defaults to ‘O1’) – For fp16 training, Apex AMP optimization level selected in [‘O0’, ‘O1’, ‘O2’, and ‘O3’]. See details on the [Apex documentation](https://nvidia.github.io/apex/amp).

  • fp16_backend (str, optional, defaults to “auto”) – This argument is deprecated. Use half_precision_backend instead.

  • half_precision_backend (str, optional, defaults to “auto”) – The backend to use for mixed precision training. Must be one of “auto”, “apex”, “cpu_amp”. “auto” will use CPU/CUDA AMP or APEX depending on the PyTorch version detected, while the other choices will force the requested backend.

  • bf16_full_eval (bool, optional, defaults to False) – Whether to use full bfloat16 evaluation instead of 32-bit. This will be faster and save memory but can harm metric values. This is an experimental API and it may change.

  • fp16_full_eval (bool, optional, defaults to False) – Whether to use full float16 evaluation instead of 32-bit. This will be faster and save memory but can harm metric values.

  • tf32 (bool, optional) – Whether to enable the TF32 mode, available in Ampere and newer GPU architectures. The default value depends on PyTorch’s version default of torch.backends.cuda.matmul.allow_tf32. For more details please refer to the [TF32](https://huggingface.co/docs/transformers/performance#tf32) documentation. This is an experimental API and it may change.

  • local_rank (int, optional, defaults to -1) – Rank of the process during distributed training.

  • ddp_backend (str, optional) – The backend to use for distributed training. Must be one of “nccl”, “mpi”, “ccl”, “gloo”, “hccl”.

  • tpu_num_cores (int, optional) – When training on TPU, the number of TPU cores (automatically passed by launcher script).

  • dataloader_drop_last (bool, optional, defaults to False) – Whether to drop the last incomplete batch (if the length of the dataset is not divisible by the batch size) or not.

  • eval_steps (int or float, optional) – Number of update steps between two evaluations if evaluation_strategy=”steps”. Will default to the same value as logging_steps if not set. Should be an integer or a float in range [0,1). If smaller than 1, will be interpreted as ratio of total training steps.

  • dataloader_num_workers (int, optional, defaults to 0) – Number of subprocesses to use for data loading (PyTorch only). 0 means that the data will be loaded in the main process.

  • past_index (int, optional, defaults to -1) – Some models like [TransformerXL](../model_doc/transformerxl) or [XLNet](../model_doc/xlnet) can make use of the past hidden states for their predictions. If this argument is set to a positive int, the Trainer will use the corresponding output (usually index 2) as the past state and feed it to the model at the next training step under the keyword argument mems.

  • run_name (str, optional) – A descriptor for the run. Typically used for [wandb](https://www.wandb.com/) and [mlflow](https://www.mlflow.org/) logging.

  • disable_tqdm (bool, optional) – Whether or not to disable the tqdm progress bars and table of metrics produced by [~notebook.NotebookTrainingTracker] in Jupyter Notebooks. Will default to True if the logging level is set to warn or lower (default), False otherwise.

  • remove_unused_columns (bool, optional, defaults to True) – Whether or not to automatically remove the columns unused by the model forward method.

  • label_names (List[str], optional) –

    The list of keys in your dictionary of inputs that correspond to the labels.

    Will eventually default to the list of argument names accepted by the model that contain the word “label”, except if the model used is one of the XxxForQuestionAnswering in which case it will also include the [“start_positions”, “end_positions”] keys.

  • load_best_model_at_end (bool, optional, defaults to False) –

    Whether or not to load the best model found during training at the end of training. When this option is enabled, the best checkpoint will always be saved. See [save_total_limit](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments.save_total_limit) for more.

    <Tip>

    When set to True, the parameters save_strategy needs to be the same as evaluation_strategy, and in the case it is “steps”, save_steps must be a round multiple of eval_steps.

    </Tip>

  • metric_for_best_model (str, optional) –

    Use in conjunction with load_best_model_at_end to specify the metric to use to compare two different models. Must be the name of a metric returned by the evaluation with or without the prefix “eval_”. Will default to “loss” if unspecified and load_best_model_at_end=True (to use the evaluation loss).

    If you set this value, greater_is_better will default to True. Don’t forget to set it to False if your metric is better when lower.

  • greater_is_better (bool, optional) –

    Use in conjunction with load_best_model_at_end and metric_for_best_model to specify if better models should have a greater metric or not. Will default to:

    • True if metric_for_best_model is set to a value that isn’t “loss” or “eval_loss”.

    • False if metric_for_best_model is not set, or set to “loss” or “eval_loss”.

  • ignore_data_skip (bool, optional, defaults to False) – When resuming training, whether or not to skip the epochs and batches to get the data loading at the same stage as in the previous training. If set to True, the training will begin faster (as that skipping step can take a long time) but will not yield the same results as the interrupted training would have.

  • fsdp (bool, str or list of [~trainer_utils.FSDPOption], optional, defaults to ‘’) –

    Use PyTorch Distributed Parallel Training (in distributed training only).

    A list of options along the following:

    • ”full_shard”: Shard parameters, gradients and optimizer states.

    • ”shard_grad_op”: Shard optimizer states and gradients.

    • ”hybrid_shard”: Apply FULL_SHARD within a node, and replicate parameters across nodes.

    • ”hybrid_shard_zero2”: Apply SHARD_GRAD_OP within a node, and replicate parameters across nodes.

    • ”offload”: Offload parameters and gradients to CPUs (only compatible with “full_shard” and “shard_grad_op”).

    • ”auto_wrap”: Automatically recursively wrap layers with FSDP using default_auto_wrap_policy.

  • fsdp_config (str or dict, optional) –

    Config to be used with fsdp (Pytorch Distributed Parallel Training). The value is either a location of fsdp json config file (e.g., fsdp_config.json) or an already loaded json file as dict.

    A List of config and its options:
    • min_num_params (int, optional, defaults to 0):

      FSDP’s minimum number of parameters for Default Auto Wrapping. (useful only when fsdp field is passed).

    • transformer_layer_cls_to_wrap (List[str], optional):

      List of transformer layer class names (case-sensitive) to wrap, e.g, BertLayer, GPTJBlock, T5Block …. (useful only when fsdp flag is passed).

    • backward_prefetch (str, optional)

      FSDP’s backward prefetch mode. Controls when to prefetch next set of parameters (useful only when fsdp field is passed).

      A list of options along the following:

      • ”backward_pre” : Prefetches the next set of parameters before the current set of parameter’s gradient

        computation.

      • ”backward_post” : This prefetches the next set of parameters after the current set of parameter’s

        gradient computation.

    • forward_prefetch (bool, optional, defaults to False)
      FSDP’s forward prefetch mode (useful only when fsdp field is passed).

      If “True”, then FSDP explicitly prefetches the next upcoming all-gather while executing in the forward pass.

    • limit_all_gathers (bool, optional, defaults to False)
      FSDP’s limit_all_gathers (useful only when fsdp field is passed).

      If “True”, FSDP explicitly synchronizes the CPU thread to prevent too many in-flight all-gathers.

    • use_orig_params (bool, optional, defaults to True)

      If “True”, allows non-uniform requires_grad during init, which means support for interspersed frozen and trainable paramteres. Useful in cases such as parameter-efficient fine-tuning. Please refer this [blog](https://dev-discuss.pytorch.org/t/rethinking-pytorch-fully-sharded-data-parallel-fsdp-from-first-principles/1019

    • sync_module_states (bool, optional, defaults to True)

      If “True”, each individually wrapped FSDP unit will broadcast module parameters from rank 0 to ensure they are the same across all ranks after initialization

    • activation_checkpointing (bool, optional, defaults to False):

      If “True”, activation checkpointing is a technique to reduce memory usage by clearing activations of certain layers and recomputing them during a backward pass. Effectively, this trades extra computation time for reduced memory usage.

    • xla (bool, optional, defaults to False):

      Whether to use PyTorch/XLA Fully Sharded Data Parallel Training. This is an experimental feature and its API may evolve in the future.

    • xla_fsdp_settings (dict, optional)

      The value is a dictionary which stores the XLA FSDP wrapping parameters.

      For a complete list of options, please see [here]( https://github.com/pytorch/xla/blob/master/torch_xla/distributed/fsdp/xla_fully_sharded_data_parallel.py).

    • xla_fsdp_grad_ckpt (bool, optional, defaults to False):

      Will use gradient checkpointing over each nested XLA FSDP wrapped layer. This setting can only be used when the xla flag is set to true, and an auto wrapping policy is specified through fsdp_min_num_params or fsdp_transformer_layer_cls_to_wrap.

  • deepspeed (str or dict, optional) – Use [Deepspeed](https://github.com/microsoft/deepspeed). This is an experimental feature and its API may evolve in the future. The value is either the location of DeepSpeed json config file (e.g., ds_config.json) or an already loaded json file as a dict

  • label_smoothing_factor (float, optional, defaults to 0.0) – The label smoothing factor to use. Zero means no label smoothing, otherwise the underlying onehot-encoded labels are changed from 0s and 1s to label_smoothing_factor/num_labels and 1 - label_smoothing_factor + label_smoothing_factor/num_labels respectively.

  • debug (str or list of [~debug_utils.DebugOption], optional, defaults to “”) –

    Enable one or more debug features. This is an experimental feature.

    Possible options are:

    • ”underflow_overflow”: detects overflow in model’s input/outputs and reports the last frames that led to the event

    • ”tpu_metrics_debug”: print debug metrics on TPU

    The options should be separated by whitespaces.

  • optim (str or [training_args.OptimizerNames], optional, defaults to “adamw_torch”) – The optimizer to use: adamw_hf, adamw_torch, adamw_torch_fused, adamw_apex_fused, adamw_anyprecision or adafactor.

  • optim_args (str, optional) – Optional arguments that are supplied to AnyPrecisionAdamW.

  • group_by_length (bool, optional, defaults to False) – Whether or not to group together samples of roughly the same length in the training dataset (to minimize padding applied and be more efficient). Only useful if applying dynamic padding.

  • length_column_name (str, optional, defaults to “length”) – Column name for precomputed lengths. If the column exists, grouping by length will use these values rather than computing them on train startup. Ignored unless group_by_length is True and the dataset is an instance of Dataset.

  • report_to (str or List[str], optional, defaults to “all”) – The list of integrations to report the results and logs to. Supported platforms are “azure_ml”, “clearml”, “codecarbon”, “comet_ml”, “dagshub”, “dvclive”, “flyte”, “mlflow”, “neptune”, “tensorboard”, and “wandb”. Use “all” to report to all integrations installed, “none” for no integrations.

  • ddp_find_unused_parameters (bool, optional) – When using distributed training, the value of the flag find_unused_parameters passed to DistributedDataParallel. Will default to False if gradient checkpointing is used, True otherwise.

  • ddp_bucket_cap_mb (int, optional) – When using distributed training, the value of the flag bucket_cap_mb passed to DistributedDataParallel.

  • ddp_broadcast_buffers (bool, optional) – When using distributed training, the value of the flag broadcast_buffers passed to DistributedDataParallel. Will default to False if gradient checkpointing is used, True otherwise.

  • dataloader_pin_memory (bool, optional, defaults to True) – Whether you want to pin memory in data loaders or not. Will default to True.

  • dataloader_persistent_workers (bool, optional, defaults to False) – If True, the data loader will not shut down the worker processes after a dataset has been consumed once. This allows to maintain the workers Dataset instances alive. Can potentially speed up training, but will increase RAM usage. Will default to False.

  • skip_memory_metrics (bool, optional, defaults to True) – Whether to skip adding of memory profiler reports to metrics. This is skipped by default because it slows down the training and evaluation speed.

  • push_to_hub (bool, optional, defaults to False) –

    Whether or not to push the model to the Hub every time the model is saved. If this is activated, output_dir will begin a git directory synced with the repo (determined by hub_model_id) and the content will be pushed each time a save is triggered (depending on your save_strategy). Calling [~Trainer.save_model] will also trigger a push.

    <Tip warning={true}>

    If output_dir exists, it needs to be a local clone of the repository to which the [Trainer] will be pushed.

    </Tip>

  • resume_from_checkpoint (str, optional) – The path to a folder with a valid checkpoint for your model. This argument is not directly used by [Trainer], it’s intended to be used by your training/evaluation scripts instead. See the [example scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details.

  • hub_model_id (str, optional) –

    The name of the repository to keep in sync with the local output_dir. It can be a simple model ID in which case the model will be pushed in your namespace. Otherwise it should be the whole repository name, for instance “user_name/model”, which allows you to push to an organization you are a member of with “organization_name/model”. Will default to user_name/output_dir_name with output_dir_name being the name of output_dir.

    Will default to the name of output_dir.

  • hub_strategy (str or [~trainer_utils.HubStrategy], optional, defaults to “every_save”) –

    Defines the scope of what is pushed to the Hub and when. Possible values are:

    • ”end”: push the model, its configuration, the tokenizer (if passed along to the [Trainer]) and a draft of a model card when the [~Trainer.save_model] method is called.

    • ”every_save”: push the model, its configuration, the tokenizer (if passed along to the [Trainer]) and a draft of a model card each time there is a model save. The pushes are asynchronous to not block training, and in case the save are very frequent, a new push is only attempted if the previous one is finished. A last push is made with the final model at the end of training.

    • ”checkpoint”: like “every_save” but the latest checkpoint is also pushed in a subfolder named last-checkpoint, allowing you to resume training easily with trainer.train(resume_from_checkpoint=”last-checkpoint”).

    • ”all_checkpoints”: like “checkpoint” but all checkpoints are pushed like they appear in the output folder (so you will get one checkpoint folder per folder in your final repository)

  • hub_token (str, optional) – The token to use to push the model to the Hub. Will default to the token in the cache folder obtained with huggingface-cli login.

  • hub_private_repo (bool, optional, defaults to False) – If True, the Hub repo will be set to private.

  • hub_always_push (bool, optional, defaults to False) – Unless this is True, the Trainer will skip pushing a checkpoint when the previous push is not finished.

  • gradient_checkpointing (bool, optional, defaults to False) – If True, use gradient checkpointing to save memory at the expense of slower backward pass.

  • gradient_checkpointing_kwargs (dict, optional, defaults to None) – Key word arguments to be passed to the gradient_checkpointing_enable method.

  • include_inputs_for_metrics (bool, optional, defaults to False) – Whether or not the inputs will be passed to the compute_metrics function. This is intended for metrics that need inputs, predictions and references for scoring calculation in Metric class.

  • auto_find_batch_size (bool, optional, defaults to False) – Whether to find a batch size that will fit into memory automatically through exponential decay, avoiding CUDA Out-of-Memory errors. Requires accelerate to be installed (pip install accelerate)

  • full_determinism (bool, optional, defaults to False) – If True, [enable_full_determinism] is called instead of [set_seed] to ensure reproducible results in distributed training. Important: this will negatively impact the performance, so only use it for debugging.

  • torchdynamo (str, optional) – If set, the backend compiler for TorchDynamo. Possible choices are “eager”, “aot_eager”, “inductor”, “nvfuser”, “aot_nvfuser”, “aot_cudagraphs”, “ofi”, “fx2trt”, “onnxrt” and “ipex”.

  • ray_scope (str, optional, defaults to “last”) – The scope to use when doing hyperparameter search with Ray. By default, “last” will be used. Ray will then use the last checkpoint of all trials, compare those, and select the best one. However, other options are also available. See the [Ray documentation]( https://docs.ray.io/en/latest/tune/api_docs/analysis.html#ray.tune.ExperimentAnalysis.get_best_trial) for more options.

  • ddp_timeout (int, optional, defaults to 1800) – The timeout for torch.distributed.init_process_group calls, used to avoid GPU socket timeouts when performing slow operations in distributed runnings. Please refer the [PyTorch documentation] (https://pytorch.org/docs/stable/distributed.html#torch.distributed.init_process_group) for more information.

  • use_mps_device (bool, optional, defaults to False) – This argument is deprecated.`mps` device will be used if it is available similar to cuda device.

  • torch_compile (bool, optional, defaults to False) –

    Whether or not to compile the model using PyTorch 2.0 [torch.compile](https://pytorch.org/get-started/pytorch-2.0/).

    This will use the best defaults for the [torch.compile API](https://pytorch.org/docs/stable/generated/torch.compile.html?highlight=torch+compile#torch.compile). You can customize the defaults with the argument torch_compile_backend and torch_compile_mode but we don’t guarantee any of them will work as the support is progressively rolled in in PyTorch.

    This flag and the whole compile API is experimental and subject to change in future releases.

  • torch_compile_backend (str, optional) –

    The backend to use in torch.compile. If set to any value, torch_compile will be set to True.

    Refer to the PyTorch doc for possible values and note that they may change across PyTorch versions.

    This flag is experimental and subject to change in future releases.

  • torch_compile_mode (str, optional) –

    The mode to use in torch.compile. If set to any value, torch_compile will be set to True.

    Refer to the PyTorch doc for possible values and note that they may change across PyTorch versions.

    This flag is experimental and subject to change in future releases.

  • split_batches (bool, optional) –

    Whether or not the accelerator should split the batches yielded by the dataloaders across the devices during distributed training. If

    set to True, the actual batch size used will be the same on any kind of distributed processes, but it must be a

    round multiple of the number of processes you are using (such as GPUs).

  • include_tokens_per_second (bool, optional) –

    Whether or not to compute the number of tokens per second per device for training speed metrics.

    This will iterate over the entire training dataloader once beforehand,

    and will slow down the entire process.

  • include_num_input_tokens_seen (bool, optional) –

    Whether or not to track the number of input tokens seen throughout training.

    May be slower in distributed training as gather operations must be called.

  • neftune_noise_alpha (Optional[float]) – If not None, this will activate NEFTune noise embeddings. This can drastically improve model performance for instruction fine-tuning. Check out the [original paper](https://arxiv.org/abs/2310.05914) and the [original code](https://github.com/neelsjain/NEFTune). Support transformers PreTrainedModel and also PeftModel from peft.

  • use_lora (bool, optional, defaults to True) – Whether to use LoRA training.

  • lora_r (int, optional, defaults to 8) – Lora R dimension.

  • lora_alpha (int, optional, defaults to 16) – Lora alpha.

  • lora_dropout (float, optional, defaults to 0.05) – Lora dropout.

  • lora_target_modules (List[str], optional, defaults to None) – Lora target modules. If None, will be automatically inferred.

  • lora_bias (str, optional, defaults to “none”) – Lora bias.

  • max_length (int, optional, defaults to 512) – Maximum source sequence length during training.

  • log_to_db (bool, optional, defaults to True) –

    Log training to db. If True, will log checkpoint to superduperdb,

    but need ray cluster can access to db.

    If can’t access to db, please set it to False.

class superduperdb.ext.llm.OpenAI(identifier: str = '', artifacts: dc.InitVar[t.Optional[t.Dict]] = None, prompt_template: str = '{input}', prompt_func: ~typing.Callable | None = None, max_batch_size: int | None = 4, inference_kwargs: dict = <factory>, api_url: str = '', openai_api_base: str = 'https://api.openai.com/v1', openai_api_key: str | None = None, model_name: str = 'gpt-3.5-turbo', chat: bool = True, system_prompt: str | None = None, user_role: str = 'user', system_role: str = 'system', *, datatype: EncoderArg = None, output_schema: t.Optional[Schema] = None, flatten: bool = False, preprocess: t.Optional[t.Callable] = None, postprocess: t.Optional[t.Callable] = None, collate_fn: t.Optional[t.Callable] = None, batch_predict: bool = False, takes_context: bool = False, metrics: t.Sequence[t.Union[str, Metric, None]] = (), model_update_kwargs: t.Dict = <factory>, validation_sets: t.Optional[t.Sequence[t.Union[str, Dataset]]] = None, predict_X: t.Optional[str] = None, predict_select: t.Optional[CompoundSelect] = None, predict_max_chunk_size: t.Optional[int] = None, predict_kwargs: t.Optional[t.Dict] = None)[source]#

Bases: BaseOpenAI

OpenAI chat completion predictor.

Parameters:
  • openai_api_base – The base URL for the OpenAI API.

  • openai_api_key – The API key to use for the OpenAI API.

  • model_name – The name of the model to use.

  • chat – Whether to use the chat API or the completion API. Defaults to False.

  • system_prompt – The prompt to use for the system.

  • user_role – The role to use for the user.

  • system_role – The role to use for the system.

  • prompt_template – The template to use for the prompt.

  • prompt_func – The function to use for the prompt.

  • max_batch_size – The maximum batch size to use for batch generation.

  • inference_kwargs – Parameters used during inference.

__post_init__(artifacts)[source]#

Set model name.

class superduperdb.ext.llm.VllmAPI(identifier: str, artifacts: dc.InitVar[t.Optional[t.Dict]] = None, prompt_template: str = '{input}', prompt_func: ~typing.Callable | None = None, max_batch_size: int | None = 4, inference_kwargs: dict = <factory>, api_url: str = '', *, datatype: EncoderArg = None, output_schema: t.Optional[Schema] = None, flatten: bool = False, preprocess: t.Optional[t.Callable] = None, postprocess: t.Optional[t.Callable] = None, collate_fn: t.Optional[t.Callable] = None, batch_predict: bool = False, takes_context: bool = False, metrics: t.Sequence[t.Union[str, Metric, None]] = (), model_update_kwargs: t.Dict = <factory>, validation_sets: t.Optional[t.Sequence[t.Union[str, Dataset]]] = None, predict_X: t.Optional[str] = None, predict_select: t.Optional[CompoundSelect] = None, predict_max_chunk_size: t.Optional[int] = None, predict_kwargs: t.Optional[t.Dict] = None)[source]#

Bases: BaseLLMAPI

Wrapper for requesting the vLLM API service (API Server format, started by vllm.entrypoints.api_server)

Parameters:
  • api_url – The URL for the API.

  • prompt_template – The template to use for the prompt.

  • prompt_func – The function to use for the prompt.

  • max_batch_size – The maximum batch size to use for batch generation.

  • inference_kwargs – Parameters used during inference.

public_api(beta): This API is in beta and may change before becoming stable.

_generate(prompt: str, **kwargs) str[source]#

Batch generate text from a prompt.

build_post_data(prompt: str, **kwargs: dict[str, Any]) dict[str, Any][source]#
class superduperdb.ext.llm.VllmModel(identifier: str = '', artifacts: dc.InitVar[t.Optional[t.Dict]] = None, prompt_template: str = '{input}', prompt_func: ~typing.Callable | None = None, max_batch_size: int | None = 4, inference_kwargs: dict = <factory>, model_name: str = '', on_ray: bool = False, ray_address: str | None = None, ray_config: dict = <factory>, tensor_parallel_size: int = 1, trust_remote_code: bool = True, vllm_kwargs: dict = <factory>, *, datatype: EncoderArg = None, output_schema: t.Optional[Schema] = None, flatten: bool = False, preprocess: t.Optional[t.Callable] = None, postprocess: t.Optional[t.Callable] = None, collate_fn: t.Optional[t.Callable] = None, batch_predict: bool = False, takes_context: bool = False, metrics: t.Sequence[t.Union[str, Metric, None]] = (), model_update_kwargs: t.Dict = <factory>, validation_sets: t.Optional[t.Sequence[t.Union[str, Dataset]]] = None, predict_X: t.Optional[str] = None, predict_select: t.Optional[CompoundSelect] = None, predict_max_chunk_size: t.Optional[int] = None, predict_kwargs: t.Optional[t.Dict] = None)[source]#

Bases: BaseLLMModel

Load a large language model from VLLM.

Parameters:
  • model_name – The name of the model to use.

  • trust_remote_code – Whether to trust remote code.

  • dtype – The data type to use.

  • model_name – The name of the model to use.

  • on_ray – Whether to run the model on Ray.

  • ray_config – The Ray config to use.

  • ray_addredd – The address of the ray cluster.

  • prompt_template – The template to use for the prompt.

  • prompt_func – The function to use for the prompt.

  • max_batch_size – The maximum batch size to use for batch generation.

  • inference_kwargs – Parameters used during inference.

public_api(beta): This API is in beta and may change before becoming stable.

inference_kwargs: dict#
init()[source]#
model_update_kwargs: t.Dict#
ray_config: dict#
tensor_parallel_size: int = 1#
trust_remote_code: bool = True#
vllm_kwargs: dict#