Skip to main content

使用基于 PGVector 的 RetrieveChat 进行检索增强代码生成和问答

在 Colab 中打开 在 GitHub 上打开

AutoGen 提供了由 LLM 驱动的可对话代理,可以通过自动聊天来执行任务,无论是工具还是人类。该框架通过多代理对话允许工具使用和人类参与。有关此功能的文档,请查看这里

RetrieveChat 是一个用于检索增强代码生成和问答的对话系统。在这个笔记本中,我们演示了如何利用 RetrieveChat 根据自定义文档生成代码和回答问题,这些文档在 LLM 的训练数据集中不存在。RetrieveChat 使用 RetrieveAssistantAgentRetrieveUserProxyAgent,类似于其他笔记本中使用 AssistantAgentUserProxyAgent 的方式(例如,使用代码生成、执行和调试自动解决任务)。实质上,RetrieveAssistantAgentRetrieveUserProxyAgent 实现了与 RetrieveChat 提示相对应的不同自动回复机制。

目录

我们将演示使用 RetrieveChat 进行代码生成和问答的六个示例:

需求

此笔记本需要一些额外的依赖项,可以通过 pip 安装:

pip install pyautogen[retrievechat-pgvector] flaml[automl]

更多信息,请参阅安装指南

确保您拥有一个 PGVector 实例。

如果没有,可以使用 Docker 快速部署一个测试版本。

docker-compose.yml

version: '3.9'

services:
pgvector:
image: pgvector/pgvector:pg16
shm_size: 128mb
restart: unless-stopped
ports:
- "5432:5432"
environment:
POSTGRES_USER: <postgres-user>
POSTGRES_PASSWORD: <postgres-password>
POSTGRES_DB: <postgres-database>
volumes:
- ./init.sql:/docker-entrypoint-initdb.d/init.sql

创建 init.sql 文件

CREATE EXTENSION IF NOT EXISTS vector;

设置 API 端点

config_list_from_json 函数从环境变量或 json 文件中加载配置列表。

import json
import os

import chromadb
import psycopg
from sentence_transformers import SentenceTransformer

import autogen
from autogen.agentchat.contrib.retrieve_assistant_agent import RetrieveAssistantAgent
from autogen.agentchat.contrib.retrieve_user_proxy_agent import RetrieveUserProxyAgent

# 可以存储在向量数据库实例中的接受的文件格式
from autogen.retrieve_utils import TEXT_FORMATS

config_list = [
{
"model": "Meta-Llama-3-8B-Instruct-imatrix",
"api_key": "YOUR_API_KEY",
"base_url": "http://localhost:8080/v1",
"api_type": "openai",
},
{"model": "gpt-3.5-turbo-0125", "api_key": "YOUR_API_KEY", "api_type": "openai"},
{
"model": "gpt-35-turbo",
"base_url": "...",
"api_type": "azure",
"api_version": "2023-07-01-preview",
"api_key": "...",
},
]
config_list = autogen.config_list_from_json(
"OAI_CONFIG_LIST",
file_location=".",
)
assert len(config_list) > 0
print("要使用的模型:", [config_list[i]["model"] for i in range(len(config_list))])
要使用的模型:  ['gpt4-1106-preview', 'gpt-4o', 'gpt-35-turbo', 'gpt-35-turbo-0613']
tip

了解有关为代理配置 LLM 的更多信息,请点击这里

构建 RetrieveChat 的代理

我们首先初始化 RetrieveAssistantAgentRetrieveUserProxyAgent。 对于 RetrieveAssistantAgent,系统消息需要设置为“您是一个有帮助的助手。”。 用户消息中给出了详细的说明。稍后,我们将使用 RetrieveUserProxyAgent.message_generator 将说明和一个检索增强生成任务组合起来, 作为发送给 LLM 助手的初始提示。

print("docs_path 可接受的文件格式:")
print(TEXT_FORMATS)
docs_path 可接受的文件格式:
['yaml', 'ppt', 'rst', 'jsonl', 'xml', 'txt', 'yml', 'log', 'rtf', 'msg', 'xlsx', 'htm', 'pdf', 'org', 'pptx', 'md', 'docx', 'epub', 'tsv', 'csv', 'html', 'doc', 'odt', 'json']
# 1. 创建一个名为 "assistant" 的 RetrieveAssistantAgent 实例
assistant = RetrieveAssistantAgent(
name="assistant",
system_message="你是一个乐于助人的助手。你必须始终回复一些形式的文本。",
llm_config={
"timeout": 600,
"cache_seed": 42,
"config_list": config_list,
},
)

# 可选:创建 psycopg 连接对象
# conn = psycopg.connect(conninfo="postgresql://postgres:postgres@localhost:5432/postgres", autocommit=True)

# 可选:创建嵌入函数对象
sentence_transformer_ef = SentenceTransformer("all-distilroberta-v1").encode

