命令行界面
命令¶
Ludwig 通过其命令行界面提供了多种功能。
模式 | 描述 |
---|---|
train |
训练模型 |
predict |
使用预训练模型进行预测 |
evaluate |
评估预训练模型的性能 |
experiment |
运行完整的实验,包括训练模型和评估模型 |
hyperopt |
执行超参数优化 |
serve |
部署预训练模型提供服务 |
visualize |
可视化实验结果 |
init_config |
从数据集和目标初始化用户配置 |
render_config |
渲染填充了所有默认值的完整配置 |
collect_summary |
打印权重和层激活的名称,以便与其他收集命令一起使用 |
collect_weights |
收集包含预训练模型权重的张量 |
collect_activations |
使用预训练模型收集每个数据点的张量 |
export_torchscript |
将 Ludwig 模型导出为 Torchscript |
export_carton |
将 Ludwig 模型导出为 Carton |
export_neuropod |
将 Ludwig 模型导出为 Neuropod |
export_mlflow |
将 Ludwig 模型导出为 MLflow |
preprocess |
预处理数据并将其保存为 HDF5 和 JSON 格式 |
synthesize_dataset |
创建用于测试目的的合成数据 |
upload_to_hf_hub |
将训练好的模型文件推送到 HuggingFace Hub |
这些命令的详细描述如下。
train¶
使用您的数据训练模型。
ludwig train [options]
或使用
python -m ludwig.train [options]
在 Ludwig 的主目录中。
以下是可用的参数
usage: ludwig train [options]
This script trains a model
optional arguments:
-h, --help show this help message and exit
--output_directory OUTPUT_DIRECTORY
directory that contains the results
--experiment_name EXPERIMENT_NAME
experiment name
--model_name MODEL_NAME
name for the model
--dataset DATASET input data file path. If it has a split column, it
will be used for splitting (0: train, 1: validation,
2: test), otherwise the dataset will be randomly split
--training_set TRAINING_SET
input train data file path
--validation_set VALIDATION_SET
input validation data file path
--test_set TEST_SET input test data file path
--training_set_metadata TRAINING_SET_METADATA
input metadata JSON file path. An intermediate
preprocessed containing the mappings of the input
file created the first time a file is used, in the
same directory with the same name and a .json
extension
--data_format {auto,csv,excel,feather,fwf,hdf5,htmltables,json,jsonl,parquet,pickle,sas,spss,stata,tsv}
format of the input data
-sspi, --skip_save_processed_input
skips saving intermediate HDF5 and JSON files
-c CONFIG, --config CONFIG
Path to the YAML file containing the model configuration
-cs CONFIG_STR, --config_str CONFIG_STRING
JSON or YAML serialized string of the model configuration. Ignores --config
-mlp MODEL_LOAD_PATH, --model_load_path MODEL_LOAD_PATH
path of a pretrained model to load as initialization
-mrp MODEL_RESUME_PATH, --model_resume_path MODEL_RESUME_PATH
path of the model directory to resume training of
-sstd, --skip_save_training_description
disables saving the description JSON file
-ssts, --skip_save_training_statistics
disables saving training statistics JSON file
-ssm, --skip_save_model
disables saving weights each time the model improves.
By default Ludwig saves weights after each epoch the
validation metric improves, but if the model is really
big that can be time consuming. If you do not want to
keep the weights and just find out what performance
can a model get with a set of hyperparameters, use
this parameter to skip it
-ssp, --skip_save_progress
disables saving weights after each epoch. By default
ludwig saves weights after each epoch for enabling
resuming of training, but if the model is really big
that can be time consuming and will save twice as much
space, use this parameter to skip it
-ssl, --skip_save_log
disables saving TensorBoard logs. By default Ludwig
saves logs for the TensorBoard, but if it is not
needed turning it off can slightly increase the
overall speed
-rs RANDOM_SEED, --random_seed RANDOM_SEED
a random seed that is going to be used anywhere there
is a call to a random number generator: data
splitting, parameter initialization and training set
shuffling
-g GPUS [GPUS ...], --gpus GPUS [GPUS ...]
list of gpus to use
-gml GPU_MEMORY_LIMIT, --gpu_memory_limit GPU_MEMORY_LIMIT
maximum memory in MB to allocate per GPU device
-dpt, --disable_parallel_threads
disable Torch from using multithreading for
reproducibility
-b BACKEND, --backend BACKEND
specifies backend to use for parallel / distributed execution,
defaults to local execution or Horovod if called using horovodrun
当 Ludwig 训练模型时,它会创建两个中间文件:一个 HDF5 文件和一个 JSON 文件。HDF5 文件包含映射到 numpy ndarray 的数据,而 JSON 文件包含张量中的值到其原始标签的映射。
例如,对于具有 3 个可能值的类别特征,HDF5 文件将包含从 0 到 3 的整数(0 是 `
保留这些中间文件有两个原因:一方面,如果您打算再次训练模型,Ludwig 将尝试加载它们而不是重新计算所有张量,这节省了大量时间;另一方面,当您想使用模型进行预测时,数据必须以与训练期间完全相同的方式映射到张量,因此在 `predict` 命令中需要加载 JSON 元数据文件。
第一次提供 UTF-8 编码数据集 (`--dataset`) 时,会创建 HDF5 和 JSON 文件;从第二次开始,即使您指定了数据集,Ludwig 也会加载这些文件而不是数据集(它会在同一目录中查找同名但扩展名不同的文件);最后,您可以直接指定 HDF5 和 JSON 文件。
由于原始数据到张量的映射取决于您在配置中指定的特征类型,因此如果更改类型(例如从 `sequence` 到 `text`),则还必须重新进行预处理,这可以通过删除 HDF5 和 JSON 文件来实现。或者,您可以通过指定 `--skip_save_processed_input` 来跳过保存 HDF5 和 JSON 文件。
训练集、验证集和测试集的分裂可以通过几种方式完成。这允许多种可能的输入数据场景
- 提供一个单独的 UTF-8 编码数据集文件 (`-dataset`)。在这种情况下,如果数据集包含一个 `split` 列,其值为 `0` 表示训练集,`1` 表示验证集,`2` 表示测试集,则将使用此分裂。如果您想忽略 `split` 列并执行随机分裂,请在配置中使用 `force_split` 参数。如果没有 `split` 列,则将执行随机的 `70-20-10` 分裂。您可以在配置的预处理部分设置百分比并指定是否要进行分层抽样。
- 您可以提供单独的 UTF-8 编码训练集、验证集和测试集(`--training_set`、`--validation_set`、`--test_set`)。
- 在单个数据集文件情况下指定的 HDF5 和 JSON 文件指示也适用于多个文件情况,唯一的区别是您只需指定一个 JSON 文件(`--train_set_metadata_json`)。
验证集是可选的,但如果缺失,训练将继续直到训练 epoch 结束;而当存在验证集时,默认行为是在验证指标在一定数量的 epoch 后没有改进时执行早停。测试集也是可选的。
其他可选参数包括 `--output_directory`、`--experiment_name` 和 `--model name`。默认情况下,输出目录为 `./results`。如果指定了模型名称和实验名称,该目录将包含一个名为 `[experiment_name]_[model_name]_0` 的目录。如果再次使用相同的实验名称和模型名称组合,名称末尾的整数将递增。如果两者都没有指定,目录将命名为 `run_0`。该目录将包含
- `description.json` - 一个文件,包含训练过程的描述以及重现它所需的所有信息。
- `training_statistics.json` - 一个文件,包含每个 epoch 的所有度量和损失记录。
- `model` - 一个目录,包含模型超参数、权重、检查点和日志(用于 TensorBoard)。
配置可以作为字符串 (`--config_str`) 或 YAML 文件 (`--config`) 提供。
有关如何编写配置的详细信息,请参阅配置部分。
在训练期间,Ludwig 为模型保存两组权重:一组是在验证指标达到最佳性能的 epoch 结束时的权重,另一组是在最新 epoch 结束时的权重。保留第二组的原因是为了能够在训练过程因某种原因中断时恢复训练。
要使用最新权重和迄今为止的完整进度历史记录来恢复训练,您必须指定 `--model_resume_path` 参数。您可以通过使用 `--skip_save_progress` 参数来避免保存最新权重和迄今为止的总体进度,但之后将无法恢复训练。
另一个可用选项是加载先前训练好的模型作为新训练过程的初始化。在这种情况下,Ludwig 将启动一个新的训练过程,而不知道先前模型的任何进度、训练统计信息,也不知道模型迄今为止训练了多少个 epoch。
这并非恢复训练,只是使用先前训练好的模型以相同配置初始化训练,这是通过 `--model_load_path` 参数实现的。
您可以使用 `--random_seed` 参数指定 Python 环境、Python random 包、numpy 和 Torch 使用的随机种子。这有助于重现性。
请注意,由于 Torch 在 GPU 执行中的异步性,在 GPU 上训练时结果可能无法重现。
您可以使用 `--gpus` 参数管理您的机器上使用的 GPU,该参数接受一个字符串,其格式与 `CUDA_VISIBLE_DEVICES` 环境变量相同,即由逗号分隔的整数列表。您还可以使用 `--gpu_memory_limit` 指定每个设备将分配的最大 GPU 内存量。默认情况下分配所有内存。如果分配的内存少于全部内存,Torch 需要更多 GPU 内存时会尝试增加此量。
如果设置了参数 `--backend`,将使用给定的后端进行分布式处理(Horovod 或 Ray)。
最后,`--logging_level` 参数允许您设置训练期间希望看到的日志级别。
示例
ludwig train --dataset reuters-allcats.csv --config_str "{input_features: [{name: text, type: text, encoder: {type: parallel_cnn}}], output_features: [{name: class, type: category}]}"
predict¶
此命令允许您使用先前训练好的模型在新数据上进行预测。您可以使用以下方式调用它
ludwig predict [options]
或使用
python -m ludwig.predict [options]
在 Ludwig 的主目录中。
以下是可用的参数
usage: ludwig predict [options]
This script loads a pretrained model and uses it to predict
optional arguments:
-h, --help show this help message and exit
--dataset DATASET input data file path
--data_format {auto,csv,excel,feather,fwf,hdf5,htmltables,json,jsonl,parquet,pickle,sas,spss,stata,tsv}
format of the input data
-s {training,validation,test,full}, --split {training,validation,test,full}
the split to test the model on
-m MODEL_PATH, --model_path MODEL_PATH
model to load
-od OUTPUT_DIRECTORY, --output_directory OUTPUT_DIRECTORY
directory that contains the results
-ssuo, --skip_save_unprocessed_output
skips saving intermediate NPY output files
-sstp, --skip_save_predictions
skips saving predictions CSV files
-bs BATCH_SIZE, --batch_size BATCH_SIZE
size of batches
-g GPUS, --gpus GPUS list of gpu to use
-gml GPU_MEMORY_LIMIT, --gpu_memory_limit GPU_MEMORY_LIMIT
maximum memory in MB to allocate per GPU device
-dpt, --disable_parallel_threads
disable Torch from using multithreading for
reproducibility
-b BACKEND, --backend BACKEND
specifies backend to use for parallel / distributed execution,
defaults to local execution or Horovod if called using horovodrun
-dbg, --debug enables debugging mode
-l {critical,error,warning,info,debug,notset}, --logging_level {critical,error,warning,info,debug,notset}
the level of logging to use
此处也适用train部分中解释的 UTF-8 编码数据集文件与 HDF5 / JSON 文件之间的相同区别。在任何一种情况下,都需要训练期间获得的 JSON 元数据文件,以便将新数据映射到张量。如果新数据包含 `split` 列,您可以使用 `--split` 参数指定用于计算预测的分裂。默认值为 `full`,这意味着将使用所有分裂。
需要加载一个模型,您可以使用 `--model_path` 参数指定其路径。如果您之前训练了一个模型,并将结果保存在例如 `./results/experiment_run_0` 中,则必须指定 `./results/experiment_run_0/model` 来使用它进行预测。
您可以使用参数 `--output-directory` 指定输出目录,默认情况下为 `./result_0`,如果存在同名目录,则数字将递增。
该目录将包含每个输出特征的预测 CSV 文件和概率 CSV 文件,以及包含原始张量的原始 NPY 文件。您可以使用参数 `skip_save_unprocessed_output` 指定不保存原始 NPY 输出文件。
可以使用参数 `--batch_size` 指定特定的批量大小以加快预测速度。
最后,`--logging_level`、`--debug`、`--gpus`、`--gpu_memory_limit` 和 `--disable_parallel_threads` 相关参数的行为与 train 命令部分所述完全相同。
示例
ludwig predict --dataset reuters-allcats.csv --model_path results/experiment_run_0/model/
evaluate¶
此命令允许您使用先前训练好的模型在新数据上进行预测,并评估预测相对于真实值的性能。您可以使用以下方式调用它
ludwig evaluate [options]
或使用
python -m ludwig.evaluate [options]
在 Ludwig 的主目录中。
以下是可用的参数
usage: ludwig evaluate [options]
This script loads a pretrained model and evaluates its performance by
comparing its predictions with ground truth.
optional arguments:
-h, --help show this help message and exit
--dataset DATASET input data file path
--data_format {auto,csv,excel,feather,fwf,hdf5,htmltables,json,jsonl,parquet,pickle,sas,spss,stata,tsv}
format of the input data
-s {training,validation,test,full}, --split {training,validation,test,full}
the split to test the model on
-m MODEL_PATH, --model_path MODEL_PATH
model to load
-od OUTPUT_DIRECTORY, --output_directory OUTPUT_DIRECTORY
directory that contains the results
-ssuo, --skip_save_unprocessed_output
skips saving intermediate NPY output files
-sses, --skip_save_eval_stats
skips saving intermediate JSON eval statistics
-scp, --skip_collect_predictions
skips collecting predictions
-scos, --skip_collect_overall_stats
skips collecting overall stats
-bs BATCH_SIZE, --batch_size BATCH_SIZE
size of batches
-g GPUS, --gpus GPUS list of gpu to use
-gml GPU_MEMORY_LIMIT, --gpu_memory_limit GPU_MEMORY_LIMIT
maximum memory in MB to allocate per GPU device
-dpt, --disable_parallel_threads
disable Torch from using multithreading for
reproducibility
-b BACKEND, --backend BACKEND
specifies backend to use for parallel / distributed execution,
defaults to local execution or Horovod if called using horovodrun
-dbg, --debug enables debugging mode
-l {critical,error,warning,info,debug,notset}, --logging_level {critical,error,warning,info,debug,notset}
the level of logging to use
所有参数与 predict 相同,行为也相同。唯一的区别是 `evaluate` 要求数据集还包含与输出特征同名的列。这是必需的,因为 `evaluate` 会将模型生成的预测与真实值进行比较,并将所有这些统计信息保存在结果目录中的 `test_statistics.json` 文件中。
请注意,数据必须包含每个输出特征对应的列,其中包含真实值输出,以便计算性能统计信息。如果您收到关于数据中缺少输出特征列的错误,这意味着数据不包含用于作为真实值的每个输出特征的列。
示例
ludwig evaluate --dataset reuters-allcats.csv --model_path results/experiment_run_0/model/
experiment¶
此命令将训练和评估组合成一个方便的命令。您可以通过指定 `--k_fold` 参数请求 k 折交叉验证运行。
您可以使用以下方式调用它
ludwig experiment [options]
或使用
python -m ludwig.experiment [options]
在 Ludwig 的主目录中。
以下是可用的参数
usage: ludwig experiment [options]
This script trains and evaluates a model
optional arguments:
-h, --help show this help message and exit
--output_directory OUTPUT_DIRECTORY
directory that contains the results
--experiment_name EXPERIMENT_NAME
experiment name
--model_name MODEL_NAME
name for the model
--dataset DATASET input data file path. If it has a split column, it
will be used for splitting (0: train, 1: validation,
2: test), otherwise the dataset will be randomly split
--training_set TRAINING_SET
input train data file path
--validation_set VALIDATION_SET
input validation data file path
--test_set TEST_SET input test data file path
--training_set_metadata TRAINING_SET_METADATA
input metadata JSON file path. An intermediate
preprocessed containing the mappings of the input
file created the first time a file is used, in the
same directory with the same name and a .json
extension
--data_format {auto,csv,excel,feather,fwf,hdf5,htmltables,json,jsonl,parquet,pickle,sas,spss,stata,tsv}
format of the input data
-es {training,validation,test,full}, --eval_split {training,validation,test,full}
the split to evaluate the model on
-sspi, --skip_save_processed_input
skips saving intermediate HDF5 and JSON files
-ssuo, --skip_save_unprocessed_output
skips saving intermediate NPY output files
-kf K_FOLD, --k_fold K_FOLD
number of folds for a k-fold cross validation run
-skfsi, --skip_save_k_fold_split_indices
disables saving indices generated to split training
data set for the k-fold cross validation run, but if
it is not needed turning it off can slightly increase
the overall speed
-c CONFIG, --config CONFIG
Path to the YAML file containing the model configuration
-cs CONFIG_STR, --config_str CONFIG_STRING
JSON or YAML serialized string of the model configuration. Ignores --config
-mlp MODEL_LOAD_PATH, --model_load_path MODEL_LOAD_PATH
path of a pretrained model to load as initialization
-mrp MODEL_RESUME_PATH, --model_resume_path MODEL_RESUME_PATH
path of the model directory to resume training of
-sstd, --skip_save_training_description
disables saving the description JSON file
-ssts, --skip_save_training_statistics
disables saving training statistics JSON file
-sstp, --skip_save_predictions
skips saving test predictions CSV files
-sstes, --skip_save_eval_stats
skips saving eval statistics JSON file
-ssm, --skip_save_model
disables saving model weights and hyperparameters each
time the model improves. By default Ludwig saves model
weights after each epoch the validation metric
improves, but if the model is really big that can be
time consuming if you do not want to keep the weights
and just find out what performance a model can get
with a set of hyperparameters, use this parameter to
skip it,but the model will not be loadable later on
-ssp, --skip_save_progress
disables saving progress each epoch. By default Ludwig
saves weights and stats after each epoch for enabling
resuming of training, but if the model is really big
that can be time consuming and will uses twice as much
space, use this parameter to skip it, but training
cannot be resumed later on
-ssl, --skip_save_log
disables saving TensorBoard logs. By default Ludwig
saves logs for the TensorBoard, but if it is not
needed turning it off can slightly increase the
overall speed
-rs RANDOM_SEED, --random_seed RANDOM_SEED
a random seed that is going to be used anywhere there
is a call to a random number generator: data
splitting, parameter initialization and training set
shuffling
-g GPUS [GPUS ...], --gpus GPUS [GPUS ...]
list of GPUs to use
-gml GPU_MEMORY_LIMIT, --gpu_memory_limit GPU_MEMORY_LIMIT
maximum memory in MB to allocate per GPU device
-dpt, --disable_parallel_threads
disable Torch from using multithreading for
reproducibility
-b BACKEND, --backend BACKEND
specifies backend to use for parallel / distributed execution,
defaults to local execution or Horovod if called using horovodrun
-dbg, --debug enables debugging mode
-l {critical,error,warning,info,debug,notset}, --logging_level {critical,error,warning,info,debug,notset}
the level of logging to use
参数结合了来自 train 和 test 的参数,请参阅这些部分以获得深入解释。输出目录将包含这两个命令产生的输出。
示例
ludwig experiment --dataset reuters-allcats.csv --config_str "{input_features: [{name: text, type: text, encoder: {type: parallel_cnn}}], output_features: [{name: class, type: category}]}"
hyperopt¶
此命令允许您使用给定的采样器和参数执行超参数搜索。您可以使用以下方式调用它
ludwig hyperopt [options]
或使用
python -m ludwig.hyperopt [options]
在 Ludwig 的主目录中。
以下是可用的参数
usage: ludwig hyperopt [options]
This script searches for optimal Hyperparameters
optional arguments:
-h, --help show this help message and exit
-sshs, --skip_save_hyperopt_statistics
skips saving hyperopt statistics file
--output_directory OUTPUT_DIRECTORY
directory that contains the results
--experiment_name EXPERIMENT_NAME
experiment name
--model_name MODEL_NAME
name for the model
--dataset DATASET input data file path. If it has a split column, it
will be used for splitting (0: train, 1: validation,
2: test), otherwise the dataset will be randomly split
--training_set TRAINING_SET
input train data file path
--validation_set VALIDATION_SET
input validation data file path
--test_set TEST_SET input test data file path
--training_set_metadata TRAINING_SET_METADATA
input metadata JSON file path. An intermediate
preprocessed file containing the mappings of the input
file created the first time a file is used, in the
same directory with the same name and a .json
extension
--data_format {auto,csv,excel,feather,fwf,hdf5,htmltables,json,jsonl,parquet,pickle,sas,spss,stata,tsv}
format of the input data
-sspi, --skip_save_processed_input
skips saving intermediate HDF5 and JSON files
-c CONFIG, --config CONFIG
Path to the YAML file containing the model configuration
-cs CONFIG_STR, --config_str CONFIG_STRING
JSON or YAML serialized string of the model configuration. Ignores --config
-mlp MODEL_LOAD_PATH, --model_load_path MODEL_LOAD_PATH
path of a pretrained model to load as initialization
-mrp MODEL_RESUME_PATH, --model_resume_path MODEL_RESUME_PATH
path of the model directory to resume training of
-sstd, --skip_save_training_description
disables saving the description JSON file
-ssts, --skip_save_training_statistics
disables saving training statistics JSON file
-ssm, --skip_save_model
disables saving weights each time the model improves.
By default Ludwig saves weights after each epoch the
validation metric improves, but if the model is really
big that can be time consuming. If you do not want to
keep the weights and just find out what performance
can a model get with a set of hyperparameters, use
this parameter to skip it
-ssp, --skip_save_progress
disables saving weights after each epoch. By default
ludwig saves weights after each epoch for enabling
resuming of training, but if the model is really big
that can be time consuming and will save twice as much
space, use this parameter to skip it
-ssl, --skip_save_log
disables saving TensorBoard logs. By default Ludwig
saves logs for the TensorBoard, but if it is not
needed turning it off can slightly increase the
overall speed
-rs RANDOM_SEED, --random_seed RANDOM_SEED
a random seed that is going to be used anywhere there
is a call to a random number generator: data
splitting, parameter initialization and training set
shuffling
-g GPUS [GPUS ...], --gpus GPUS [GPUS ...]
list of gpus to use
-gml GPU_MEMORY_LIMIT, --gpu_memory_limit GPU_MEMORY_LIMIT
maximum memory in MB to allocate per GPU device
-b BACKEND, --backend BACKEND
specifies backend to use for parallel / distributed execution,
defaults to local execution or Horovod if called using horovodrun
-dbg, --debug enables debugging mode
-l {critical,error,warning,info,debug,notset}, --logging_level {critical,error,warning,info,debug,notset}
the level of logging to use
参数结合了 train 和 test 的参数,请参阅这些部分以获得深入解释。输出目录将包含一个 `hyperopt_statistics.json` 文件,其中总结了获得的结果。
为了执行超参数优化,需要在配置中提供 `hyperopt` 部分。在 `hyperopt` 部分中,您可以定义要优化的指标、参数、用于优化它们的采样器以及如何执行优化。有关 `hyperopt` 部分的详细信息,请参阅超参数优化部分的详细描述。
serve¶
此命令允许您加载预训练模型并在 http 服务器上提供服务。
您可以使用以下方式调用它
ludwig serve [options]
或使用
python -m ludwig.serve [options]
在 Ludwig 的主目录中。
以下是可用的参数
usage: ludwig serve [options]
This script serves a pretrained model
optional arguments:
-h, --help show this help message and exit
-m MODEL_PATH, --model_path MODEL_PATH
model to load
-l {critical,error,warning,info,debug,notset}, --logging_level {critical,error,warning,info,debug,notset}
the level of logging to use
-p PORT, --port PORT port for server (default: 8000)
-H HOST, --host HOST host for server (default: 0.0.0.0)
最重要的参数是 `--model_path`,您需要在其中指定要加载模型的路径。
运行后,您可以在 `/predict` 端点上发出 POST 请求,以对提交的表单数据运行推理。
注意
`ludwig serve` 将自动使用 GPU 进行模型服务,如果机器本地的 torch 环境可用。
curl 示例¶
文件
curl http://0.0.0.0:8000/predict -X POST -F 'image_path=@path_to_image/example.png'
文本
curl http://0.0.0.0:8000/predict -X POST -F 'english_text=words to be translated'
文本和文件
curl http://0.0.0.0:8000/predict -X POST -F 'text=mixed together with' -F 'image=@path_to_image/example.png'
批量预测
您还可以在 `/batch_predict` 端点上发出 POST 请求,以一次性对多个样本运行推理。
请求必须以表单数据形式提交,其中一个字段为 `dataset`:一个 JSON 编码的字符串,表示要预测的数据。
期望 `dataset` JSON 字符串采用 Pandas 的“split”格式,以减小负载大小。此格式将数据集分为三个部分
- columns: `List[str]`
- index (可选): `List[Union[str, int]]`
- data: `List[List[object]]`
可以使用额外的表单字段来提供文件中引用的文件资源,例如图像。
批量预测示例
curl http://0.0.0.0:8000/batch_predict -X POST -F 'dataset={"columns": ["a", "b"], "data": [[1, 2], [3, 4]]}'
visualize¶
此命令允许您可视化训练和预测统计信息,以及比较不同模型的性能和预测。您可以使用以下方式调用它
ludwig visualize [options]
或使用
python -m ludwig.visualize [options]
在 Ludwig 的主目录中。
以下是可用的参数
usage: ludwig visualize [options]
This script analyzes results and shows some nice plots.
optional arguments:
-h, --help show this help message and exit
-g GROUND_TRUTH, --ground_truth GROUND_TRUTH
ground truth file
-gm GROUND_TRUTH_METADATA, --ground_truth_metadata GROUND_TRUTH_METADATA
input metadata JSON file
-od OUTPUT_DIRECTORY, --output_directory OUTPUT_DIRECTORY
directory where to save plots.If not specified, plots
will be displayed in a window
-ff {pdf,png}, --file_format {pdf,png}
file format of output plots
-v {binary_threshold_vs_metric,calibration_1_vs_all,calibration_multiclass,compare_classifiers_multiclass_multimetric,compare_classifiers_performance_changing_k,compare_classifiers_performance_from_pred,compare_classifiers_performance_from_prob,compare_classifiers_performance_subset,compare_classifiers_predictions,compare_classifiers_predictions_distribution,compare_performance,confidence_thresholding,confidence_thresholding_2thresholds_2d,confidence_thresholding_2thresholds_3d,confidence_thresholding_data_vs_acc,confidence_thresholding_data_vs_acc_subset,confidence_thresholding_data_vs_acc_subset_per_class,confusion_matrix,frequency_vs_f1,hyperopt_hiplot,hyperopt_report,learning_curves,roc_curves,roc_curves_from_test_statistics}, --visualization {binary_threshold_vs_metric,calibration_1_vs_all,calibration_multiclass,compare_classifiers_multiclass_multimetric,compare_classifiers_performance_changing_k,compare_classifiers_performance_from_pred,compare_classifiers_performance_from_prob,compare_classifiers_performance_subset,compare_classifiers_predictions,compare_classifiers_predictions_distribution,compare_performance,confidence_thresholding,confidence_thresholding_2thresholds_2d,confidence_thresholding_2thresholds_3d,confidence_thresholding_data_vs_acc,confidence_thresholding_data_vs_acc_subset,confidence_thresholding_data_vs_acc_subset_per_class,confusion_matrix,frequency_vs_f1,hyperopt_hiplot,hyperopt_report,learning_curves,roc_curves,roc_curves_from_test_statistics}
type of visualization
-f OUTPUT_FEATURE_NAME, --output_feature_name OUTPUT_FEATURE_NAME
name of the output feature to visualize
-gts GROUND_TRUTH_SPLIT, --ground_truth_split GROUND_TRUTH_SPLIT
ground truth split - 0:train, 1:validation, 2:test
split
-tf THRESHOLD_OUTPUT_FEATURE_NAMES [THRESHOLD_OUTPUT_FEATURE_NAMES ...], --threshold_output_feature_names THRESHOLD_OUTPUT_FEATURE_NAMES [THRESHOLD_OUTPUT_FEATURE_NAMES ...]
names of output features for 2d threshold
-pred PREDICTIONS [PREDICTIONS ...], --predictions PREDICTIONS [PREDICTIONS ...]
predictions files
-prob PROBABILITIES [PROBABILITIES ...], --probabilities PROBABILITIES [PROBABILITIES ...]
probabilities files
-trs TRAINING_STATISTICS [TRAINING_STATISTICS ...], --training_statistics TRAINING_STATISTICS [TRAINING_STATISTICS ...]
training stats files
-tes TEST_STATISTICS [TEST_STATISTICS ...], --test_statistics TEST_STATISTICS [TEST_STATISTICS ...]
test stats files
-hs HYPEROPT_STATS_PATH, --hyperopt_stats_path HYPEROPT_STATS_PATH
hyperopt stats file
-mn MODEL_NAMES [MODEL_NAMES ...], --model_names MODEL_NAMES [MODEL_NAMES ...]
names of the models to use as labels
-tn TOP_N_CLASSES [TOP_N_CLASSES ...], --top_n_classes TOP_N_CLASSES [TOP_N_CLASSES ...]
number of classes to plot
-k TOP_K, --top_k TOP_K
number of elements in the ranklist to consider
-ll LABELS_LIMIT, --labels_limit LABELS_LIMIT
maximum numbers of labels. If labels in dataset are
higher than this number, "rare" label
-ss {ground_truth,predictions}, --subset {ground_truth,predictions}
type of subset filtering
-n, --normalize normalize rows in confusion matrix
-m METRICS [METRICS ...], --metrics METRICS [METRICS ...]
metrics to display in threshold_vs_metric
-pl POSITIVE_LABEL, --positive_label POSITIVE_LABEL
label of the positive class for the roc curve
-l {critical,error,warning,info,debug,notset}, --logging_level {critical,error,warning,info,debug,notset}
the level of logging to use
正如 `--visualization` 参数所示,有大量现成的可视化工具可用。它们每一个都需要此命令参数的不同子集,因此将在可视化部分逐一描述。
init_config¶
从数据集和目标初始化用户配置。
usage: ludwig init_config [options]
This script initializes a valid config from a dataset.
optional arguments:
-h, --help show this help message and exit
-d DATASET, --dataset DATASET
input data file path
-t TARGET, --target TARGET
target(s) to predict as output features of the model
--time_limit_s TIME_LIMIT_S
time limit to train the model in seconds when using hyperopt
--suggested SUGGESTED
use suggested config from automl, otherwise only use inferred types and return a minimal config
--hyperopt HYPEROPT include automl hyperopt config
--random_seed RANDOM_SEED
seed for random number generators used in hyperopt to improve repeatability
--use_reference_config USE_REFERENCE_CONFIG
refine hyperopt search space by setting first search point from stored reference model config
-o OUTPUT, --output OUTPUT
output initialized YAML config path
render_config¶
渲染填充了所有默认值的完整配置。
usage: ludwig render_config [options]
This script renders the full config from a user config.
optional arguments:
-h, --help show this help message and exit
-o OUTPUT, --output OUTPUT
output rendered YAML config path
collect_summary¶
此命令加载预训练模型并打印权重和层激活的名称,以便与 `collect_weights` 或 `collect_activations` 一起使用。
ludwig collect_summary [options]
或使用
python -m ludwig.collect names [options]
在 Ludwig 的主目录中。
以下是可用的参数
usage: ludwig collect_summary [options]
This script loads a pretrained model and print names of weights and layer activations.
optional arguments:
-h, --help show this help message and exit
-m MODEL_PATH, --model_path MODEL_PATH
model to load
-l {critical,error,warning,info,debug,notset}, --logging_level {critical,error,warning,info,debug,notset}
the level of logging to use
collect_weights¶
此命令允许您加载预训练模型并收集具有特定名称的张量,以便将其保存为 NPY 格式。这对于可视化学习到的权重(例如收集嵌入矩阵)以及进行一些事后分析可能很有用。您可以使用以下方式调用它
ludwig collect_weights [options]
或使用
python -m ludwig.collect weights [options]
在 Ludwig 的主目录中。
以下是可用的参数
usage: ludwig collect_weights [options]
This script loads a pretrained model and uses it collect weights.
optional arguments:
-h, --help show this help message and exit
-m MODEL_PATH, --model_path MODEL_PATH
model to load
-t TENSORS [TENSORS ...], --tensors TENSORS [TENSORS ...]
tensors to collect
-od OUTPUT_DIRECTORY, --output_directory OUTPUT_DIRECTORY
directory that contains the results
-dbg, --debug enables debugging mode
-l {critical,error,warning,info,debug,notset}, --logging_level {critical,error,warning,info,debug,notset}
the level of logging to use
三个最重要的参数是 `--model_path`(您需要在其中指定要加载模型的路径)、`--tensors`(允许您指定 Torch 图中包含要收集的权重的张量名称列表)以及 `--output_directory`(允许您指定 NPY 文件(每个指定的张量名称对应一个)的保存位置)。
为了找出包含您要收集的权重的张量名称,请使用 `collect_summary` 命令。
collect_activations¶
此命令允许您加载预训练模型和输入数据,并收集包含在具有特定名称的张量中的激活值,以便将其保存为 NPY 格式。
这对于可视化激活(例如收集最后一层的激活作为输入数据点的嵌入表示)以及进行一些事后分析可能很有用。
您可以使用以下方式调用它
ludwig collect_activations [options]
或使用
python -m ludwig.collect activations [options]
在 Ludwig 的主目录中。
以下是可用的参数
usage: ludwig collect_activations [options]
This script loads a pretrained model and uses it collect tensors for each
datapoint in the dataset.
optional arguments:
-h, --help show this help message and exit
--dataset DATASET filepath for input dataset
--data_format DATA_FORMAT format of the dataset. Valid values are auto,
csv, excel, feature, fwf, hdf5, html, tables, json,
json, jsonl, parquet, pickle, sas, spss, stata, tsv
-s {training,validation,test,full}, --split {training,validation,test,full}
the split to test the model on
-m MODEL_PATH, --model_path MODEL_PATH
model to load
-lyr LAYER [LAYER ..], --layers LAYER [LAYER ..]
layers to collect
-od OUTPUT_DIRECTORY, --output_directory OUTPUT_DIRECTORY
directory that contains the results
-bs BATCH_SIZE, --batch_size BATCH_SIZE
size of batches
-g GPUS, --gpus GPUS list of gpu to use
-gml GPU_MEMORY, --gpu_memory_limit GPU_MEMORY
maximum memory in MB of gpu memory to allocate per
GPU device
-dpt, --disable_parallel_threads
disable Torch from using multithreading
for reproducibility
-b BACKEND, --backend BACKEND
specifies backend to use for parallel / distributed execution,
defaults to local execution or Horovod if called using horovodrun
-dbg, --debug enables debugging mode
-l {critical,error,warning,info,debug,notset}, --logging_level {critical,error,warning,info,debug,notset}
the level of logging to use
数据相关和运行时相关参数(GPU、批量大小等)与 predict 中使用的参数相同,您可以参考该部分了解详细解释。
特定于收集的参数 `--model_path`、`--tensors` 和 `--output_directory` 与 collect_weights 中使用的相同,您可以参考该部分了解详细解释。
export_torchscript¶
将预训练模型导出为 Torch 的 `torchscript` 格式。
ludwig export_torchscript [options]
或使用
python -m ludwig.export torchscript [options]
以下是可用的参数
usage: ludwig export_torchscript [options]
This script loads a pretrained model and saves it as torchscript.
optional arguments:
-h, --help show this help message and exit
-m MODEL_PATH, --model_path MODEL_PATH
model to load
-mo, --model_only Script and export the model only.
-d DEVICE, --device DEVICE
Device to use for torchscript tracing (e.g. "cuda" or "cpu"). Ideally, this is the same as the device used
when the model is loaded.
-op OUTPUT_PATH, --output_path OUTPUT_PATH
path where to save the export model. If not specified, defaults to model_path.
-l {critical,error,warning,info,debug,notset}, --logging_level {critical,error,warning,info,debug,notset}
the level of logging to use
更多信息,请参阅TorchScript 导出
export_carton¶
Ludwig 模型可以导出为 Carton,这使得它可以从多种编程语言(包括 C、C++、Rust 等)运行。
为了将 Ludwig 模型导出为 Carton,首先确保您的环境中已安装 `cartonml` 包(`pip install cartonml-nightly`),然后运行以下命令
ludwig export_carton [options]
或使用
python -m ludwig.export carton [options]
以下是可用的参数
usage: ludwig export_carton [options]
This script loads a pretrained model and saves it as a Carton.
options:
-h, --help show this help message and exit
-m MODEL_PATH, --model_path MODEL_PATH
model to load
-mn MODEL_NAME, --model_name MODEL_NAME
model name
-od OUTPUT_PATH, --output_path OUTPUT_PATH
path where to save the export model
-l {critical,error,warning,info,debug,notset}, --logging_level {critical,error,warning,info,debug,notset}
the level of logging to use
更多信息,请参阅Carton 导出
export_neuropod¶
Ludwig 模型可以导出为 Neuropod,这是一种允许以框架无关方式执行模型的机制。
为了将 Ludwig 模型导出为 Neuropod,首先确保您的环境中已安装 `neuropod` 包以及适当的后端(仅使用 Python 3.7+),然后运行以下命令
ludwig export_neuropod [options]
或使用
python -m ludwig.export neuropod [options]
以下是可用的参数
usage: ludwig export_neuropod [options]
This script loads a pretrained model and uses it collect weights.
optional arguments:
-h, --help show this help message and exit
-m MODEL_PATH, --model_path MODEL_PATH
model to load
-mn MODEL_NAME, --model_name MODEL_NAME
model name
-od OUTPUT_PATH, --output_path OUTPUT_PATH
path where to save the export model
-l {critical,error,warning,info,debug,notset}, --logging_level {critical,error,warning,info,debug,notset}
the level of logging to use
此功能已使用 `neuropod==0.2.0` 进行测试。
export_mlflow¶
Ludwig 模型可以导出为 mlflow.pyfunc 模型,这允许以框架无关方式执行模型。
将 Ludwig 模型导出到 MLflow 有两种方式
- 将磁盘上已保存的模型目录转换为磁盘上的 MLflow 格式。
- 将磁盘上或现有 MLflow 实验中的已保存模型目录注册到 MLflow 模型注册表。
对于第一种方法,您只需提供本地保存的 Ludwig 模型位置以及模型应写入本地磁盘的位置
ludwig export_mlflow --model_path /saved/ludwig/model --output_path /exported/mlflow/model
对于第二种方法,您需要提供模型注册表使用的已注册模型名称
ludwig export_mlflow --model_path /saved/ludwig/model --output_path relative/model/path --registered_model_name my_ludwig_model
preprocess¶
预处理数据并将其保存为 HDF5 和 JSON 格式。然后可以使用这些预处理文件进行训练、预测和评估。这样做的好处是,数据已经过预处理,如果需要在相同数据上训练多个模型,预处理文件可以作为缓存,避免多次执行预处理。
ludwig preprocess [options]
或使用
python -m ludwig.preprocess [options]
以下是可用的参数
usage: ludwig preprocess [options]
This script preprocess a dataset
optional arguments:
-h, --help show this help message and exit
--dataset DATASET input data file path. If it has a split column, it
will be used for splitting (0: train, 1: validation,
2: test), otherwise the dataset will be randomly split
--training_set TRAINING_SET
input train data file path
--validation_set VALIDATION_SET
input validation data file path
--test_set TEST_SET input test data file path
--training_set_metadata TRAINING_SET_METADATA
input metadata JSON file path. An intermediate
preprocessed containing the mappings of the input
file created the first time a file is used, in the
same directory with the same name and a .json
extension
--data_format {auto,csv,excel,feather,fwf,hdf5,htmltables,json,jsonl,parquet,pickle,sas,spss,stata,tsv}
format of the input data
-pc PREPROCESSING_CONFIG, --preprocessing_config PREPROCESSING_CONFIG
preprocessing config. Uses the same format of config,
but ignores encoder specific parameters, decoder
specific parameters, combiner and training parameters
-pcf PREPROCESSING_CONFIG_FILE, --preprocessing_config_file PREPROCESSING_CONFIG_FILE
YAML file describing the preprocessing. Ignores
--preprocessing_config.Uses the same format of config,
but ignores encoder specific parameters, decoder
specific parameters, combiner and training parameters
-rs RANDOM_SEED, --random_seed RANDOM_SEED
a random seed that is going to be used anywhere there
is a call to a random number generator: data
splitting, parameter initialization and training set
shuffling
-dbg, --debug enables debugging mode
-l {critical,error,warning,info,debug,notset}, --logging_level {critical,error,warning,info,debug,notset}
the level of logging to use
synthesize_dataset¶
根据 YAML 格式提供的特征列表参数,创建用于测试目的的合成数据。
ludwig synthesize_dataset [options]
或使用
python -m ludwig.data.dataset_synthesizer [options]
以下是可用的参数
usage: ludwig synthesize_dataset [options]
This script generates a synthetic dataset.
optional arguments:
-h, --help show this help message and exit
-od OUTPUT_PATH, --output_path OUTPUT_PATH
output CSV file path
-d DATASET_SIZE, --dataset_size DATASET_SIZE
size of the dataset
-f FEATURES, --features FEATURES
list of features to generate in YAML format. Provide a
list containing one dictionary for each feature, each
dictionary must include a name, a type and can include
some generation parameters depending on the type
示例
ludwig synthesize_dataset --features="[ \
{name: text, type: text}, \
{name: category, type: category}, \
{name: number, type: number}, \
{name: binary, type: binary}, \
{name: set, type: set}, \
{name: bag, type: bag}, \
{name: sequence, type: sequence}, \
{name: timeseries, type: timeseries}, \
{name: date, type: date}, \
{name: h3, type: h3}, \
{name: vector, type: vector}, \
{name: image, type: image} \
]" --dataset_size=10 --output_path=synthetic_dataset.csv
可用参数取决于特征类型。
binary
- `prob` (浮点数, 默认值: `0.5`): 生成 `true` 的概率。
- `cycle` (布尔值, 默认值: `false`): 循环遍历值而不是采样。
number
- `min` (浮点数, 默认值: `0`): 生成的值范围的最小值。
- `max` (浮点数, 默认值: `1`): 生成的值范围的最大值。
category
- `vocab_size` (整数, 默认值: `10`): 用于采样的词汇表大小。
- `cycle` (布尔值, 默认值: `false`): 循环遍历值而不是采样。
sequence
- `vocab_size` (整数, 默认值: `10`): 用于采样的词汇表大小。
- `max_len` (整数, 默认值: `10`): 生成序列的最大长度。
- `min_len` (整数, 默认值: `null`): 如果为 `null`,则所有序列的长度都为 `max_len`。如果提供一个值,则长度将在 `min_len` 和 `max_len` 之间随机确定。
set
- `vocab_size` (整数, 默认值: `10`): 用于采样的词汇表大小。
- `max_len` (整数, 默认值: `10`): 生成 Set 的最大长度。
bag
- `vocab_size` (整数, 默认值: `10`): 用于采样的词汇表大小。
- `max_len` (整数, 默认值: `10`): 生成 Set 的最大长度。
text
- `vocab_size` (整数, 默认值: `10`): 用于采样的词汇表大小。
- `max_len` (整数, 默认值: `10`): 生成序列的最大长度,长度将在 `max_len - 20%` 和 `max_len` 之间随机采样。
timeseries
- `max_len` (整数, 默认值: `10`): 生成序列的最大长度。
- `min` (浮点数, 默认值: `0`): 生成的值范围的最小值。
- `max` (浮点数, 默认值: `1`): 生成的值范围的最大值。
audio
- `destination_folder` (字符串): 生成的音频文件将保存到的文件夹。
- `preprocessing: {audio_file_length_limit_in_s}` (整数, 默认值: `1`): 生成音频的秒数长度。
image
- `destination_folder` (字符串): 生成的图像文件将保存到的文件夹。
- `preprocessing: {height}` (整数, 默认值: `28`): 生成图像的像素高度。
- `preprocessing: {width}` (整数, 默认值: `28`): 生成图像的像素宽度。
- `preprocessing: {num_channels}` (整数, 默认值: `1`): 生成图像的通道数。有效值为 `1`、`3`、`4`。
- `preprocessing: {infer_image_dimensions}` (布尔值, 默认值: `true`): 是否将不同大小的图像转换为相同的宽度/高度尺寸。目标尺寸通过获取前 `infer_image_sample_size` 张图像的平均尺寸,然后应用 `infer_image_max_height` 和 `infer_image_max_width` 来推断。如果指定了明确的 `width` 和 `height`,此参数无效。
- `preprocessing: {infer_image_sample_size}` (整数, 默认值 `100`): `infer_image_dimensions` 的采样大小。
- `preprocessing: {infer_image_max_height}` (整数, 默认值 `256`): 使用 `infer_image_dimensions` 转换的图像的最大高度。
- `preprocessing: {infer_image_max_width}` (整数, 默认值 `256`): 使用 `infer_image_dimensions` 转换的图像的最大宽度。
date
无参数。
h3
无参数。
vector
- `vector_size` (整数, 默认值: `10`): 生成向量的大小。
upload_to_hf_hub¶
将微调后的 LLM 模型文件推送到 HuggingFace Hub。
ludwig upload [options]
或使用
python -m ludwig.upload [options]
以下是可用的参数
usage: ludwig upload [options]
This script pushes a trained model to a hosted model repository service
positional arguments:
{hf_hub} Name of the model repository service.
optional arguments:
-h, --help show this help message and exit
-r REPO_ID, --repo_id REPO_ID
Name of the repo. This will be created if it doesn't exist. Format: username/repo_name
-m MODEL_PATH, --model_path MODEL_PATH
Path of the trained model on disk
-p {True,False}, --private {True,False}
Make the repo private
-t {model,space,dataset}, --repo_type {model,space,dataset}
Type of repo
-c COMMIT_MESSAGE, --commit_message COMMIT_MESSAGE
The summary / title / first line of the generated commit.
-d COMMIT_DESCRIPTION, --commit_description COMMIT_DESCRIPTION
The description of the generated commit
-l {critical,error,warning,info,debug,notset}, --logging_level {critical,error,warning,info,debug,notset}
The level of logging to use
示例
ludwig upload hf_hub --repo_id ludwig/test_model --model_path ~/trained_models/my_model
这将把 `~/trained_models/my_model` 中的微调权重上传到 HuggingFace Hub 上的 `ludwig/test_model`。