Extra¶
steps
¶
DBSCAN
¶
Bases: GlobalStep
DBSCAN(基于密度的空间聚类应用与噪声)在regions of high density中查找核心样本,并从中扩展集群。此算法适用于包含相似密度集群的数据。
这是一个 GlobalStep
,它使用来自 sklearn
的 DBSCAN 算法对 embeddings 进行聚类。访问 TextClustering
step 以获取使用示例。训练后的模型在创建 distiset 并将其推送到 Hugging Face Hub 时保存为工件。
输入列
- projection (
List[float]
): 文本的向量表示,通常是UMAP
step 的输出。
输出列
- cluster_label (
int
): 表示给定集群标签的整数。-1 表示未聚类。
类别
- clustering
- text-classification
属性
名称 | 类型 | 描述 |
---|---|---|
- |
eps
|
两个样本之间被认为在彼此邻域内的最大距离。 这不是集群内点距离的最大界限。 这是最重要的 DBSCAN 参数,需要根据您的数据集和距离函数适当选择。 |
- |
min_samples
|
一个点被认为是核心点的邻域中的样本数(或总权重)。 这包括点本身。 如果 |
- |
metric
|
在特征数组中计算实例之间距离时使用的度量。 如果 metric 是字符串或可调用对象,则它必须是 |
- |
n_jobs
|
要运行的并行作业数。 |
运行时参数
eps
: 两个样本之间被认为在彼此邻域内的最大距离。 这不是集群内点距离的最大界限。 这是最重要的 DBSCAN 参数,需要根据您的数据集和距离函数适当选择。min_samples
: 一个点被认为是核心点的邻域中的样本数(或总权重)。 这包括点本身。 如果min_samples
设置为较高的值,DBSCAN 将找到更密集的集群,而如果设置为较低的值,则找到的集群将更加稀疏。metric
: 在特征数组中计算实例之间距离时使用的度量。 如果 metric 是字符串或可调用对象,则它必须是sklearn.metrics.pairwise_distances
允许的 metric 参数的选项之一。n_jobs
: 要运行的并行作业数。
源代码位于 src/distilabel/steps/clustering/dbscan.py
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 |
|
TextClustering
¶
Bases: TextClassification
, GlobalTask
对一组文本进行聚类并为每个集群生成摘要标签的任务。
这是一个从 TextClassification
继承的 GlobalTask
,这意味着该类中的所有属性在此处都可用。 此外,在这种情况下,我们一次处理所有输入,而不是使用批次。 input_batch_size
在此处用于将示例分批发送到 LLM(与更常见的 Task
定义略有不同)。 该任务在每个集群中查找给定数量的代表性示例(数量由 samples_per_cluster
属性设置),并将它们发送到 LLM 以获取代表集群的标签。 然后将标签分配给集群中的每个文本。 此步骤中使用的集群和 projections 假定是从 UMAP
+ DBSCAN
steps 获得的,但可以为类似的 steps 生成,只要它们代表相同的概念即可。 此 step 运行类似于此存储库中的 pipeline:https://github.com/huggingface/text-clustering
输入列
- text (
str
): 我们要获取标签的参考文本。 - projection (
List[float]
): 文本的向量表示,通常是UMAP
step 的输出。 - cluster_label (
int
): 表示给定集群标签的整数。-1 表示未聚类。
输出列
- summary_label (
str
): 文本的标签或标签列表。 - model_name (
str
): 用于生成标签的模型名称。
类别
- clustering
- text-classification
参考文献
属性
名称 | 类型 | 描述 |
---|---|---|
- |
savefig
|
是否生成并保存包含文本聚类的图形。 |
- |
samples_per_cluster
|
在 LLM 中用作集群样本的示例数。 |
示例
使用聚类为一组文本生成标签
from distilabel.models import InferenceEndpointsLLM
from distilabel.steps import UMAP, DBSCAN, TextClustering
from distilabel.pipeline import Pipeline
ds_name = "argilla-warehouse/personahub-fineweb-edu-4-clustering-100k"
with Pipeline(name="Text clustering dataset") as pipeline:
batch_size = 500
ds = load_dataset(ds_name, split="train").select(range(10000))
loader = make_generator_step(ds, batch_size=batch_size, repo_id=ds_name)
umap = UMAP(n_components=2, metric="cosine")
dbscan = DBSCAN(eps=0.3, min_samples=30)
text_clustering = TextClustering(
llm=InferenceEndpointsLLM(
model_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
tokenizer_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
),
n=3, # 3 labels per example
query_title="Examples of Personas",
samples_per_cluster=10,
context=(
"Describe the main themes, topics, or categories that could describe the "
"following types of personas. All the examples of personas must share "
"the same set of labels."
),
default_label="None",
savefig=True,
input_batch_size=8,
input_mappings={"text": "persona"},
use_default_structured_output=True,
)
loader >> umap >> dbscan >> text_clustering
源代码位于 src/distilabel/steps/clustering/text_clustering.py
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 |
|
inputs
property
¶
该任务的输入与 TextClassification
的输入相同,外加 projection
和 cluster_label
列(可以从 UMAP + DBSCAN steps 获得)。
outputs
property
¶
该任务的输出是 summary_label
和 model_name
。
_save_figure(data, cluster_centers, cluster_summaries)
¶
使用 matplotlib 从 dataframe 开始保存图形。
参数
名称 | 类型 | 描述 | 默认 |
---|---|---|---|
data
|
DataFrame
|
pd.DataFrame,其中包含 'X'、'Y' 和 'labels' 列,分别代表 projections 和每个文本的标签。 |
required |
cluster_centers
|
Dict[str, Tuple[float, float]]
|
从每个标签到集群中心的字典映射,以帮助注释的放置。 |
required |
cluster_summaries
|
Dict[int, str]
|
从 LLM 获取的集群摘要。 |
required |
源代码位于 src/distilabel/steps/clustering/text_clustering.py
_create_figure(inputs, label2docs, cluster_summaries)
¶
创建聚类文本的图形并将其另存为工件。
参数
名称 | 类型 | 描述 | 默认 |
---|---|---|---|
inputs
|
StepInput
|
step 的输入,因为我们将再次从中提取信息。 |
required |
label2docs
|
Dict[int, List[str]]
|
从每个标签到属于该集群的文档(文本)列表的映射。 |
required |
cluster_summaries
|
Dict[int, str]
|
从 LLM 获取的集群摘要。 |
required |
源代码位于 src/distilabel/steps/clustering/text_clustering.py
_prepare_input_texts(inputs, label2docs, unique_labels)
¶
准备一批输入以发送到 LLM,其中包含每个集群的示例。
参数
名称 | 类型 | 描述 | 默认 |
---|---|---|---|
inputs
|
StepInput
|
来自 step 的输入。 |
required |
label2docs
|
Dict[int, List[int]]
|
从每个标签到属于该集群的文档(文本)列表的映射。 |
required |
unique_labels
|
List[int]
|
集群的唯一标签。 |
required |
返回
类型 | 描述 |
---|---|
List[Dict[str, Union[str, int]]]
|
要发送到 LLM 的输入文本,其中包含每个集群的示例 |
List[Dict[str, Union[str, int]]]
|
准备在 prompt 中使用,以及一个额外的键来存储 |
List[Dict[str, Union[str, int]]]
|
标签(在批次返回后需要找到数据)。 |
List[Dict[str, Union[str, int]]]
|
从 LLM 返回)。 |
源代码位于 src/distilabel/steps/clustering/text_clustering.py
UMAP
¶
Bases: GlobalStep
UMAP 是一种通用的流形学习和降维算法。
这是一个 GlobalStep
,它使用 embeddings 降低维度。 访问 TextClustering
step 以获取使用示例。 训练后的模型在创建 distiset 并将其推送到 Hugging Face Hub 时保存为工件。
输入列
- embedding (
List[float]
): 我们要降低维度的原始 embeddings。
输出列
- projection (
List[float]
): 降低到指定组件数的 Embedding,新 embeddings 的大小将由n_components
确定。
类别
- clustering
- text-classification
属性
名称 | 类型 | 描述 |
---|---|---|
- |
n_components
|
要嵌入的空间的维度。 默认为 2 以提供简单的可视化(这可能是您想要的),但可以合理地设置为 2 到 100 范围内的任何整数值。 |
- |
metric
|
用于计算高维空间距离的度量。 有关更多信息,请访问 UMAP 的文档。 默认为 |
- |
n_jobs
|
要运行的并行作业数。 默认为 |
- |
random_state
|
用于 UMAP 算法的随机状态。 |
运行时参数
n_components
: 要嵌入的空间的维度。 默认为 2 以提供简单的可视化(这可能是您想要的),但可以合理地设置为 2 到 100 范围内的任何整数值。metric
: 用于计算高维空间距离的度量。 有关更多信息,请访问 UMAP 的文档。 默认为euclidean
。n_jobs
: 要运行的并行作业数。 默认为8
。random_state
: 用于 UMAP 算法的随机状态。
引文
@misc{mcinnes2020umapuniformmanifoldapproximation,
title={UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction},
author={Leland McInnes and John Healy and James Melville},
year={2020},
eprint={1802.03426},
archivePrefix={arXiv},
primaryClass={stat.ML},
url={https://arxiv.org/abs/1802.03426},
}
源代码位于 src/distilabel/steps/clustering/umap.py
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 |
|
CombineOutputs
¶
Bases: Step
组合多个上游 steps 的输出。
CombineOutputs
是一个 Step
,它获取多个上游 steps 的输出并将它们组合起来,生成一个包含上游 steps 输出的所有键/列的新字典。
输入列
- 动态的(基于上游
Step
s):上游 steps 输出的所有列。
输出列
- 动态的(基于上游
Step
s):上游 steps 输出的所有列。
类别
- columns
示例
Combine dictionaries of a dataset:
```python
from distilabel.steps import CombineOutputs
combine_outputs = CombineOutputs()
combine_outputs.load()
result = next(
combine_outputs.process(
[{"a": 1, "b": 2}, {"a": 3, "b": 4}],
[{"c": 5, "d": 6}, {"c": 7, "d": 8}],
)
)
# [
# {"a": 1, "b": 2, "c": 5, "d": 6},
# {"a": 3, "b": 4, "c": 7, "d": 8},
# ]
```
Combine upstream steps outputs in a pipeline:
```python
from distilabel.pipeline import Pipeline
from distilabel.steps import CombineOutputs
with Pipeline() as pipeline:
step_1 = ...
step_2 = ...
step_3 = ...
combine = CombineOutputs()
[step_1, step_2, step_3] >> combine
```
源代码位于 src/distilabel/steps/columns/combine.py
DeitaFiltering
¶
Bases: GlobalStep
使用 DEITA 过滤策略过滤数据集行。
根据 DEITA 分数和 embeddings 之间的余弦距离过滤数据集。 它是论文“What Makes Good Data for Alignment? A Comprehensive Study of Automatic Data Selection in Instruction Tuning”中过滤步骤的实现。
属性
名称 | 类型 | 描述 |
---|---|---|
data_budget |
RuntimeParameter[int]
|
过滤后数据集的期望大小。 |
diversity_threshold |
RuntimeParameter[float]
|
如果某行与其最近邻居的余弦距离大于此值,则会将其包含在过滤后的数据集中。 默认为 |
normalize_embeddings |
RuntimeParameter[bool]
|
是否在计算余弦距离之前对 embeddings 进行归一化。 默认为 |
运行时参数
data_budget
: 过滤后数据集的期望大小。diversity_threshold
: 如果某行与其最近邻居的余弦距离大于此值,则会将其包含在过滤后的数据集中。
输入列
- evol_instruction_score (
float
): 由ComplexityScorer
step 生成的 instruction 的分数。 - evol_response_score (
float
): 由QualityScorer
step 生成的 response 的分数。 - embedding (
List[float]
): 使用GenerateEmbeddings
step 为 instruction-response 对的 conversation 生成的 embedding。
输出列
- deita_score (
float
): instruction-response 对的 DEITA 分数。 - deita_score_computed_with (
List[str]
): 用于计算 DEITA 分数的分数。 - nearest_neighbor_distance (
float
): instruction-response 对的 embeddings 之间的余弦距离。
类别
- filtering
示例
根据 DEITA 分数和 embeddings 之间的余弦距离过滤数据集
from distilabel.steps import DeitaFiltering
deita_filtering = DeitaFiltering(data_budget=1)
deita_filtering.load()
result = next(
deita_filtering.process(
[
{
"evol_instruction_score": 0.5,
"evol_response_score": 0.5,
"embedding": [-8.12729941, -5.24642847, -6.34003029],
},
{
"evol_instruction_score": 0.6,
"evol_response_score": 0.6,
"embedding": [2.99329242, 0.7800932, 0.7799726],
},
{
"evol_instruction_score": 0.7,
"evol_response_score": 0.7,
"embedding": [10.29041806, 14.33088073, 13.00557506],
},
],
)
)
# >>> result
# [{'evol_instruction_score': 0.5, 'evol_response_score': 0.5, 'embedding': [-8.12729941, -5.24642847, -6.34003029], 'deita_score': 0.25, 'deita_score_computed_with': ['evol_instruction_score', 'evol_response_score'], 'nearest_neighbor_distance': 1.9042812683723933}]
引文
@misc{liu2024makesgooddataalignment,
title={What Makes Good Data for Alignment? A Comprehensive Study of Automatic Data Selection in Instruction Tuning},
author={Wei Liu and Weihao Zeng and Keqing He and Yong Jiang and Junxian He},
year={2024},
eprint={2312.15685},
archivePrefix={arXiv},
primaryClass={cs.CL},
url={https://arxiv.org/abs/2312.15685},
}
源代码位于 src/distilabel/steps/deita.py
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 |
|
process(inputs)
¶
根据 DEITA 分数和 embeddings 之间的余弦距离过滤数据集。
参数
名称 | 类型 | 描述 | 默认 |
---|---|---|---|
inputs
|
StepInput
|
输入数据。 |
required |
返回
类型 | 描述 |
---|---|
StepOutput
|
过滤后的数据集。 |
源代码位于 src/distilabel/steps/deita.py
_compute_deita_score(inputs)
¶
计算每个 instruction-response 对的 DEITA 分数。 DEITA 分数是 instruction 分数和 response 分数的乘积。
参数
名称 | 类型 | 描述 | 默认 |
---|---|---|---|
inputs
|
StepInput
|
输入数据。 |
required |
返回
类型 | 描述 |
---|---|
StepInput
|
计算了 DEITA 分数的输入数据。 |
源代码位于 src/distilabel/steps/deita.py
_compute_nearest_neighbor(inputs)
¶
计算 instruction-response 对的 embeddings 与最近邻居之间的余弦距离。
参数
名称 | 类型 | 描述 | 默认 |
---|---|---|---|
inputs
|
StepInput
|
输入数据。 |
required |
返回
类型 | 描述 |
---|---|
StepInput
|
计算了余弦距离的输入数据。 |
源代码位于 src/distilabel/steps/deita.py
_normalize_embeddings(embeddings)
¶
归一化 embeddings。
参数
名称 | 类型 | 描述 | 默认 |
---|---|---|---|
embeddings
|
ndarray
|
要归一化的 embeddings。 |
required |
返回
类型 | 描述 |
---|---|
ndarray
|
归一化后的 embeddings。 |
源代码位于 src/distilabel/steps/deita.py
_cosine_distance(embeddings)
¶
计算 embeddings 之间的余弦距离。
参数
名称 | 类型 | 描述 | 默认 |
---|---|---|---|
embeddings
|
array
|
embeddings。 |
required |
返回
类型 | 描述 |
---|---|
array
|
embeddings 之间的余弦距离。 |
源代码位于 src/distilabel/steps/deita.py
_manhattan_distance(embeddings)
¶
计算 embeddings 之间的曼哈顿距离。
参数
名称 | 类型 | 描述 | 默认 |
---|---|---|---|
embeddings
|
array
|
embeddings。 |
required |
返回
类型 | 描述 |
---|---|
array
|
embeddings 之间的曼哈顿距离。 |
源代码位于 src/distilabel/steps/deita.py
EmbeddingGeneration
¶
Bases: Step
使用 Embeddings
模型生成 embeddings。
EmbeddingGeneration
是一个 Step
,它使用 Embeddings
模型为提供的输入文本生成句子 embeddings。
属性
名称 | 类型 | 描述 |
---|---|---|
embeddings |
Embeddings
|
用于生成句子 embeddings 的 |
输入列
- text (
str
): 要为其生成句子 embedding 的文本。
输出列
- embedding (
List[Union[float, int]]
): 生成的句子 embedding。
类别
- embedding
示例
使用 Sentence Transformers 生成句子 embeddings
from distilabel.models import SentenceTransformerEmbeddings
from distilabel.steps import EmbeddingGeneration
embedding_generation = EmbeddingGeneration(
embeddings=SentenceTransformerEmbeddings(
model="mixedbread-ai/mxbai-embed-large-v1",
)
)
embedding_generation.load()
result = next(embedding_generation.process([{"text": "Hello, how are you?"}]))
# [{'text': 'Hello, how are you?', 'embedding': [0.06209656596183777, -0.015797119587659836, ...]}]
源代码位于 src/distilabel/steps/embeddings/embedding_generation.py
FaissNearestNeighbour
¶
Bases: GlobalStep
创建 faiss
索引以获取最近邻居。
FaissNearestNeighbour
是一个 GlobalStep
,它使用 Hugging Face datasets
库集成创建 faiss
索引,然后获取最近邻居以及每个输入行的最近邻居的分数或距离。
属性
名称 | 类型 | 描述 |
---|---|---|
device |
Optional[RuntimeParameter[Union[int, List[int]]]]
|
要使用的 CUDA 设备 ID 或 ID 列表。 如果为负整数,它将使用所有可用的 GPU。 默认为 |
string_factory |
Optional[RuntimeParameter[str]]
|
用于构建 |
metric_type |
Optional[RuntimeParameter[int]]
|
用于测量点之间距离的度量。 这是一个整数,推荐的传递方式是导入 |
k |
Optional[RuntimeParameter[int]]
|
要为每个输入行搜索的最近邻居的数量。 默认为 |
search_batch_size |
Optional[RuntimeParameter[int]]
|
搜索批次中包含的行数。 可以调整该值以最大化资源使用率或避免 OOM 问题。 默认为 |
train_size |
Optional[RuntimeParameter[int]]
|
如果索引需要训练步骤,则指定将使用多少向量来训练索引。 |
运行时参数
device
: 要使用的 CUDA 设备 ID 或 ID 列表。 如果为负整数,它将使用所有可用的 GPU。 默认为None
。string_factory
: 用于构建faiss
索引的工厂名称。 可用的字符串工厂可以在此处查看:https://github.com/facebookresearch/faiss/wiki/Faiss-indexes。 默认为None
。metric_type
: 用于测量点之间距离的度量。 这是一个整数,推荐的传递方式是导入faiss
,然后传递faiss.METRIC_x
变量之一。 默认为None
。k
: 要为每个输入行搜索的最近邻居的数量。 默认为1
。search_batch_size
: 搜索批次中包含的行数。 可以调整该值以最大化资源使用率或避免 OOM 问题。 默认为50
。train_size
: 如果索引需要训练步骤,则指定将使用多少向量来训练索引。
输入列
- embedding (
List[Union[float, int]]
): 句子 embedding。
输出列
- nn_indices (
List[int]
): 包含行输入中k
个最近邻居索引的列表。 - nn_scores (
List[float]
): 包含到输入中每个k
个最近邻居的分数或距离的列表。
类别
- embedding
参考文献
示例
生成 embeddings 并获取最近邻居
from distilabel.models import SentenceTransformerEmbeddings
from distilabel.pipeline import Pipeline
from distilabel.steps import EmbeddingGeneration, FaissNearestNeighbour, LoadDataFromHub
with Pipeline(name="hello") as pipeline:
load_data = LoadDataFromHub(output_mappings={"prompt": "text"})
embeddings = EmbeddingGeneration(
embeddings=SentenceTransformerEmbeddings(
model="mixedbread-ai/mxbai-embed-large-v1"
)
)
nearest_neighbours = FaissNearestNeighbour()
load_data >> embeddings >> nearest_neighbours
if __name__ == "__main__":
distiset = pipeline.run(
parameters={
load_data.name: {
"repo_id": "distilabel-internal-testing/instruction-dataset-mini",
"split": "test",
},
},
use_cache=False,
)
引文
@misc{douze2024faisslibrary,
title={The Faiss library},
author={Matthijs Douze and Alexandr Guzhva and Chengqi Deng and Jeff Johnson and Gergely Szilvasy and Pierre-Emmanuel Mazaré and Maria Lomeli and Lucas Hosseini and Hervé Jégou},
year={2024},
eprint={2401.08281},
archivePrefix={arXiv},
primaryClass={cs.LG},
url={https://arxiv.org/abs/2401.08281},
}
源代码位于 src/distilabel/steps/embeddings/nearest_neighbour.py
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 |
|
_build_index(inputs)
¶
使用 datasets
集成构建 faiss
索引。
参数
名称 | 类型 | 描述 | 默认 |
---|---|---|---|
inputs
|
List[Dict[str, Any]]
|
字典列表。 |
required |
返回
类型 | 描述 |
---|---|
Dataset
|
构建的带有 |
源代码位于 src/distilabel/steps/embeddings/nearest_neighbour.py
_save_index(dataset)
¶
将生成的 Faiss 索引另存为 step 的工件。
参数
名称 | 类型 | 描述 | 默认 |
---|---|---|---|
dataset
|
Dataset
|
构建了 |
required |
源代码位于 src/distilabel/steps/embeddings/nearest_neighbour.py
_search(dataset)
¶
搜索数据集中每行的前 k
个最近邻居。
参数
名称 | 类型 | 描述 | 默认 |
---|---|---|---|
dataset
|
Dataset
|
构建了 |
required |
返回
类型 | 描述 |
---|---|
Dataset
|
更新后的数据集,其中包含每行的前 |
Dataset
|
以及分数或距离。 |
源代码位于 src/distilabel/steps/embeddings/nearest_neighbour.py
EmbeddingDedup
¶
Bases: GlobalStep
使用 embeddings 去重文本。
EmbeddingDedup
是一个 Step,它使用 embeddings 来检测数据集中的近似重复项,以比较文本之间的相似性。 此 step 的典型工作流程包括拥有一个预先计算了 embeddings 的数据集,然后(可能使用 FaissNearestNeighbour
)使用 nn_indices
和 nn_scores
来确定重复的文本。
属性
名称 | 类型 | 描述 |
---|---|---|
threshold |
Optional[RuntimeParameter[float]]
|
将 2 个示例视为重复项的阈值。 它取决于用于生成 embeddings 的索引类型。 例如,如果 embeddings 是使用余弦相似度生成的,则阈值 |
运行时参数
threshold
: 将 2 个示例视为重复项的阈值。
输入列
- nn_indices (
List[int]
): 包含行输入中k
个最近邻居索引的列表。 - nn_scores (
List[float]
): 包含到输入中每个k
个最近邻居的分数或距离的列表。
输出列
- keep_row_after_embedding_filtering (
bool
): 布尔值,指示 piecetext
是否不是重复项,即应保留此文本。
类别
- filtering
示例
Deduplicate a list of texts using embedding information:
```python
from distilabel.pipeline import Pipeline
from distilabel.steps import EmbeddingDedup
from distilabel.steps import LoadDataFromDicts
with Pipeline() as pipeline:
data = LoadDataFromDicts(
data=[
{
"persona": "A chemistry student or academic researcher interested in inorganic or physical chemistry, likely at an advanced undergraduate or graduate level, studying acid-base interactions and chemical bonding.",
"embedding": [
0.018477669046149742,
-0.03748236608841726,
0.001919870620352492,
0.024918478063770535,
0.02348063521315178,
0.0038251285566308375,
-0.01723884983037716,
0.02881971942372201,
],
"nn_indices": [0, 1],
"nn_scores": [
0.9164746999740601,
0.782106876373291,
],
},
{
"persona": "A music teacher or instructor focused on theoretical and practical piano lessons.",
"embedding": [
-0.0023464179614082125,
-0.07325472251663565,
-0.06058678419516501,
-0.02100326928586996,
-0.013462744792362657,
0.027368447064244242,
-0.003916070100455717,
0.01243614518480423,
],
"nn_indices": [0, 2],
"nn_scores": [
0.7552462220191956,
0.7261884808540344,
],
},
{
"persona": "A classical guitar teacher or instructor, likely with experience teaching beginners, who focuses on breaking down complex music notation into understandable steps for their students.",
"embedding": [
-0.01630817942328242,
-0.023760151552345232,
-0.014249650090627883,
-0.005713686451446624,
-0.016033059279131567,
0.0071440908501058786,
-0.05691099643425161,
0.01597412704817784,
],
"nn_indices": [1, 2],
"nn_scores": [
0.8107735514640808,
0.7172299027442932,
],
},
],
batch_size=batch_size,
)
# In general you should do something like this before the deduplication step, to obtain the
# `nn_indices` and `nn_scores`. In this case the embeddings are already normalized, so there's
# no need for it.
# nn = FaissNearestNeighbour(
# k=30,
# metric_type=faiss.METRIC_INNER_PRODUCT,
# search_batch_size=50,
# train_size=len(dataset), # The number of embeddings to use for training
# string_factory="IVF300_HNSW32,Flat" # To use an index (optional, maybe required for big datasets)
# )
# Read more about the `string_factory` here:
# https://github.com/facebookresearch/faiss/wiki/Guidelines-to-choose-an-index
embedding_dedup = EmbeddingDedup(
threshold=0.8,
input_batch_size=batch_size,
)
data >> embedding_dedup
if __name__ == "__main__":
distiset = pipeline.run(use_cache=False)
ds = distiset["default"]["train"]
# Filter out the duplicates
ds_dedup = ds.filter(lambda x: x["keep_row_after_embedding_filtering"])
```
源代码位于 src/distilabel/steps/filtering/embedding.py
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 |
|
MinHashDedup
¶
Bases: Step
使用 MinHash
和 MinHashLSH
去重文本。
MinHashDedup
是一个 Step,它检测数据集中的近似重复项。 该想法大致转化为以下步骤:1. 将文本标记化为单词或 n 元语法。 2. 为每个文本创建一个 MinHash
。 3. 将 MinHashes
存储在 MinHashLSH
中。 4. 检查 MinHash
是否已在 LSH
中,如果是,则它是重复项。
属性
名称 | 类型 | 描述 |
---|---|---|
num_perm |
int
|
要使用的排列数。 默认为 |
seed |
int
|
用于 MinHash 的种子。 默认为 |
tokenizer |
Literal['words', 'ngrams']
|
要使用的 tokenizer。 可用的有 |
n |
Optional[int]
|
要使用的 n 元语法的大小。 仅当 |
threshold |
float
|
将两个 MinHashes 视为重复项的阈值。 值越接近 0,检测到的重复项越多。 默认为 |
storage |
Literal['dict', 'disk']
|
用于 LSH 的存储。 可以是 |
输入列
- text (
str
): 要过滤的文本。
输出列
- keep_row_after_minhash_filtering (
bool
): 布尔值,指示 piecetext
是否不是重复项,即应保留此文本。
类别
- filtering
示例
Deduplicate a list of texts using MinHash and MinHashLSH:
```python
from distilabel.pipeline import Pipeline
from distilabel.steps import MinHashDedup
from distilabel.steps import LoadDataFromDicts
with Pipeline() as pipeline:
ds_size = 1000
batch_size = 500 # Bigger batch sizes work better for this step
data = LoadDataFromDicts(
data=[
{"text": "This is a test document."},
{"text": "This document is a test."},
{"text": "Test document for duplication."},
{"text": "Document for duplication test."},
{"text": "This is another unique document."},
]
* (ds_size // 5),
batch_size=batch_size,
)
minhash_dedup = MinHashDedup(
tokenizer="words",
threshold=0.9, # lower values will increase the number of duplicates
storage="dict", # or "disk" for bigger datasets
)
data >> minhash_dedup
if __name__ == "__main__":
distiset = pipeline.run(use_cache=False)
ds = distiset["default"]["train"]
# Filter out the duplicates
ds_dedup = ds.filter(lambda x: x["keep_row_after_minhash_filtering"])
```
源代码位于 src/distilabel/steps/filtering/minhash.py
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 |
|
ConversationTemplate
¶
Bases: Step
从 instruction 和 response 生成 conversation template。
输入列
- instruction (
str
): 要在 conversation 中使用的 instruction。 - response (
str
): 要在 conversation 中使用的 response。
输出列
- conversation (
ChatType
): conversation template。
类别
- format
- chat
- template
示例
从 instruction 和 response 创建 conversation
from distilabel.steps import ConversationTemplate
conv_template = ConversationTemplate()
conv_template.load()
result = next(
conv_template.process(
[
{
"instruction": "Hello",
"response": "Hi",
}
],
)
)
# >>> result
# [{'instruction': 'Hello', 'response': 'Hi', 'conversation': [{'role': 'user', 'content': 'Hello'}, {'role': 'assistant', 'content': 'Hi'}]}]
源代码位于 src/distilabel/steps/formatting/conversation.py
inputs
property
¶
instruction 和 response。
outputs
property
¶
conversation template。
process(inputs)
¶
从 instruction 和 response 生成 conversation template。
参数
名称 | 类型 | 描述 | 默认 |
---|---|---|---|
inputs
|
StepInput
|
输入数据。 |
required |
Yields
类型 | 描述 |
---|---|
StepOutput
|
带有 conversation template 的输入数据。 |
源代码位于 src/distilabel/steps/formatting/conversation.py
FormatChatGenerationDPO
¶
Bases: Step
格式化 Direct Preference Optimization (DPO) 的 ChatGeneration
和偏好任务的组合输出。
FormatChatGenerationDPO
是一个 Step
,用于格式化 ChatGeneration
任务与偏好 Task
的组合输出,例如生成 ratings
的任务(如 UltraFeedback
),遵循 axolotl
或 alignment-handbook
等框架的标准格式。这样,这些评分将被用于对现有生成结果进行排序,并基于 ratings
提供 chosen
和 rejected
生成结果。
注意
messages
列应至少包含一条来自用户的消息,generations
列应至少包含两个生成结果,ratings
列应包含与生成结果数量相同的评分。
输入列
- messages (
List[Dict[str, str]]
): 对话消息。 - generations (
List[str]
): 由LLM
生成的结果。 - generation_models (
List[str]
, 可选): 用于生成generations
的模型名称,仅当来自ChatGeneration
任务的模型名称被合并到名为此名称的单个列中时可用,否则将被忽略。 - ratings (
List[float]
): 每个generations
的评分,由偏好任务(如UltraFeedback
)生成。
输出列
- prompt (
str
): 用于使用LLM
生成generations
的用户消息。 - prompt_id (
str
):prompt
的SHA256
哈希值。 - chosen (
List[Dict[str, str]]
): 基于ratings
选择的chosen
生成结果。 - chosen_model (
str
, 可选): 用于生成chosen
生成结果的模型名称,如果generation_models
可用。 - chosen_rating (
float
):chosen
生成结果的评分。 - rejected (
List[Dict[str, str]]
): 基于ratings
拒绝的rejected
生成结果。 - rejected_model (
str
, 可选): 用于生成rejected
生成结果的模型名称,如果generation_models
可用。 - rejected_rating (
float
):rejected
生成结果的评分。
类别
- format
- chat-generation
- preference
- messages
- generations
示例
格式化您的数据集以进行 DPO 微调
from distilabel.steps import FormatChatGenerationDPO
format_dpo = FormatChatGenerationDPO()
format_dpo.load()
# NOTE: "generation_models" can be added optionally.
result = next(
format_dpo.process(
[
{
"messages": [{"role": "user", "content": "What's 2+2?"}],
"generations": ["4", "5", "6"],
"ratings": [1, 0, -1],
}
]
)
)
# >>> result
# [
# {
# 'messages': [{'role': 'user', 'content': "What's 2+2?"}],
# 'generations': ['4', '5', '6'],
# 'ratings': [1, 0, -1],
# 'prompt': "What's 2+2?",
# 'prompt_id': '7762ecf17ad41479767061a8f4a7bfa3b63d371672af5180872f9b82b4cd4e29',
# 'chosen': [{'role': 'user', 'content': "What's 2+2?"}, {'role': 'assistant', 'content': '4'}],
# 'chosen_rating': 1,
# 'rejected': [{'role': 'user', 'content': "What's 2+2?"}, {'role': 'assistant', 'content': '6'}],
# 'rejected_rating': -1
# }
# ]
源代码位于 src/distilabel/steps/formatting/dpo.py
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 |
|
inputs
property
¶
Step
所需的输入列表,在本例中为:messages
、generations
和 ratings
。
optional_inputs
property
¶
可选输入列表,Step
不是必需的,但在可用时使用,在本例中为:generation_models
。
outputs
property
¶
Step
生成的输出列表,包括:prompt
、prompt_id
、chosen
、chosen_model
、chosen_rating
、rejected
、rejected_model
、rejected_rating
。chosen_model
和 rejected_model
都是可选的,仅在 generation_models
可用时使用。
参考
- 格式灵感来自 https://hugging-face.cn/datasets/HuggingFaceH4/ultrachat_200k
process(*inputs)
¶
process
方法根据 DPO 格式标准格式化接收到的 StepInput
或 StepInput
列表。
参数
名称 | 类型 | 描述 | 默认 |
---|---|---|---|
*inputs
|
StepInput
|
要组合的 |
()
|
Yields
类型 | 描述 |
---|---|
StepOutput
|
一个 |
源代码位于 src/distilabel/steps/formatting/dpo.py
FormatTextGenerationDPO
¶
Bases: Step
格式化您的 LLM 输出以进行 Direct Preference Optimization (DPO)。
FormatTextGenerationDPO
是一个 Step
,用于格式化 TextGeneration
任务与偏好 Task
的组合输出,例如生成 ratings
的任务。这些评分将被用于对现有生成结果进行排序,并基于 ratings
提供 chosen
和 rejected
生成结果。使用此步骤转换 TextGeneration
和偏好任务(如 UltraFeedback
)的组合输出,遵循 axolotl
或 alignment-handbook
等框架的标准格式。
注意
generations
列应至少包含两个生成结果,ratings
列应包含与生成结果数量相同的评分。
输入列
- system_prompt (
str
, 可选): 在LLM
中用于生成generations
的系统提示(如果可用)。 - instruction (
str
): 用于使用LLM
生成generations
的指令。 - generations (
List[str]
): 由LLM
生成的结果。 - generation_models (
List[str]
, 可选): 用于生成generations
的模型名称,仅当来自TextGeneration
任务的模型名称被合并到名为此名称的单个列中时可用,否则将被忽略。 - ratings (
List[float]
): 每个generations
的评分,由偏好任务(如UltraFeedback
)生成。
输出列
- prompt (
str
): 用于使用LLM
生成generations
的指令。 - prompt_id (
str
):prompt
的SHA256
哈希值。 - chosen (
List[Dict[str, str]]
): 基于ratings
选择的chosen
生成结果。 - chosen_model (
str
, 可选): 用于生成chosen
生成结果的模型名称,如果generation_models
可用。 - chosen_rating (
float
):chosen
生成结果的评分。 - rejected (
List[Dict[str, str]]
): 基于ratings
拒绝的rejected
生成结果。 - rejected_model (
str
, 可选): 用于生成rejected
生成结果的模型名称,如果generation_models
可用。 - rejected_rating (
float
):rejected
生成结果的评分。
类别
- format
- text-generation
- preference
- instruction
- generations
示例
格式化您的数据集以进行 DPO 微调
from distilabel.steps import FormatTextGenerationDPO
format_dpo = FormatTextGenerationDPO()
format_dpo.load()
# NOTE: Both "system_prompt" and "generation_models" can be added optionally.
result = next(
format_dpo.process(
[
{
"instruction": "What's 2+2?",
"generations": ["4", "5", "6"],
"ratings": [1, 0, -1],
}
]
)
)
# >>> result
# [
# { 'instruction': "What's 2+2?",
# 'generations': ['4', '5', '6'],
# 'ratings': [1, 0, -1],
# 'prompt': "What's 2+2?",
# 'prompt_id': '7762ecf17ad41479767061a8f4a7bfa3b63d371672af5180872f9b82b4cd4e29',
# 'chosen': [{'role': 'user', 'content': "What's 2+2?"}, {'role': 'assistant', 'content': '4'}],
# 'chosen_rating': 1,
# 'rejected': [{'role': 'user', 'content': "What's 2+2?"}, {'role': 'assistant', 'content': '6'}],
# 'rejected_rating': -1
# }
# ]
源代码位于 src/distilabel/steps/formatting/dpo.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 |
|
inputs
property
¶
Step
所需的输入列表,在本例中为:instruction
、generations
和 ratings
。
optional_inputs
property
¶
可选输入列表,Step
不是必需的,但在可用时使用,在本例中为:system_prompt
和 generation_models
。
outputs
property
¶
Step
生成的输出列表,包括:prompt
、prompt_id
、chosen
、chosen_model
、chosen_rating
、rejected
、rejected_model
、rejected_rating
。chosen_model
和 rejected_model
都是可选的,仅在 generation_models
可用时使用。
参考
- 格式灵感来自 https://hugging-face.cn/datasets/HuggingFaceH4/ultrachat_200k
process(*inputs)
¶
process
方法根据 DPO 格式标准格式化接收到的 StepInput
或 StepInput
列表。
参数
名称 | 类型 | 描述 | 默认 |
---|---|---|---|
*inputs
|
StepInput
|
要组合的 |
()
|
Yields
类型 | 描述 |
---|---|
StepOutput
|
一个 |
源代码位于 src/distilabel/steps/formatting/dpo.py
FormatChatGenerationSFT
¶
Bases: Step
格式化 ChatGeneration
任务的输出以进行 Supervised Fine-Tuning (SFT)。
FormatChatGenerationSFT
是一个 Step
,用于格式化 ChatGeneration
任务的输出,以进行 Supervised Fine-Tuning (SFT),遵循 axolotl
或 alignment-handbook
等框架的标准格式。ChatGeneration
任务的输出被格式化为类聊天对话,其中 instruction
作为用户消息,generation
作为助手消息。可选地,如果 system_prompt
可用,它将被包含为对话中的第一条消息。
输入列
- system_prompt (
str
, 可选): 在LLM
中用于生成generation
的系统提示(如果可用)。 - instruction (
str
): 用于使用LLM
生成generation
的指令。 - generation (
str
): 由LLM
生成的结果。
输出列
- prompt (
str
): 用于使用LLM
生成generation
的指令。 - prompt_id (
str
):prompt
的SHA256
哈希值。 - messages (
List[Dict[str, str]]
): 类聊天对话,其中instruction
作为用户消息,generation
作为助手消息。
类别
- format
- chat-generation
- instruction
- generation
示例
格式化您的数据集以进行 SFT
from distilabel.steps import FormatChatGenerationSFT
format_sft = FormatChatGenerationSFT()
format_sft.load()
# NOTE: "system_prompt" can be added optionally.
result = next(
format_sft.process(
[
{
"messages": [{"role": "user", "content": "What's 2+2?"}],
"generation": "4"
}
]
)
)
# >>> result
# [
# {
# 'messages': [{'role': 'user', 'content': "What's 2+2?"}, {'role': 'assistant', 'content': '4'}],
# 'generation': '4',
# 'prompt': 'What's 2+2?',
# 'prompt_id': '7762ecf17ad41479767061a8f4a7bfa3b63d371672af5180872f9b82b4cd4e29',
# }
# ]
源代码位于 src/distilabel/steps/formatting/sft.py
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 |
|
inputs
property
¶
Step
所需的输入列表,在本例中为:instruction
和 generation
。
outputs
property
¶
Step
生成的输出列表,包括:prompt
、prompt_id
、messages
。
参考
- 格式灵感来自 https://hugging-face.cn/datasets/HuggingFaceH4/ultrachat_200k
process(*inputs)
¶
process
方法根据 SFT 格式标准格式化接收到的 StepInput
或 StepInput
列表。
参数
名称 | 类型 | 描述 | 默认 |
---|---|---|---|
*inputs
|
StepInput
|
要组合的 |
()
|
Yields
类型 | 描述 |
---|---|
StepOutput
|
一个 |
源代码位于 src/distilabel/steps/formatting/sft.py
FormatTextGenerationSFT
¶
Bases: Step
格式化 TextGeneration
任务的输出以进行 Supervised Fine-Tuning (SFT)。
FormatTextGenerationSFT
是一个 Step
,用于格式化 TextGeneration
任务的输出,以进行 Supervised Fine-Tuning (SFT),遵循 axolotl
或 alignment-handbook
等框架的标准格式。TextGeneration
任务的输出被格式化为类聊天对话,其中 instruction
作为用户消息,generation
作为助手消息。可选地,如果 system_prompt
可用,它将被包含为对话中的第一条消息。
输入列
- system_prompt (
str
, 可选): 在LLM
中用于生成generation
的系统提示(如果可用)。 - instruction (
str
): 用于使用LLM
生成generation
的指令。 - generation (
str
): 由LLM
生成的结果。
输出列
- prompt (
str
): 用于使用LLM
生成generation
的指令。 - prompt_id (
str
):prompt
的SHA256
哈希值。 - messages (
List[Dict[str, str]]
): 类聊天对话,其中instruction
作为用户消息,generation
作为助手消息。
类别
- format
- text-generation
- instruction
- generation
示例
格式化您的数据集以进行 SFT 微调
from distilabel.steps import FormatTextGenerationSFT
format_sft = FormatTextGenerationSFT()
format_sft.load()
# NOTE: "system_prompt" can be added optionally.
result = next(
format_sft.process(
[
{
"instruction": "What's 2+2?",
"generation": "4"
}
]
)
)
# >>> result
# [
# {
# 'instruction': 'What's 2+2?',
# 'generation': '4',
# 'prompt': 'What's 2+2?',
# 'prompt_id': '7762ecf17ad41479767061a8f4a7bfa3b63d371672af5180872f9b82b4cd4e29',
# 'messages': [{'role': 'user', 'content': "What's 2+2?"}, {'role': 'assistant', 'content': '4'}]
# }
# ]
源代码位于 src/distilabel/steps/formatting/sft.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 |
|
inputs
property
¶
Step
所需的输入列表,在本例中为:instruction
和 generation
。
optional_inputs
property
¶
可选输入列表,Step
不是必需的,但在可用时使用,在本例中为:system_prompt
。
outputs
property
¶
Step
生成的输出列表,包括:prompt
、prompt_id
、messages
。
参考
- 格式灵感来自 https://hugging-face.cn/datasets/HuggingFaceH4/ultrachat_200k
process(*inputs)
¶
process
方法根据 SFT 格式标准格式化接收到的 StepInput
或 StepInput
列表。
参数
名称 | 类型 | 描述 | 默认 |
---|---|---|---|
*inputs
|
StepInput
|
要组合的 |
()
|
Yields
类型 | 描述 |
---|---|
StepOutput
|
一个 |
源代码位于 src/distilabel/steps/formatting/sft.py
LoadDataFromDicts
¶
基类: GeneratorStep
从字典列表加载数据集。
GeneratorStep
从字典列表中加载数据集并批量生成。
属性
名称 | 类型 | 描述 |
---|---|---|
data |
List[Dict[str, Any]]
|
要加载数据的字典列表。 |
运行时参数
batch_size
: 处理数据时使用的批次大小。
输出列
- dynamic (基于在列表的第一个字典中找到的键): 数据集的列。
类别
- load
示例
从字典列表加载数据
from distilabel.steps import LoadDataFromDicts
loader = LoadDataFromDicts(
data=[{"instruction": "What are 2+2?"}] * 5,
batch_size=2
)
loader.load()
result = next(loader.process())
# >>> result
# ([{'instruction': 'What are 2+2?'}, {'instruction': 'What are 2+2?'}], False)
源代码位于 src/distilabel/steps/generators/data.py
outputs
property
¶
返回包含步骤将生成的列名称的字符串列表。
process(offset=0)
¶
从字典列表生成批次。
参数
名称 | 类型 | 描述 | 默认 |
---|---|---|---|
offset
|
int
|
开始生成的偏移量。默认为 |
0
|
Yields
类型 | 描述 |
---|---|
GeneratorStepOutput
|
从输入读取的 Python 字典列表(以批次形式传播) |
GeneratorStepOutput
|
以及指示产量批次是否为最后一个批次的标志。 |
源代码位于 src/distilabel/steps/generators/data.py
DataSampler
¶
基类: GeneratorStep
从数据集采样的步骤。
GeneratorStep
从数据集采样并批量生成。当您的 pipeline 可以受益于在提示中使用示例(例如作为少样本学习)时,此步骤非常有用,这些示例可以在每一行上更改。例如,您可以传递包含 N 个示例的字典列表,并从中生成 M 个样本(假设您有另一个加载数据的步骤,则此 M 应与该步骤中加载的数据大小相同)。size S 参数是每行生成的样本数,因此每个示例将包含 S 个示例以用作示例。
属性
名称 | 类型 | 描述 |
---|---|---|
data |
List[Dict[str, Any]]
|
要从中采样的字典列表。 |
size |
int
|
每个示例的样本数。例如,在少样本学习场景中,每个示例将生成的少样本示例的数量。默认为 2。 |
samples |
int
|
步骤总共将生成的示例数。如果与另一个加载器步骤一起使用,则应与加载器步骤中的样本数相同。默认为 100。 |
输出列
- dynamic (基于在列表的第一个字典中找到的键): 数据集的列。
类别
- load
示例
从字典列表采样数据
from distilabel.steps import DataSampler
sampler = DataSampler(
data=[{"sample": f"sample {i}"} for i in range(30)],
samples=10,
size=2,
batch_size=4
)
sampler.load()
result = next(sampler.process())
# >>> result
# ([{'sample': ['sample 7', 'sample 0']}, {'sample': ['sample 2', 'sample 21']}, {'sample': ['sample 17', 'sample 12']}, {'sample': ['sample 2', 'sample 14']}], False)
Pipeline,加载器和采样器组合在单个流中
from datasets import load_dataset
from distilabel.steps import LoadDataFromDicts, DataSampler
from distilabel.steps.tasks.apigen.utils import PrepareExamples
from distilabel.pipeline import Pipeline
ds = (
load_dataset("Salesforce/xlam-function-calling-60k", split="train")
.shuffle(seed=42)
.select(range(500))
.to_list()
)
data = [
{
"func_name": "final_velocity",
"func_desc": "Calculates the final velocity of an object given its initial velocity, acceleration, and time.",
},
{
"func_name": "permutation_count",
"func_desc": "Calculates the number of permutations of k elements from a set of n elements.",
},
{
"func_name": "getdivision",
"func_desc": "Divides two numbers by making an API call to a division service.",
},
]
with Pipeline(name="APIGenPipeline") as pipeline:
loader_seeds = LoadDataFromDicts(data=data)
sampler = DataSampler(
data=ds,
size=2,
samples=len(data),
batch_size=8,
)
prep_examples = PrepareExamples()
sampler >> prep_examples
(
[loader_seeds, prep_examples]
>> combine_steps
)
# Now we have a single stream of data with the loader and the sampler data
源代码位于 src/distilabel/steps/generators/data_sampler.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 |
|
process(offset=0)
¶
从字典列表生成批次。
参数
名称 | 类型 | 描述 | 默认 |
---|---|---|---|
offset
|
int
|
开始生成的偏移量。默认为 |
0
|
Yields
类型 | 描述 |
---|---|
GeneratorStepOutput
|
从输入读取的 Python 字典列表(以批次形式传播) |
GeneratorStepOutput
|
以及指示产量批次是否为最后一个批次的标志。 |
源代码位于 src/distilabel/steps/generators/data_sampler.py
RewardModelScore
¶
基类: Step
, CudaDevicePlacementMixin
使用奖励模型为响应分配分数。
RewardModelScore
是一个 Step
,它使用 transformers
加载的奖励模型 (RM),为针对指令生成的响应分配分数,或为多轮对话分配分数。
属性
名称 | 类型 | 描述 |
---|---|---|
model |
str
|
模型 Hugging Face Hub repo id 或包含模型权重和配置文件目录的路径。 |
revision |
str
|
如果 |
torch_dtype |
str
|
模型要使用的 torch dtype,例如 "float16"、"float32" 等。默认为 |
trust_remote_code |
bool
|
是否允许获取和执行从 Hub 中的存储库获取的远程代码。默认为 |
device_map |
Union[str, Dict[str, Any], None]
|
将模型的每一层映射到设备的字典,或类似 |
token |
Union[SecretStr, None]
|
将用于向 Hugging Face Hub 验证身份的 Hugging Face Hub 令牌。如果未提供,则将使用 |
truncation |
bool
|
是否在最大长度处截断序列。默认为 |
max_length |
Union[int, None]
|
用于填充或截断的最大长度。默认为 |
输入列
- instruction (
str
, 可选): 用于生成response
的指令。如果提供,则也必须提供response
。 - response (
str
, 可选): 针对instruction
生成的响应。如果提供,则也必须提供instruction
。 - conversation (
ChatType
, 可选): 多轮对话。如果未提供,则必须提供instruction
和response
列。
输出列
- score (
float
): 奖励模型为指令-响应对或对话给出的分数。
类别
- scorer
示例
为指令-响应对分配分数
from distilabel.steps import RewardModelScore
step = RewardModelScore(
model="RLHFlow/ArmoRM-Llama3-8B-v0.1", device_map="auto", trust_remote_code=True
)
step.load()
result = next(
step.process(
inputs=[
{
"instruction": "How much is 2+2?",
"response": "The output of 2+2 is 4",
},
{"instruction": "How much is 2+2?", "response": "4"},
]
)
)
# [
# {'instruction': 'How much is 2+2?', 'response': 'The output of 2+2 is 4', 'score': 0.11690367758274078},
# {'instruction': 'How much is 2+2?', 'response': '4', 'score': 0.10300665348768234}
# ]
为多轮对话分配分数
from distilabel.steps import RewardModelScore
step = RewardModelScore(
model="RLHFlow/ArmoRM-Llama3-8B-v0.1", device_map="auto", trust_remote_code=True
)
step.load()
result = next(
step.process(
inputs=[
{
"conversation": [
{"role": "user", "content": "How much is 2+2?"},
{"role": "assistant", "content": "The output of 2+2 is 4"},
],
},
{
"conversation": [
{"role": "user", "content": "How much is 2+2?"},
{"role": "assistant", "content": "4"},
],
},
]
)
)
# [
# {'conversation': [{'role': 'user', 'content': 'How much is 2+2?'}, {'role': 'assistant', 'content': 'The output of 2+2 is 4'}], 'score': 0.11690367758274078},
# {'conversation': [{'role': 'user', 'content': 'How much is 2+2?'}, {'role': 'assistant', 'content': '4'}], 'score': 0.10300665348768234}
# ]
源代码位于 src/distilabel/steps/reward_model.py
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 |
|
TruncateTextColumn
¶
Bases: Step
使用 tokenizer 或字符数截断行。
TruncateTextColumn
是一个 Step
,它根据最大长度截断行。如果提供了 tokenizer
,则将使用 tokenizer 截断行,并且 max_length
将用作最大 token 数;否则,它将用作最大字符数。当想要将行截断为特定长度,以避免模型中由于长度引起的后续错误时,TruncateTextColumn
步骤非常有用。
属性
名称 | 类型 | 描述 |
---|---|---|
column |
str
|
要截断的列。默认为 |
max_length |
int
|
用于截断的最大长度。如果给定 |
tokenizer |
Optional[str]
|
要使用的 tokenizer 的名称。如果提供,则将使用 tokenizer 截断行。默认为 |
输入列
- dynamic (由
column
属性确定): 要截断的列,默认为 "text"。
输出列
- dynamic (由
column
属性确定): 截断后的列。
类别
- text-manipulation
示例
将行截断为给定的 token 数
from distilabel.steps import TruncateTextColumn
trunc = TruncateTextColumn(
tokenizer="meta-llama/Meta-Llama-3.1-70B-Instruct",
max_length=4,
column="text"
)
trunc.load()
result = next(
trunc.process(
[
{"text": "This is a sample text that is longer than 10 characters"}
]
)
)
# result
# [{'text': 'This is a sample'}]
将行截断为给定的字符数
from distilabel.steps import TruncateTextColumn
trunc = TruncateTextColumn(max_length=10)
trunc.load()
result = next(
trunc.process(
[
{"text": "This is a sample text that is longer than 10 characters"}
]
)
)
# result
# [{'text': 'This is a '}]
源代码位于 src/distilabel/steps/truncate.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 |
|