# 2. 创建一个名为 "ragproxyagent" 的 RetrieveUserProxyAgent 实例
# 默认情况下,human_input_mode 为 "ALWAYS",这意味着代理将在每一步都要求人类输入。我们在这里将其设置为 "NEVER"。
# `docs_path` 是文档目录的路径。它也可以是单个文件的路径,或者是单个文件的 URL。默认情况下,
# 它设置为 None,只有在集合已经创建的情况下才有效。
# `task` 表示我们正在处理的任务类型。在这个例子中,是一个 `code` 任务。
# `chunk_token_size` 是用于检索聊天的块令牌大小。默认情况下,它设置为 `max_tokens * 0.6`,这里我们将其设置为 2000。
# `custom_text_types` 是要处理的文件类型列表。默认值为 `autogen.retrieve_utils.TEXT_FORMATS`。
# 这仅适用于 `docs_path` 中的目录下的文件。无论其类型如何,显式包含的文件和 URL 都将被分块处理。
# 在这个例子中,我们将其设置为 ["non-existent-type"],以仅处理 markdown 文件。由于 `websit/docs` 中没有包含任何 "non-existent-type" 文件,
# 因此那里的文件将不会被处理。但是,显式包含的 URL 仍将被处理。
ragproxyagent = RetrieveUserProxyAgent(
name="ragproxyagent",
human_input_mode="NEVER",
max_consecutive_auto_reply=1,
retrieve_config={
"task": "code",
"docs_path": [
"https://raw.githubusercontent.com/microsoft/FLAML/main/website/docs/Examples/Integrate%20-%20Spark.md",
"https://raw.githubusercontent.com/microsoft/FLAML/main/website/docs/Research.md",
os.path.join(os.path.abspath(""), "..", "website", "docs"),
],
"custom_text_types": ["non-existent-type"],
"chunk_token_size": 2000,
"model": config_list[0]["model"],
"vector_db": "pgvector", # PGVector 数据库
"collection_name": "flaml_collection",
"db_config": {
"connection_string": "postgresql://postgres:postgres@localhost:5432/postgres", # 可选 - 连接到外部向量数据库
# "host": "postgres", # 可选向量数据库主机
# "port": 5432, # 可选向量数据库端口
# "dbname": "postgres", # 可选向量数据库名称
# "username": "postgres", # 可选向量数据库用户名
# "password": "postgres", # 可选向量数据库密码
# "conn": conn, # 可选 - 连接到数据库的 conn 对象
},
"get_or_create": True, # 如果不想重用现有集合,请将其设置为 False
"overwrite": True, # 如果要覆盖现有集合,请将其设置为 True
"embedding_function": sentence_transformer_ef, # 如果省略将使用 SentenceTransformer("all-MiniLM-L6-v2").encode
},
code_execution_config=False, # 如果不想执行代码,请将其设置为 False
)
/home/lijiang1/anaconda3/envs/autogen/lib/python3.10/site-packages/transformers/utils/generic.py:311: UserWarning: torch.utils._pytree._register_pytree_node is deprecated. Please use torch.utils._pytree.register_pytree_node instead.
torch.utils._pytree._register_pytree_node(

示例 1

返回目录

使用 RetrieveChat 来帮助生成示例代码,并自动运行代码和修复错误(如果有的话)。

问题:如果我想在一个分类任务中使用 FLAML,并且想要在 30 秒内训练模型,应该使用哪个 API?使用 spark 来并行训练。如果达到时间限制,强制取消作业。

# 重置助手。在开始新对话之前,始终重置助手。
assistant.reset()

# 给定一个问题,我们使用 ragproxyagent 生成一个要发送给助手的提示作为初始消息。
# 助手接收消息并生成回复。回复将被发送回 ragproxyagent 进行处理。
# 对话将继续,直到满足终止条件,在 RetrieveChat 中,当没有检测到代码块时,终止条件是没有人在循环中。
# 在人在循环中的情况下,对话将继续,直到用户说“exit”为止。
code_problem = "如何使用 FLAML 执行分类任务并使用 spark 进行并行训练。训练 30 秒,并在达到时间限制时强制取消作业。"
chat_result = ragproxyagent.initiate_chat(
assistant, message=ragproxyagent.message_generator, problem=code_problem, search_string="spark"
)
正在尝试创建集合。
2024-06-11 19:57:44,122 - autogen.agentchat.contrib.retrieve_user_proxy_agent - INFO - 找到 2 个块。
找不到模型 gpt4-1106-preview。使用 cl100k_base 编码。
VectorDB 返回文档 ID:[['bdfbc921', '7968cf3c']]
将文档 bdfbc921 的内容添加到上下文中。
找不到模型 gpt4-1106-preview。使用 cl100k_base 编码。
将文档 7968cf3c 的内容添加到上下文中。
ragproxyagent(给助手):

你是一个增强的检索编码助手。你根据自己的知识和用户提供的上下文来回答用户的问题。
如果你无法根据当前的上下文回答问题,你应该回复“UPDATE CONTEXT”。
对于代码生成,你必须遵守以下规则:
规则 1. 你不得安装任何包,因为已经安装了所有需要的包。
规则 2. 你必须按照以下格式编写你的代码:
```language
# 你的代码
用户的问题是:如何使用FLAML执行分类任务并使用Spark进行并行训练。训练时间为30秒,如果达到时间限制则强制取消作业。

背景是:# 集成 - Spark

FLAML已经集成了Spark用于分布式训练。Spark集成有两个主要方面:

- 使用Spark ML估计器进行自动机器学习。
- 使用Spark运行并行Spark作业进行训练。

## Spark ML估计器

FLAML集成了基于Spark ML模型的估计器。这些模型使用Spark并行训练,因此我们称之为Spark估计器。要使用这些模型,您首先需要按照所需的格式组织数据。

### 数据

对于Spark估计器,AutoML只能使用Spark数据。FLAML在`flaml.automl.spark.utils`模块中提供了一个方便的函数`to_pandas_on_spark`,用于将数据转换为pandas-on-spark(`pyspark.pandas`)数据帧/系列,这是Spark估计器所需的。

此实用函数接受`pandas.Dataframe`或`pyspark.sql.Dataframe`形式的数据,并将其转换为pandas-on-spark数据帧。它还接受`pandas.Series`或`pyspark.sql.Dataframe`并将其转换为[pandas-on-spark](https://spark.apache.org/docs/latest/api/python/user_guide/pandas_on_spark/index.html)系列。如果传入`pyspark.pandas.Dataframe`,它将不会进行任何更改。

此函数还接受可选参数`index_col`和`default_index_type`。

- `index_col`是要用作索引的列名,默认为None。
- `default_index_type`是默认索引类型,默认为"distributed-sequence"。有关默认索引类型的更多信息,请参阅Spark官方[文档](https://spark.apache.org/docs/latest/api/python/user_guide/pandas_on_spark/options.html#default-index-type)。

下面是一个Spark数据的示例代码片段:

```python
```python
import pandas as pd
from flaml.automl.spark.utils import to_pandas_on_spark

# 创建一个字典
data = {
"Square_Feet": [800, 1200, 1800, 1500, 850],
"Age_Years": [20, 15, 10, 7, 25],
"Price": [100000, 200000, 300000, 240000, 120000],
}

# 创建一个 pandas DataFrame
dataframe = pd.DataFrame(data)
label = "Price"

# 转换为 pandas-on-spark DataFrame
psdf = to_pandas_on_spark(dataframe)
```

要使用 Spark ML 模型,您需要适当地格式化数据。具体来说,使用 [`VectorAssembler`](https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.ml.feature.VectorAssembler.html) 将所有特征列合并为一个向量列。

以下是如何使用它的示例:

```python
from pyspark.ml.feature import VectorAssembler

columns = psdf.columns
feature_cols = [col for col in columns if col != label]
featurizer = VectorAssembler(inputCols=feature_cols, outputCol="features")
psdf = featurizer.transform(psdf.to_spark(index_col="index"))["index", "features"]
```

在进行实验时,像处理非 Spark 数据一样使用您的 pandas-on-spark 数据,并使用 `X_train, y_train` 或 `dataframe, label` 进行传递。

### 估计器

#### 模型列表

- `lgbm_spark`:用于微调 Spark 版本 LightGBM 模型的类,使用 [SynapseML](https://microsoft.github.io/SynapseML/docs/features/lightgbm/about/) API。

#### 用法

首先,按照前面部分的描述,将数据准备成所需的格式。

通过将您打算尝试的模型包含在 `estimators_list` 参数中传递给 `flaml.automl`,FLAML 将开始尝试这些模型的配置。如果您的输入是 Spark 数据,则 FLAML 默认还会使用带有 `_spark` 后缀的估计器,即使您没有指定它们。

以下是在 AutoML 中使用 SparkML 模型的示例代码片段:

```python
import flaml

# 按照前面提到的方式,将数据准备成 pandas-on-spark 格式

automl = flaml.AutoML()
settings = {
"time_budget": 30,
"metric": "r2",
"estimator_list": ["lgbm_spark"], # 这个设置是可选的
"task": "regression",
}

automl.fit(
dataframe=psdf,
label=label,
**settings,
)
[链接到笔记本](https://github.com/microsoft/FLAML/blob/main/notebook/automl_bankrupt_synapseml.ipynb) | [在colab中打开](https://colab.research.google.com/github/microsoft/FLAML/blob/main/notebook/automl_bankrupt_synapseml.ipynb)

## 并行 Spark 作业

您可以在[自动机器学习](/docs/Use-Cases/Task-Oriented-AutoML#parallel-tuning)和[超参数调整](/docs/Use-Cases/Tune-User-Defined-Function#parallel-tuning)中将 Spark 激活为并行后端,方法是将 `use_spark` 设置为 `true`。FLAML 将使用 [`joblib-spark`](https://github.com/joblib/joblib-spark) 将您的作业分发到分布式 Spark 后端。

请注意,在应用于 Spark 数据的自动机器学习和调整过程中,不应将 `use_spark` 设置为 `true`。这是因为自动机器学习和调整过程中只会使用 SparkML 模型来处理 Spark 数据。由于 SparkML 模型可以并行运行,因此不需要再次使用 `use_spark` 进行分发。

下面列出了所有与 Spark 相关的参数。这些参数在超参数调整和自动机器学习中都可用:

- `use_spark`:布尔值,默认为 False | 是否使用 Spark 在并行 Spark 作业中运行训练。这可以用于加速大型模型和大型数据集的训练,但会增加时间开销,从而在某些情况下减慢训练速度。当 `use_spark` 为 True 时,不支持 GPU 训练。对于 Spark 集群,默认情况下,我们将为每个执行器启动一个试验。但是,有时我们希望启动的试验数量超过执行器的数量(例如,本地模式)。在这种情况下,我们可以设置环境变量 `FLAML_MAX_CONCURRENT` 来覆盖检测到的 `num_executors`。最终的并发试验数量将是 `n_concurrent_trials` 和 `num_executors` 中的最小值。
- `n_concurrent_trials`:整数,默认为 1 | 并发试验的数量。当 n_concurrent_trials > 1 时,FLAML 执行并行调整。
- `force_cancel`:布尔值,默认为 False | 如果搜索时间超过时间预算,则是否强制取消 Spark 作业。Spark 作业包括并行调整作业和基于 Spark 的模型训练作业。

使用并行 Spark 作业的示例代码片段:

```python
```python
import flaml

automl_experiment = flaml.AutoML()
automl_settings = {
"time_budget": 30,
"metric": "r2",
"task": "regression",
"n_concurrent_trials": 2,
"use_spark": True,
"force_cancel": True, # 激活 force_cancel 选项可以在超出分配的 time_budget 后立即停止 Spark 作业。
}

automl.fit(
dataframe=dataframe,
label=label,
**automl_settings,
)
```

[笔记本链接](https://github.com/microsoft/FLAML/blob/main/notebook/integrate_spark.ipynb) | [在 Colab 中打开](https://colab.research.google.com/github/microsoft/FLAML/blob/main/notebook/integrate_spark.ipynb)
# 研究

有关技术细节,请查阅我们的研究论文。

- [FLAML: 一个快速轻量级的 AutoML 库](https://www.microsoft.com/en-us/research/publication/flaml-a-fast-and-lightweight-automl-library/)。Chi Wang, Qingyun Wu, Markus Weimer, Erkang Zhu。MLSys 2021。

```bibtex
@inproceedings{wang2021flaml,
title={FLAML: A Fast and Lightweight AutoML Library},
author={Chi Wang and Qingyun Wu and Markus Weimer and Erkang Zhu},
year={2021},
booktitle={MLSys},
}
```

- [面向成本相关超参数的节俭优化](https://arxiv.org/abs/2005.01571)。Qingyun Wu, Chi Wang, Silu Huang。AAAI 2021。

```bibtex
@inproceedings{wu2021cfo,
title={Frugal Optimization for Cost-related Hyperparameters},
author={Qingyun Wu and Chi Wang and Silu Huang},
year={2021},
booktitle={AAAI},
}
```

- [混合搜索策略的经济超参数优化](https://www.microsoft.com/en-us/research/publication/economical-hyperparameter-optimization-with-blended-search-strategy/)。Chi Wang, Qingyun Wu, Silu Huang, Amin Saied。ICLR 2021。

```bibtex
@inproceedings{wang2021blendsearch,
title={Economical Hyperparameter Optimization With Blended Search Strategy},
author={Chi Wang and Qingyun Wu and Silu Huang and Amin Saied},
year={2021},
booktitle={ICLR},
}
```

- [关于预训练语言模型微调的超参数优化的实证研究](https://aclanthology.org/2021.acl-long.178.pdf)。Susan Xueqing Liu, Chi Wang。ACL 2021。

```bibtex
@inproceedings{liuwang2021hpolm,
title={An Empirical Study on Hyperparameter Optimization for Fine-Tuning Pre-trained Language Models},
author={Susan Xueqing Liu and Chi Wang},
year={2021},
booktitle={ACL},
}
```

- [在线 AutoML 的 ChaCha](https://www.microsoft.com/en-us/research/publication/chacha-for-online-automl/)。Qingyun Wu, Chi Wang, John Langford, Paul Mineiro 和 Marco Rossi。ICML 2021。

```bibtex
@inproceedings{wu2021chacha,
title={ChaCha for Online AutoML},
author={Qingyun Wu and Chi Wang and John Langford and Paul Mineiro and Marco Rossi},
year={2021},
booktitle={ICML},
}
```

- [公平的 AutoML](https://arxiv.org/abs/2111.06495)。Qingyun Wu, Chi Wang。ArXiv preprint arXiv:2111.06495 (2021)。

```bibtex
@inproceedings{wuwang2021fairautoml,
title={Fair AutoML},
ragproxyagent (to assistant):

You're a retrieve augmented coding assistant. You answer user's questions based on your own knowledge and the
context provided by the user.
If you can't answer the question with or without the current context, you should reply exactly `UPDATE CONTEXT`.
For code generation, you must obey the following rules:
Rule 1. You MUST NOT install any packages because all the packages needed are already installed.
Rule 2. You must follow the formats below to write your code:
```language
# your code
用户的问题是:如何使用FLAML执行分类任务并使用Spark进行并行训练。训练30秒,并在达到时间限制时强制取消作业。

背景是:# 集成 - Spark

FLAML已经集成了Spark用于分布式训练。与Spark的集成有两个主要方面:

- 使用Spark ML估计器进行自动机器学习。
- 使用Spark运行并行Spark作业进行训练。

## Spark ML估计器

FLAML集成了基于Spark ML模型的估计器。这些模型使用Spark并行训练,因此我们称之为Spark估计器。要使用这些模型,您首先需要按照所需的格式组织数据。

### 数据

对于Spark估计器,AutoML只能使用Spark数据。FLAML在`flaml.automl.spark.utils`模块中提供了一个方便的函数`to_pandas_on_spark`,用于将数据转换为pandas-on-spark(`pyspark.pandas`)数据帧/系列,这是Spark估计器所需的。

此实用函数接受`pandas.Dataframe`或`pyspark.sql.Dataframe`形式的数据,并将其转换为pandas-on-spark数据帧。它还接受`pandas.Series`或`pyspark.sql.Dataframe`并将其转换为[pandas-on-spark](https://spark.apache.org/docs/latest/api/python/user_guide/pandas_on_spark/index.html)系列。如果传入`pyspark.pandas.Dataframe`,它将不会进行任何更改。

该函数还接受可选参数`index_col`和`default_index_type`。

- `index_col`是要用作索引的列名,默认为None。
- `default_index_type`是默认索引类型,默认为"distributed-sequence"。有关默认索引类型的更多信息,请参阅Spark官方[文档](https://spark.apache.org/docs/latest/api/python/user_guide/pandas_on_spark/options.html#default-index-type)

以下是Spark数据的示例代码片段:

```python
```python
import pandas as pd
from flaml.automl.spark.utils import to_pandas_on_spark

# 创建一个字典
data = {
"Square_Feet": [800, 1200, 1800, 1500, 850],
"Age_Years": [20, 15, 10, 7, 25],
"Price": [100000, 200000, 300000, 240000, 120000],
}

# 创建一个 pandas DataFrame
dataframe = pd.DataFrame(data)
label = "Price"

# 转换为 pandas-on-spark DataFrame
psdf = to_pandas_on_spark(dataframe)
```

要使用 Spark ML 模型,您需要适当地格式化数据。具体来说,使用 [`VectorAssembler`](https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.ml.feature.VectorAssembler.html) 将所有特征列合并为一个向量列。

以下是如何使用它的示例:

```python
from pyspark.ml.feature import VectorAssembler

columns = psdf.columns
feature_cols = [col for col in columns if col != label]
featurizer = VectorAssembler(inputCols=feature_cols, outputCol="features")
psdf = featurizer.transform(psdf.to_spark(index_col="index"))["index", "features"]
```

在进行实验时,像处理非 Spark 数据一样使用您的 pandas-on-spark 数据,并使用 `X_train, y_train` 或 `dataframe, label` 进行传递。

### 估计器

#### 模型列表

- `lgbm_spark`:用于微调 Spark 版本 LightGBM 模型的类,使用 [SynapseML](https://microsoft.github.io/SynapseML/docs/features/lightgbm/about/) API。

#### 用法

首先,按照前一节中的描述,将数据准备成所需的格式。

通过将您打算尝试的模型包含在 `estimators_list` 参数中传递给 `flaml.automl`,FLAML 将开始尝试这些模型的配置。如果您的输入是 Spark 数据,即使您没有指定它们,FLAML 也会默认使用带有 `_spark` 后缀的估计器。

以下是在 AutoML 中使用 SparkML 模型的示例代码片段:

```python
import flaml

# 按照前面提到的方式准备您的 pandas-on-spark 格式数据

automl = flaml.AutoML()
settings = {
"time_budget": 30,
"metric": "r2",
"estimator_list": ["lgbm_spark"], # 这个设置是可选的
"task": "regression",
}

automl.fit(
dataframe=psdf,
label=label,
**settings,
)
[链接到笔记本](https://github.com/microsoft/FLAML/blob/main/notebook/automl_bankrupt_synapseml.ipynb) | [在colab中打开](https://colab.research.google.com/github/microsoft/FLAML/blob/main/notebook/automl_bankrupt_synapseml.ipynb)

## 并行 Spark 作业

您可以在[AutoML](/docs/Use-Cases/Task-Oriented-AutoML#parallel-tuning)和[超参数调整](/docs/Use-Cases/Tune-User-Defined-Function#parallel-tuning)中将Spark激活为并行后端,方法是将`use_spark`设置为`true`。FLAML将使用[`joblib-spark`](https://github.com/joblib/joblib-spark)将您的作业分发到分布式Spark后端。

请注意,当应用于Spark数据的AutoML和调整时,不应将`use_spark`设置为`true`。这是因为在AutoML和调整中,仅使用SparkML模型来处理Spark数据。由于SparkML模型可以并行运行,因此不需要再使用`use_spark`进行分发。

下面列出了与Spark相关的所有参数。这些参数在超参数调整和AutoML中都可用:

- `use_spark`:布尔值,默认为False | 是否使用Spark在并行Spark作业中运行训练。这可以用于加速大型模型和大型数据集的训练,但会增加时间开销,从而在某些情况下减慢训练速度。当`use_spark`为True时,不支持GPU训练。对于Spark集群,默认情况下,我们将每个执行器启动一个试验。但是,有时我们希望启动的试验数量超过执行器的数量(例如,本地模式)。在这种情况下,我们可以设置环境变量`FLAML_MAX_CONCURRENT`以覆盖检测到的`num_executors`。最终的并发试验数将是`n_concurrent_trials`和`num_executors`的最小值。
- `n_concurrent_trials`:整数,默认为1 | 并发试验的数量。当n_concurrent_trials > 1时,FLAML执行并行调整。
- `force_cancel`:布尔值,默认为False | 如果搜索时间超过时间预算,则是否强制取消Spark作业。Spark作业包括并行调整作业和基于Spark的模型训练作业。

使用并行Spark作业的示例代码段:

```python
```python
import flaml

automl_experiment = flaml.AutoML()
automl_settings = {
"time_budget": 30,
"metric": "r2",
"task": "regression",
"n_concurrent_trials": 2,
"use_spark": True,
"force_cancel": True, # 激活 force_cancel 选项可以在超出分配的 time_budget 后立即停止 Spark 作业。
}

automl.fit(
dataframe=dataframe,
label=label,
**automl_settings,
)
```

[笔记本链接](https://github.com/microsoft/FLAML/blob/main/notebook/integrate_spark.ipynb) | [在 Colab 中打开](https://colab.research.google.com/github/microsoft/FLAML/blob/main/notebook/integrate_spark.ipynb)
# 研究

有关技术细节,请查阅我们的研究论文。

- [FLAML: 一款快速且轻量级的 AutoML 库](https://www.microsoft.com/en-us/research/publication/flaml-a-fast-and-lightweight-automl-library/)。Chi Wang, Qingyun Wu, Markus Weimer, Erkang Zhu. MLSys 2021.

```bibtex
@inproceedings{wang2021flaml,
title={FLAML: 一款快速且轻量级的 AutoML 库},
author={Chi Wang and Qingyun Wu and Markus Weimer and Erkang Zhu},
year={2021},
booktitle={MLSys},
}
```

- [面向成本相关超参数的节俭优化](https://arxiv.org/abs/2005.01571)。Qingyun Wu, Chi Wang, Silu Huang. AAAI 2021.

```bibtex
@inproceedings{wu2021cfo,
title={面向成本相关超参数的节俭优化},
author={Qingyun Wu and Chi Wang and Silu Huang},
year={2021},
booktitle={AAAI},
}
```

- [混合搜索策略的经济超参数优化](https://www.microsoft.com/en-us/research/publication/economical-hyperparameter-optimization-with-blended-search-strategy/)。Chi Wang, Qingyun Wu, Silu Huang, Amin Saied. ICLR 2021.

```bibtex
@inproceedings{wang2021blendsearch,
title={混合搜索策略的经济超参数优化},
author={Chi Wang and Qingyun Wu and Silu Huang and Amin Saied},
year={2021},
booktitle={ICLR},
}
```

- [关于预训练语言模型微调的超参数优化的实证研究](https://aclanthology.org/2021.acl-long.178.pdf)。Susan Xueqing Liu, Chi Wang. ACL 2021.

```bibtex
@inproceedings{liuwang2021hpolm,
title={关于预训练语言模型微调的超参数优化的实证研究},
author={Susan Xueqing Liu and Chi Wang},
year={2021},
booktitle={ACL},
}
```

- [在线 AutoML 中的 ChaCha](https://www.microsoft.com/en-us/research/publication/chacha-for-online-automl/)。Qingyun Wu, Chi Wang, John Langford, Paul Mineiro 和 Marco Rossi. ICML 2021.

```bibtex
@inproceedings{wu2021chacha,
title={在线 AutoML 中的 ChaCha},
author={Qingyun Wu and Chi Wang and John Langford and Paul Mineiro and Marco Rossi},
year={2021},
booktitle={ICML},
}
```

- [公平的 AutoML](https://arxiv.org/abs/2111.06495)。Qingyun Wu, Chi Wang. ArXiv preprint arXiv:2111.06495 (2021).

```bibtex
@inproceedings{wuwang2021fairautoml,
title={公平的 AutoML},
```python
# 将pandas DataFrame转换为Spark DataFrame
spark_df = spark.createDataFrame(data)

# 将Spark DataFrame转换为pandas DataFrame
pandas_df = to_pandas_on_spark(spark_df)

# 创建FLAML AutoML对象
automl = AutoML()

# 配置FLAML AutoML
automl_settings = {
"time_budget": 30, # 设置时间预算为30秒
"task": "classification", # 设置任务类型为分类
"log_file_name": "flaml.log", # 设置日志文件名
"log_training_metric": True, # 记录训练指标
"n_jobs": -1, # 使用所有可用的CPU核心
}

# 在Spark上训练FLAML AutoML模型
automl.fit(spark_df, **automl_settings)

# 获取最佳模型和性能指标
best_model = automl.best_model
best_model_metric = automl.best_model_metric

# 将最佳模型应用于新数据
new_data = pd.DataFrame(...) # 新数据的pandas DataFrame
predictions = best_model.predict(new_data)
```

请注意,上述代码假设您已经在Spark上配置了FLAML,并且已经将数据加载到了Spark DataFrame中。您需要根据您的实际情况进行相应的调整。

希望这可以帮助您在Spark中使用FLAML进行并行训练和分类任务。如果您有任何进一步的问题,请随时提问。
### 示例 2

[返回顶部](#table-of-contents)

使用 RetrieveChat 来回答一个与代码生成无关的问题。

问题:FLAML 的作者是谁?
```python
# 重置助手。在开始新对话之前,始终重置助手。
assistant.reset()

# 可选地创建 psycopg 连接对象
conn = psycopg.connect(conninfo="postgresql://postgres:postgres@localhost:5432/postgres", autocommit=True)

ragproxyagent = RetrieveUserProxyAgent(
name="ragproxyagent",
human_input_mode="NEVER",
max_consecutive_auto_reply=1,
retrieve_config={
"task": "code",
"docs_path": [
"https://raw.githubusercontent.com/microsoft/FLAML/main/website/docs/Examples/Integrate%20-%20Spark.md",
"https://raw.githubusercontent.com/microsoft/FLAML/main/website/docs/Research.md",
os.path.join(os.path.abspath(""), "..", "website", "docs"),
],
"custom_text_types": ["non-existent-type"],
"chunk_token_size": 2000,
"model": config_list[0]["model"],
"vector_db": "pgvector", # PGVector 数据库
"collection_name": "flaml_collection",
"db_config": {
# "connection_string": "postgresql://postgres:postgres@localhost:5432/postgres", # 可选 - 连接到外部向量数据库
# "host": "postgres", # 可选的向量数据库主机
# "port": 5432, # 可选的向量数据库端口
# "dbname": "postgres", # 可选的向量数据库名称
# "username": "postgres", # 可选的向量数据库用户名
# "password": "postgres", # 可选的向量数据库密码
"conn": conn, # 可选 - 连接到数据库的 conn 对象
},
"get_or_create": True, # 如果不想重用现有集合,请将其设置为 False
"overwrite": True, # 如果要覆盖现有集合,请将其设置为 True
},
code_execution_config=False, # 如果不想执行代码,请将其设置为 False
)

qa_problem = "FLAML 的作者是谁?"
chat_result = ragproxyagent.initiate_chat(assistant, message=ragproxyagent.message_generator, problem=qa_problem)
```
``` text
/home/lijiang1/anaconda3/envs/autogen/lib/python3.10/site-packages/transformers/utils/generic.py:311: UserWarning: torch.utils._pytree._register_pytree_node is deprecated. Please use torch.utils._pytree.register_pytree_node instead.
torch.utils._pytree._register_pytree_node(
```

``` text
尝试创建集合。
```

``` text
2024-06-11 19:58:21,076 - autogen.agentchat.contrib.retrieve_user_proxy_agent - INFO - 找到 2 个块。
找不到模型 gpt4-1106-preview。使用 cl100k_base 编码。
```

``` text
VectorDB 返回文档 ID:[['7968cf3c', 'bdfbc921']]
将文档 7968cf3c 的内容添加到上下文中。
```

``` text
找不到模型 gpt4-1106-preview。使用 cl100k_base 编码。
```

``` text
将文档 bdfbc921 的内容添加到上下文中。
ragproxyagent(对助手):

你是一个增强型检索编码助手。你根据自己的知识和用户提供的上下文来回答用户的问题。
如果你无法根据当前上下文回答问题,你应该回复 `UPDATE CONTEXT`。
对于代码生成,你必须遵守以下规则:
规则 1. 你不得安装任何包,因为所需的所有包已经安装好了。
规则 2. 你必须按照以下格式编写你的代码:
```language
# 你的代码
```

用户的问题是:FLAML 的作者是谁?

上下文是:# 研究

有关技术细节,请查看我们的研究出版物。

- [FLAML: A Fast and Lightweight AutoML Library](https://www.microsoft.com/en-us/research/publication/flaml-a-fast-and-lightweight-automl-library/)。Chi Wang, Qingyun Wu, Markus Weimer, Erkang Zhu。MLSys 2021。

```bibtex
@inproceedings{wang2021flaml,
title={FLAML: A Fast and Lightweight AutoML Library},
author={Chi Wang and Qingyun Wu and Markus Weimer and Erkang Zhu},
year={2021},
booktitle={MLSys},
}
```

- [Frugal Optimization for Cost-related Hyperparameters](https://arxiv.org/abs/2005.01571)。Qingyun Wu, Chi Wang, Silu Huang。AAAI 2021。

```bibtex
@inproceedings{wu2021cfo,
title={Frugal Optimization for Cost-related Hyperparameters},
author={Qingyun Wu and Chi Wang and Silu Huang},
year={2021},
booktitle={AAAI},
}
```

- [Economical Hyperparameter Optimization With Blended Search Strategy](https://www.microsoft.com/en-us/research/publication/economical-hyperparameter-optimization-with-blended-search-strategy/)。Chi Wang, Qingyun Wu, Silu Huang, Amin Saied。ICLR 2021。

```bibtex
@inproceedings{wang2021blendsearch,
title={Economical Hyperparameter Optimization With Blended Search Strategy},
author={Chi Wang and Qingyun Wu and Silu Huang and Amin Saied},
year={2021},
booktitle={ICLR},
}
```

- [An Empirical Study on Hyperparameter Optimization for Fine-Tuning Pre-trained Language Models](https://aclanthology.org/2021.acl-long.178.pdf)。Susan Xueqing Liu, Chi Wang。ACL 2021。

```bibtex
@inproceedings{liuwang2021hpolm,
# 基于预训练语言模型的超参数优化的实证研究

- [在线自动机器学习的ChaCha](https://www.microsoft.com/en-us/research/publication/chacha-for-online-automl/)。Qingyun Wu, Chi Wang, John Langford, Paul Mineiro和Marco Rossi。ICML 2021。

```bibtex
@inproceedings{wu2021chacha,
title={ChaCha for Online AutoML},
author={Qingyun Wu and Chi Wang and John Langford and Paul Mineiro and Marco Rossi},
year={2021},
booktitle={ICML},
}
```

- [公平的自动机器学习](https://arxiv.org/abs/2111.06495)。Qingyun Wu, Chi Wang。ArXiv预印本arXiv:2111.06495(2021年)。

```bibtex
@inproceedings{wuwang2021fairautoml,
title={Fair AutoML},
author={Qingyun Wu and Chi Wang},
year={2021},
booktitle={ArXiv preprint arXiv:2111.06495},
}
```

- [针对资源受限的自动机器学习的稳健默认配置挖掘](https://arxiv.org/abs/2202.09927)。Moe Kayali, Chi Wang。ArXiv预印本arXiv:2202.09927(2022年)。

```bibtex
@inproceedings{kayaliwang2022default,
title={Mining Robust Default Configurations for Resource-constrained AutoML},
author={Moe Kayali and Chi Wang},
year={2022},
booktitle={ArXiv preprint arXiv:2202.09927},
}
```

- [基于词典偏好的多目标超参数优化](https://openreview.net/forum?id=0Ij9_q567Ma)。Shaokun Zhang, Feiran Jia, Chi Wang, Qingyun Wu。ICLR 2023(显著性前5%)。

```bibtex
@inproceedings{zhang2023targeted,
title={Targeted Hyperparameter Optimization with Lexicographic Preferences Over Multiple Objectives},
author={Shaokun Zhang and Feiran Jia and Chi Wang and Qingyun Wu},
booktitle={International Conference on Learning Representations},
year={2023},
url={https://openreview.net/forum?id=0Ij9_q567Ma},
}
```

- [大型语言模型生成推理的成本效益超参数优化](https://arxiv.org/abs/2303.04673)。Chi Wang, Susan Xueqing Liu, Ahmed H. Awadallah。ArXiv预印本arXiv:2303.04673(2023年)。

```bibtex
@inproceedings{wang2023EcoOptiGen,
title={Cost-Effective Hyperparameter Optimization for Large Language Model Generation Inference},
author={Chi Wang and Susan Xueqing Liu and Ahmed H. Awadallah},
year={2023},
booktitle={ArXiv preprint arXiv:2303.04673},
}
```

- [使用GPT-4解决具有挑战性的数学问题的实证研究](https://arxiv.org/abs/2306.01337)。Yiran Wu, Feiran Jia, Shaokun Zhang, Hangyu Li, Erkang Zhu, Yue Wang, Yin Tat Lee, Richard Peng, Qingyun Wu, Chi Wang。ArXiv预印本arXiv:2306.01337(2023年)。

```bibtex
@inproceedings{wu2023empirical,
title={An Empirical Study on Challenging Math Problem Solving with GPT-4},
author={Yiran Wu and Feiran Jia and Shaokun Zhang and Hangyu Li and Erkang Zhu and Yue Wang and Yin Tat Lee and Richard Peng and Qingyun Wu and Chi Wang},
year={2023},
# 集成 - Spark

FLAML已经集成了Spark进行分布式训练。Spark集成主要有两个方面:

- 使用Spark ML估计器进行自动机器学习。
- 使用Spark运行并行的Spark作业进行训练。

## Spark ML估计器

FLAML集成了基于Spark ML模型的估计器。这些模型使用Spark并行训练,因此我们称之为Spark估计器。要使用这些模型,您首先需要按照所需的格式组织数据。

### 数据

对于Spark估计器,AutoML只能处理Spark数据。FLAML在`flaml.automl.spark.utils`模块中提供了一个方便的函数`to_pandas_on_spark`,用于将数据转换为pandas-on-spark(`pyspark.pandas`)数据帧/系列,这是Spark估计器所需的。

这个实用函数接受`pandas.Dataframe`或`pyspark.sql.Dataframe`形式的数据,并将其转换为pandas-on-spark数据帧。它还接受`pandas.Series`或`pyspark.sql.Dataframe`并将其转换为[pandas-on-spark](https://spark.apache.org/docs/latest/api/python/user_guide/pandas_on_spark/index.html)系列。如果传入`pyspark.pandas.Dataframe`,它将不会进行任何更改。

该函数还接受可选参数`index_col`和`default_index_type`。

- `index_col`是要用作索引的列名,默认为None。
- `default_index_type`是默认的索引类型,默认为"distributed-sequence"。有关默认索引类型的更多信息可以在Spark官方[文档](https://spark.apache.org/docs/latest/api/python/user_guide/pandas_on_spark/options.html#default-index-type)中找到。

下面是一个使用Spark数据的示例代码片段:

```python
import pandas as pd
from flaml.automl.spark.utils import to_pandas_on_spark

# 创建一个字典
data = {
"Square_Feet": [800, 1200, 1800, 1500, 850],
"Age_Years": [20, 15, 10, 7, 25],
"Price": [100000, 200000, 300000, 240000, 120000],
}

# 创建一个pandas DataFrame
dataframe = pd.DataFrame(data)
label = "Price"

# 转换为pandas-on-spark数据帧
psdf = to_pandas_on_spark(dataframe)
```

要使用Spark ML模型,您需要适当地格式化数据。具体来说,使用[`VectorAssembler`](https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.ml.feature.VectorAssembler.html)将所有特征列合并为一个向量列。

以下是如何使用的示例:

```python
from pyspark.ml.feature import VectorAssembler

columns = psdf.columns
feature_cols = [col for col in columns if col != label]
featurizer = VectorAssembler(inputCols=feature_cols, outputCol="features")
psdf = featurizer.transform(psdf.to_spark(index_col="index"))["index", "features"]
```

在进行实验时,可以像非 Spark 数据一样使用你的 pandas-on-spark 数据,并使用 `X_train, y_train` 或 `dataframe, label` 进行传递。

### 估计器

#### 模型列表

- `lgbm_spark`:用于微调 Spark 版本 LightGBM 模型的类,使用 [SynapseML](https://microsoft.github.io/SynapseML/docs/features/lightgbm/about/) API。

#### 用法

首先,按照前一节中的描述,将数据准备成所需的格式。

通过将你打算尝试的模型包含在 `estimators_list` 参数中传递给 `flaml.automl`,FLAML 将开始尝试这些模型的配置。如果你的输入是 Spark 数据,即使你没有指定,FLAML 也会默认使用带有 `_spark` 后缀的估计器。

以下是使用 AutoML 中的 SparkML 模型的示例代码片段:

```python
```python
import flaml

# 准备你的数据,格式为 pandas-on-spark,如前所述

automl = flaml.AutoML()
settings = {
"time_budget": 30,
"metric": "r2",
"estimator_list": ["lgbm_spark"], # 这个设置是可选的
"task": "regression",
}

automl.fit(
dataframe=psdf,
label=label,
**settings,
)
```

[笔记本链接](https://github.com/microsoft/FLAML/blob/main/notebook/automl_bankrupt_synapseml.ipynb) | [在 Colab 中打开](https://colab.research.google.com/github/microsoft/FLAML/blob/main/notebook/automl_bankrupt_synapseml.ipynb)

## 并行 Spark 作业

您可以在[AutoML](/docs/Use-Cases/Task-Oriented-AutoML#parallel-tuning)和[超参数调整](/docs/Use-Cases/Tune-User-Defined-Function#parallel-tuning)中将 Spark 设置为并行后端,只需将 `use_spark` 设置为 `true`。FLAML 将使用 [`joblib-spark`](https://github.com/joblib/joblib-spark) 将您的作业分发到分布式 Spark 后端。

请注意,在应用于 Spark 数据的 AutoML 和调整过程中,不应将 `use_spark` 设置为 `true`。这是因为在 AutoML 和调整过程中,只会使用 SparkML 模型来处理 Spark 数据。由于 SparkML 模型可以并行运行,因此不需要再次使用 `use_spark` 进行分发。

下面列出了所有与 Spark 相关的参数。这些参数在超参数调整和 AutoML 中都可用:

- `use_spark`:布尔值,默认为 False | 是否使用 Spark 在并行 Spark 作业中运行训练。这可以用于加速大型模型和大型数据集的训练,但会增加时间开销,从而在某些情况下减慢训练速度。当 `use_spark` 为 True 时,不支持 GPU 训练。对于 Spark 集群,默认情况下,我们将为每个执行器启动一个试验。然而,有时我们希望启动的试验数量超过执行器的数量(例如,本地模式)。在这种情况下,我们可以设置环境变量 `FLAML_MAX_CONCURRENT` 来覆盖检测到的 `num_executors`。最终的并发试验数量将是 `n_concurrent_trials` 和 `num_executors` 中的最小值。
- `n_concurrent_trials`:整数,默认为 1 | 并发试验的数量。当 `n_concurrent_trials` 大于 1 时,FLAML 执行并行调整。
- `force_cancel`:布尔值,默认为 False | 如果搜索时间超过时间预算,则是否强制取消 Spark 作业。Spark 作业包括并行调整作业和基于 Spark 的模型训练作业。

使用并行 Spark 作业的示例代码片段:

```python
import flaml

automl_experiment = flaml.AutoML()
automl_settings = {
"time_budget": 30,
"metric": "r2",
"task": "regression",
"n_concurrent_trials": 2,
"use_spark": True,
"force_cancel": True, # 激活 force_cancel 选项可以在超过分配的时间预算后立即停止 Spark 作业。
}

automl.fit(
dataframe=dataframe,
label=label,
**automl_settings,
)
```
[链接到笔记本](https://github.com/microsoft/FLAML/blob/main/notebook/integrate_spark.ipynb) | [在colab中打开](https://colab.research.google.com/github/microsoft/FLAML/blob/main/notebook/integrate_spark.ipynb)



--------------------------------------------------------------------------------
ragproxyagent(对助手说):

你是一个增强型的检索编码助手。你根据自己的知识和用户提供的上下文来回答用户的问题。
如果你无论有无当前上下文都无法回答问题,你应该回复`UPDATE CONTEXT`。
对于代码生成,你必须遵守以下规则:
规则1. 你绝对不能安装任何包,因为所需的所有包都已经安装好了。
规则2. 你必须按照以下格式编写你的代码:
```language
# 你的代码
```

用户的问题是:FLAML的作者是谁?

背景是:# 研究

有关技术细节,请查阅我们的研究出版物。

- [FLAML:一种快速轻量级的AutoML库](https://www.microsoft.com/en-us/research/publication/flaml-a-fast-and-lightweight-automl-library/)。Chi Wang,Qingyun Wu,Markus Weimer,Erkang Zhu。MLSys 2021。

```bibtex
@inproceedings{wang2021flaml,
title={FLAML: A Fast and Lightweight AutoML Library},
author={Chi Wang and Qingyun Wu and Markus Weimer and Erkang Zhu},
year={2021},
booktitle={MLSys},
}
```

- [面向成本相关超参数的节俭优化](https://arxiv.org/abs/2005.01571)。Qingyun Wu,Chi Wang,Silu Huang。AAAI 2021。

```bibtex
@inproceedings{wu2021cfo,
title={Frugal Optimization for Cost-related Hyperparameters},
author={Qingyun Wu and Chi Wang and Silu Huang},
year={2021},
booktitle={AAAI},
}
```

- [混合搜索策略的经济超参数优化](https://www.microsoft.com/en-us/research/publication/economical-hyperparameter-optimization-with-blended-search-strategy/)。Chi Wang,Qingyun Wu,Silu Huang,Amin Saied。ICLR 2021。

```bibtex
@inproceedings{wang2021blendsearch,
title={Economical Hyperparameter Optimization With Blended Search Strategy},
author={Chi Wang and Qingyun Wu and Silu Huang and Amin Saied},
year={2021},
booktitle={ICLR},
}
```

- [关于微调预训练语言模型的超参数优化的实证研究](https://aclanthology.org/2021.acl-long.178.pdf)。Susan Xueqing Liu,Chi Wang。ACL 2021。

```bibtex
@inproceedings{liuwang2021hpolm,
title={An Empirical Study on Hyperparameter Optimization for Fine-Tuning Pre-trained Language Models},
author={Susan Xueqing Liu and Chi Wang},
year={2021},
booktitle={ACL},
}
```

- [在线AutoML的ChaCha](https://www.microsoft.com/en-us/research/publication/chacha-for-online-automl/)。Qingyun Wu,Chi Wang,John Langford,Paul Mineiro和Marco Rossi。ICML 2021。

```bibtex
@inproceedings{wu2021chacha,
title={ChaCha for Online AutoML},
author={Qingyun Wu and Chi Wang and John Langford and Paul Mineiro and Marco Rossi},
year={2021},
booktitle={ICML},
}
```

- [公平的AutoML](https://arxiv.org/abs/2111.06495)。Qingyun Wu,Chi Wang。ArXiv预印本arXiv:2111.06495(2021)。

```bibtex
@inproceedings{wuwang2021fairautoml,
title={Fair AutoML},
author={Qingyun Wu and Chi Wang},
year={2021},
booktitle={ArXiv preprint arXiv:2111.06495},
}
```

- [针对资源受限的AutoML挖掘稳健的默认配置](https://arxiv.org/abs/2202.09927)。Moe Kayali,Chi Wang。ArXiv预印本arXiv:2202.09927(2022)。

```bibtex
@inproceedings{kayaliwang2022default,
title={Mining Robust Default Configurations for Resource-constrained AutoML},
author={Moe Kayali and Chi Wang},
year={2022},
booktitle={ArXiv preprint arXiv:2202.09927},
}
```

- [基于词典偏好的多目标超参数优化](https://openreview.net/forum?id=0Ij9_q567Ma). 张少坤, 贾飞然, 王驰, 吴庆云. ICLR 2023 (显著-前5%)。

```bibtex
@inproceedings{zhang2023targeted,
title={基于词典偏好的多目标超参数优化},
author={张少坤 and 贾飞然 and 王驰 and 吴庆云},
booktitle={国际学习表示会议},
year={2023},
url={https://openreview.net/forum?id=0Ij9_q567Ma},
}
```

- [大语言模型生成推理的成本效益超参数优化](https://arxiv.org/abs/2303.04673). 王驰, 刘雪晴, Ahmed H. Awadallah. ArXiv预印本 arXiv:2303.04673 (2023).

```bibtex
@inproceedings{wang2023EcoOptiGen,
title={大语言模型生成推理的成本效益超参数优化},
author={王驰 and 刘雪晴 and Ahmed H. Awadallah},
year={2023},
booktitle={ArXiv预印本 arXiv:2303.04673},
}
```

- [使用GPT-4解决具有挑战性的数学问题的实证研究](https://arxiv.org/abs/2306.01337). 吴逸然, 贾飞然, 张少坤, 李航宇, 朱尔康, 王越, 李胤达, 彭睿, 吴庆云, 王驰. ArXiv预印本 arXiv:2306.01337 (2023).

```bibtex
@inproceedings{wu2023empirical,
title={使用GPT-4解决具有挑战性的数学问题的实证研究},
author={吴逸然 and 贾飞然 and 张少坤 and 李航宇 and 朱尔康 and 王越 and 李胤达 and 彭睿 and 吴庆云 and 王驰},
year={2023},
booktitle={ArXiv预印本 arXiv:2306.01337},
}
# 集成 - Spark

FLAML已经集成了Spark用于分布式训练。Spark的集成主要有两个方面:

- 使用Spark ML估计器进行自动机器学习。
- 使用Spark运行并行的Spark作业进行训练。

## Spark ML 估计器

FLAML集成了基于Spark ML模型的估计器。这些模型使用Spark并行训练,因此我们称之为Spark估计器。要使用这些模型,您首先需要按照所需的格式组织数据。

### 数据

对于Spark估计器,AutoML只能使用Spark数据。FLAML在`flaml.automl.spark.utils`模块中提供了一个方便的函数`to_pandas_on_spark`,用于将数据转换为pandas-on-spark(`pyspark.pandas`)的DataFrame/series,这是Spark估计器所需的。

这个实用函数接受`pandas.Dataframe`或`pyspark.sql.Dataframe`形式的数据,并将其转换为pandas-on-spark DataFrame。它还接受`pandas.Series`或`pyspark.sql.Dataframe`并将其转换为[pandas-on-spark](https://spark.apache.org/docs/latest/api/python/user_guide/pandas_on_spark/index.html) series。如果传入`pyspark.pandas.Dataframe`,它将不会进行任何更改。

该函数还接受可选参数`index_col`和`default_index_type`。

- `index_col`是要用作索引的列名,默认为None。
- `default_index_type`是默认的索引类型,默认为"distributed-sequence"。有关默认索引类型的更多信息,请参阅Spark官方[文档](https://spark.apache.org/docs/latest/api/python/user_guide/pandas_on_spark/options.html#default-index-type)

下面是一个使用Spark数据的示例代码片段:

```python
```python
import pandas as pd
from flaml.automl.spark.utils import to_pandas_on_spark

# 创建一个字典
data = {
"Square_Feet": [800, 1200, 1800, 1500, 850],
"Age_Years": [20, 15, 10, 7, 25],
"Price": [100000, 200000, 300000, 240000, 120000],
}

# 创建一个 pandas DataFrame
dataframe = pd.DataFrame(data)
label = "Price"

# 转换为 pandas-on-spark DataFrame
psdf = to_pandas_on_spark(dataframe)
```

要使用 Spark ML 模型,您需要适当地格式化数据。具体来说,使用 [`VectorAssembler`](https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.ml.feature.VectorAssembler.html) 将所有特征列合并为一个向量列。

以下是如何使用的示例:

```python
from pyspark.ml.feature import VectorAssembler

columns = psdf.columns
feature_cols = [col for col in columns if col != label]
featurizer = VectorAssembler(inputCols=feature_cols, outputCol="features")
psdf = featurizer.transform(psdf.to_spark(index_col="index"))["index", "features"]
```

在进行实验时,像处理非 Spark 数据一样使用您的 pandas-on-spark 数据,并使用 `X_train, y_train` 或 `dataframe, label` 进行传递。

### 估计器

#### 模型列表

- `lgbm_spark`:用于微调 Spark 版本 LightGBM 模型的类,使用 [SynapseML](https://microsoft.github.io/SynapseML/docs/features/lightgbm/about/) API。

#### 用法

首先,按照前面部分的描述,将数据准备成所需的格式。

通过将您打算尝试的模型包含在 `estimators_list` 参数中传递给 `flaml.automl`,FLAML 将开始尝试这些模型的配置。如果您的输入是 Spark 数据,则 FLAML 默认还会使用带有 `_spark` 后缀的估计器,即使您没有指定它们。

以下是使用 SparkML 模型的示例代码片段:

```python
import flaml

# 按照前面提到的方式准备您的 pandas-on-spark 格式数据

automl = flaml.AutoML()
settings = {
"time_budget": 30,
"metric": "r2",
"estimator_list": ["lgbm_spark"], # 这个设置是可选的
"task": "regression",
}

automl.fit(
dataframe=psdf,
label=label,
**settings,
)
[链接到笔记本](https://github.com/microsoft/FLAML/blob/main/notebook/automl_bankrupt_synapseml.ipynb) | [在Colab中打开](https://colab.research.google.com/github/microsoft/FLAML/blob/main/notebook/automl_bankrupt_synapseml.ipynb)

## 并行 Spark 作业

您可以在[自动机器学习](/docs/Use-Cases/Task-Oriented-AutoML#parallel-tuning)和[超参数调整](/docs/Use-Cases/Tune-User-Defined-Function#parallel-tuning)中将 Spark 激活为并行后端,方法是将 `use_spark` 设置为 `true`。FLAML 将使用 [`joblib-spark`](https://github.com/joblib/joblib-spark) 将您的作业分发到分布式 Spark 后端。

请注意,在应用于 Spark 数据的自动机器学习和调整时,不应将 `use_spark` 设置为 `true`。这是因为自动机器学习和调整中只会使用 SparkML 模型来处理 Spark 数据。由于 SparkML 模型可以并行运行,因此不需要再次使用 `use_spark` 进行分发。

下面列出了所有与 Spark 相关的参数。这些参数在超参数调整和自动机器学习中都可用:

- `use_spark`:布尔值,默认为 False | 是否使用 Spark 在并行 Spark 作业中运行训练。这可以用于加速大型模型和大型数据集的训练,但会增加时间开销,从而在某些情况下减慢训练速度。当 `use_spark` 为 True 时,不支持 GPU 训练。对于 Spark 集群,默认情况下,我们将为每个执行器启动一个试验。但是,有时我们希望启动的试验数量超过执行器的数量(例如,本地模式)。在这种情况下,我们可以设置环境变量 `FLAML_MAX_CONCURRENT` 来覆盖检测到的 `num_executors`。最终的并发试验数量将是 `n_concurrent_trials` 和 `num_executors` 中的最小值。
- `n_concurrent_trials`:整数,默认为 1 | 并发试验的数量。当 n_concurrent_trials > 1 时,FLAML 执行并行调整。
- `force_cancel`:布尔值,默认为 False | 如果搜索时间超过时间预算,则是否强制取消 Spark 作业。Spark 作业包括并行调整作业和基于 Spark 的模型训练作业。

使用并行 Spark 作业的示例代码段:

```python
```python
import flaml

automl_experiment = flaml.AutoML()
automl_settings = {
"time_budget": 30,
"metric": "r2",
"task": "regression",
"n_concurrent_trials": 2,
"use_spark": True,
"force_cancel": True, # 激活 force_cancel 选项可以在超过分配的 time_budget 后立即停止 Spark 作业。
}

automl.fit(
dataframe=dataframe,
label=label,
**automl_settings,
)
```

[笔记本链接](https://github.com/microsoft/FLAML/blob/main/notebook/integrate_spark.ipynb) | [在 Colab 中打开](https://colab.research.google.com/github/microsoft/FLAML/blob/main/notebook/integrate_spark.ipynb)



--------------------------------------------------------------------------------
助理(给 ragproxyagent):

FLAML 的作者是王驰、吴庆云、Markus Weimer 和朱尔康。
```