---
title: "43 | 大规模语料清洗与合成蒸馏流水线研发：基于KubeRay与Data-Juicer的CPU与GPU异构混跑实践"
url: "https://johng.cn/ai/thousand-gpu-cluster/distributed-corpus-curation-and-synthetic-distillation-kuberay-data-juicer"
markdown_url: "https://johng.cn/ai/thousand-gpu-cluster/distributed-corpus-curation-and-synthetic-distillation-kuberay-data-juicer.md"
type: "doc"
section: "AI技术"
category: "AI技术 / 技术专栏 / AI Infra千卡集群实战 / 五、平台研发：训推一体平台架构设计与工程实现 / 5.2 数据处理平台研发"
column: "专栏：AI Infra 千卡集群实战"
published: "2026-12-06"
updated: "2026-12-06"
description: "整机GPU混跑正则分词与模型打分易致算力空转，单机脚本处理TB级语料更会频发内存溢出。基于KubeRay与Data-Juicer设计CPU与潮汐GPU异构反压管线、分布式去重与在线合成蒸馏，并落地Ubuntu 26.04实践。"
keywords: ["千卡集群实战", "大规模语料清洗", "KubeRay实践", "Ray Data流式处理", "Data-Juicer配方", "CPU与GPU异构混跑", "流式反压机制", "MinHash-LSH去重", "合成数据蒸馏", "Distilabel管线", "拒采样过滤", "潮汐算力复用", "分片断点续跑", "Megatron预分词", "Ubuntu 26.04实战"]
---

# 43 | 大规模语料清洗与合成蒸馏流水线研发：基于KubeRay与Data-Juicer的CPU与GPU异构混跑实践

## 海量语料处理的算力与内存瓶颈

![基于KubeRay与Data-Juicer的大规模语料异构清洗与合成蒸馏全景：剖析同构容器算力错配、全量解压OOM与潮汐抢占三大瓶颈，串联通用CPU池粗筛去重、Apache Arrow零拷贝反压管道与潮汐GPU常驻批打分，并落地离线vLLM拒采样与分片断点续跑](https://johng.cn/assets/images/image-8e2b7f9e50c93a0b0584dca4369ea23d.webp)

在[AI数据处理平台架构设计与核心功能研发](https://johng.cn/ai/thousand-gpu-cluster/ai-data-processing-platform-architecture-and-recipe-governance)中，我们确定了以`KubeRay + Data-Juicer + Distilabel`为核心的平台技术底座。一旦进入`TB`级预训练语料提纯与百万条级后训练合成蒸馏的真实生产环节，平台底层执行引擎立刻要直面三道棘手的系统工程瓶颈：

1. **串行同构容器内的`CPU / GPU`木桶效应**：一条典型的高质量语料提纯管线往往交替穿插`HTML/Markdown`清洗、长度与字符比过滤、`MinHash`签名去重（纯`CPU`密集）以及`MinerU`复杂版面解析、文本向量化、质量分类器打分（`GPU`密集）。若每个进程独占`1`张`GPU`从头串行跑到尾，在漫长的正则清洗与网络`I/O`阶段加速卡完全空转；反之若只用`CPU`硬跑视觉与打分模型，吞吐又会跌落两个数量级。
2. **全量物化加载引发节点`OOM`雪崩**：原始网页压缩包（`WARC / JSONL.zst`）或多模态图文包解压后体积常膨胀`3 ~ 5`倍；若框架一次性将数十`GB`分片全部读入宿主机内存再进入下一算子，极易触发`cgroups v2 OOM Killer`（`ExitCode 137`）导致整组分布式作业崩溃重来。
3. **夜间潮汐抢占下的长任务前功尽弃风险**：为降低数据处理成本，平台将`GPU`加速算子与离线合成蒸馏优先调度至**夜间潮汐可抢占队列**；当清晨在线推理早高峰触发`Volcano Reclaim`驱逐部分`GPU Worker`时，若管线缺乏分片级幂等提交（`Shard-Level Checkpointing`），跑了一整夜的数十万条合成样本便会付诸东流。

## CPU与GPU异构流式反压管线设计

为彻底拆解算力耦合与内存爆炸，平台基于**`Ray Data`基于`Apache Arrow`的流式执行引擎（`Streaming Execution`）**结合`Data-Juicer`的`RayExecutor`，将单一作业物理拆分为配比独立的**高密`CPU WorkerGroup`**与**弹性`GPU WorkerGroup`**，通过有界内存块队列实现流水线并行与自动反压（`Backpressure`）：

```mermaid
%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#FFFFFF", "primaryBorderColor": "#2563EB", "primaryTextColor": "#0F172A", "lineColor": "#475569", "edgeLabelBackground": "#FFFFFF", "clusterBkg": "#F8FAFC", "clusterBorder": "#CBD5E1", "fontFamily": "PingFang SC, Hiragino Sans GB, Inter, Microsoft YaHei, sans-serif"}, "flowchart": {"curve": "basis", "wrappingWidth": 340, "nodeSpacing": 22, "rankSpacing": 54, "padding": 18, "subGraphTitleMargin": {"top": 12, "bottom": 18}}}}%%
flowchart TB
    subgraph TierCPU ["<span style='white-space:nowrap'><b>上层：通用高密 CPU 池流式接入、算子融合粗筛与全局去重（先行剥离 50%~70% 噪声废料）</b></span>"]
        direction LR
        Src["<b>① XSKY XEOS 分片读取</b><br/>自适应 64~128MB 块切分<br/>自动跳过已提交 .done 分片"]
        C1["<b>② CPU Task 算子融合粗筛</b><br/>HTML/Unicode 修复 · 长度/字符比过滤<br/>单核内存流水线一次遍历"]
        DD["<b>③ 分布式 MinHash-LSH 去重</b><br/>128 维签名波段分桶 Shuffle<br/>并查集连通分量裁剪近似重复"]
        Src ==>|"<span style='white-space:nowrap'>Arrow 流式块</span>"| C1 ==>|"<span style='white-space:nowrap'>哈希桶路由</span>"| DD
    end

    subgraph TierGPU ["<span style='white-space:nowrap'><b>下层：潮汐可抢占 GPU Actor 池精排脱敏与不可变分片落盘（常驻显存满载批推理）</b></span>"]
        direction LR
        G1["<b>④ 潮汐 GPU Actor 池</b><br/>MinerU 版面公式解析 · 质量/毒性打分<br/>权重单次加载 · Batch=256 饱和推理"]
        Gate["<b>⑤ 隐私脱敏与训练打包</b><br/>Presidio 敏感实体掩码 · 基准防污染<br/>预分词编译 Parquet / binidx"]
        Sink["<b>⑥ 原子落盘与资产交接</b><br/>写出 1GB 规整分片与 .done 标记<br/>回调 asset 模块定稿 Ready 快照"]
        G1 ==>|"<span style='white-space:nowrap'>高分净料流</span>"| Gate ==>|"<span style='white-space:nowrap'>并发刷盘</span>"| Sink
    end

    TierCPU ==>|"<span style='white-space:nowrap'>Ray Object Store 有界队列流式反压（防节点 OOM） · 仅高潜净料送入 GPU</span>"| TierGPU

    classDef io fill:#FFFFFF,stroke:#64748B,stroke-width:1.5px,color:#0F172A;
    classDef cpu fill:#FFFFFF,stroke:#2563EB,stroke-width:1.5px,color:#0F172A;
    classDef dedup fill:#FFFFFF,stroke:#0D9488,stroke-width:1.5px,color:#0F172A;
    classDef gpu fill:#FFFFFF,stroke:#D97706,stroke-width:1.5px,color:#0F172A;
    class Src,Sink io;
    class C1 cpu;
    class DD,Gate dedup;
    class G1 gpu;

    style TierCPU fill:#EFF6FF,stroke:#93C5FD,stroke-width:1.5px,color:#1E3A8A;
    style TierGPU fill:#FFFBEB,stroke:#FCD34D,stroke-width:1.5px,color:#92400E;
```

这套异构流式架构蕴含四项关键性能优化设计：

1. **“先粗筛去重、后上卡精评”漏斗铁律**：控制面配方编译器会自动重排或提示用户将低开销规则过滤（特殊字符比、短文本剔除、`FastText`语种识别）与`MinHash`去重前置到纯`CPU`阶段，先滤除`50% ~ 70%`的低质与重复冗余网页，仅让高潜净料流入昂贵的`GPU Actor`执行精排打分或视觉解析，直接节省过半`GPU`卡时。
2. **`Task`与常驻`Actor Pool`分工解耦**：纯`CPU`无状态算子编译为轻量级`Ray Task`并开启**连续算子融合（`Operator Fusion`）**，在单核内存内一次遍历完成十余项正则清洗；而需要加载数`GB`模型权重的打分器或`MinerU`解析器则封装为有状态**`Ray Actor Pool`**——模型权重仅在`Actor`初始化时加载一次常驻显存，持续拉取上游凑齐的`Arrow`微批次（如`batch_size: 256`）跑满`Tensor Core`吞吐。
3. **自适应分片切分与流式内存水位反压**：针对输入桶中“少量百`GB`巨型压缩包与海量`KB`级碎文件并存”的问题，启用自适应块切分（将单块控制在`64 ~ 128 MiB`），同时限制`Ray Object Store`最大在途内存占比；一旦下游`GPU Actor`消费变慢，上游`S3`读取`Task`自动暂停拉取，从根源上杜绝宿主机内存堆积`OOM`。
4. **分布式`MinHash-LSH`桶路由去重原理**：单机哈希表装不下十亿文档指纹。`Data-Juicer`的`ray_document_deduplicator`先在各`CPU`节点并行提取文本`N-gram`生成`128`个`MinHash`签名并切分为`b`个波段（`Band`，如`16 Bands × 8 Rows`），以`(band_id, band_hash)`作为归约键将潜在相似文档哈希路由至同一归约分片，最后通过分布式并查集（`Union-Find`）裁剪近似重复连通图，在纯`CPU`池上即可数小时洗完数`TB`语料。

| 流水线阶段 | 承载算力形态 | 典型代表算子 | 关键调优护栏 |
| :---: | :--- | :--- | :--- |
| **文档解析（复杂版面）** | 潮汐/切分`GPU Actor` | `MinerU`（版面检测 + 公式`LaTeX` + 表格还原） | 按页拆批并发，单`Actor`申请`1/2`卡或整卡避免显存争抢 |
| **规则清洗与启发式过滤** | 通用`CPU Task` | `clean_html`、`text_length_filter`、`alphanumeric_filter`、`perplexity_filter (KenLM)` | 开启算子融合减少`Arrow`反序列化；`CPU`与内存配比建议`1 Core : 4 GiB` |
| **跨库全局模糊去重** | 通用`CPU Shuffle` | `ray_document_deduplicator`（`MinHash-LSH`） | `Jaccard`阈值常取`0.7 ~ 0.8`；确保节点`/tmp`或本地`NVMe`溢出盘空间充足 |
| **模型精排与隐私脱敏** | `GPU Actor` + `CPU` | 领域质量分类器、安全毒性模型、`presidio_pii` | 固定推理`batch_size`压满算力；`PII`支持正则预筛缩小`NER`扫描范围 |
| **预分词与训练打包** | 通用`CPU Task` | `HuggingFace Tokenizer` → `Parquet`或`Megatron .bin/.idx` | 拼接文档注入`<eos>`分隔符，输出固定`1 ~ 2 GB`分片消除训练期小文件风暴 |

## 后训练在线合成蒸馏与拒采样设计

![分布式MinHash-LSH近似去重原理与后训练确定性拒采样断点机制：左侧拆解十亿文档Shingling切片、128维MinHash签名、波段分桶Shuffle路由与分布式并查集裁剪四步流水线，右侧展示潮汐离线vLLM配合无网Python沙箱判题拒采样及5000条分片幂等断点续跑机制](https://johng.cn/assets/images/image-1-e3f9425141859ca320d023db9499aefb.webp)

进入监督微调（`SFT`）与强化学习后训练（`GRPO / DPO`）阶段，数据处理平台的重心转向**用强模型算力换取高纯度推理轨迹**。平台集成`Distilabel`连接潮汐池内的无状态批量推理引擎（`vLLM / SGLang`），构建**“生成 → 校验（`Verifier`） → 拒采样（`Rejection Sampling`） → 分片落盘”**闭环流水线：

```mermaid
%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#FFFFFF", "primaryBorderColor": "#2563EB", "primaryTextColor": "#0F172A", "lineColor": "#475569", "edgeLabelBackground": "#FFFFFF", "clusterBkg": "#F8FAFC", "clusterBorder": "#CBD5E1", "fontFamily": "PingFang SC, Hiragino Sans GB, Inter, Microsoft YaHei, sans-serif"}, "flowchart": {"curve": "basis", "wrappingWidth": 380, "nodeSpacing": 24, "rankSpacing": 52, "padding": 18, "subGraphTitleMargin": {"top": 12, "bottom": 18}}}}%%
flowchart TB
    subgraph SynthGen ["<span style='white-space:nowrap'><b>阶段一：分片断点过滤与夜间潮汐池离线批推理采样（零冲击白昼线上网关）</b></span>"]
        direction LR
        Chunk["<b>① 种子集分片与断点扫描</b><br/>按 5,000 条切分固定 Input Chunk<br/>扫描 _committed 跳过已完成 .done 块"]
        Teacher["<b>② 潮汐离线 vLLM 并发蒸馏</b><br/>Distilabel 演化扩增复杂约束指令<br/>Best-of-N 高吞吐批量生成候选思维链"]
        Chunk ==>|"<span style='white-space:nowrap'>仅派发未完成分片</span>"| Teacher
    end

    subgraph SynthVerify ["<span style='white-space:nowrap'><b>阶段二：确定性沙箱校验拒采样与分片级幂等提交（容忍 Volcano 潮汐抢占）</b></span>"]
        direction LR
        Verify["<b>③ 确定性沙箱判题与拒采样</b><br/>无网 Python 单测 / 符号判题器核验<br/>自动配对正确 Chosen 与失败 Rejected"]
        Commit["<b>④ 幂等原子落盘与资产入库</b><br/>先写 Parquet 分片再落盘 .done 标记<br/>全量完成后经质量门禁交接 asset 模块"]
        Verify ==>|"<span style='white-space:nowrap'>高纯度 SFT / DPO 样本</span>"| Commit
    end

    SynthGen ==>|"<span style='white-space:nowrap'>输出 N 条候选推理轨迹与待核验答案</span>"| SynthVerify

    classDef s1 fill:#FFFFFF,stroke:#64748B,stroke-width:1.5px,color:#0F172A;
    classDef s2 fill:#FFFFFF,stroke:#D97706,stroke-width:1.5px,color:#0F172A;
    classDef s3 fill:#FFFFFF,stroke:#059669,stroke-width:1.5px,color:#0F172A;
    classDef s4 fill:#FFFFFF,stroke:#2563EB,stroke-width:1.5px,color:#0F172A;
    class Chunk s1;
    class Teacher s2;
    class Verify s3;
    class Commit s4;
    style SynthGen fill:#FFFBEB,stroke:#FCD34D,stroke-width:1.5px,color:#92400E;
    style SynthVerify fill:#ECFDF5,stroke:#6EE7B7,stroke-width:1.5px,color:#065F46;
```

1. **走离线批推理池而非挤占线上实时`AI`网关**：几十万条种子题目的`Best-of-8`并发采样会产生极高的持续`TPM`吞吐，但对首字延迟（`TTFT`）毫无要求。因此，平台`dataops`模块默认在夜间潮汐队列单独拉起开启高吞吐模式的**专用离线`vLLM`合成`Worker`组**（或通过网关最低优先级后台配额路由），确保绝不冲击白昼线上业务`SLA`。
2. **确定性沙箱校验替代纯主观模型自评**：针对代码生成、数学推演与`JSON`工具调用等可验证领域（`Verifiable Rewards`），流水线在教师模型吐出候选思维链与答案后，立即调用轻量无网`Python`执行沙箱或符号判题器核验结果正确性——仅保留推演过程闭合且执行全过的轨迹作为`SFT`正样本，或将同一题目下的通过轨迹与报错轨迹自动配对为高对比度`DPO`偏好对。
3. **输入分块签名与断点无损续跑**：面对潮汐队列随时可能发生的节点回收，平台将原始种子集预先切分为固定`5,000`条一个的输入分片（`Input Chunk`）。每完成一个分片的清洗或蒸馏，`Worker`先写出临时文件再原子提交`<chunk-hash>.parquet`与状态清单；作业被抢占重调度或扩缩容后，启动器扫描输出前缀自动跳过已提交分片，实现零重复算力损耗的增量续跑。

## Ubuntu 26.04环境异构清洗与蒸馏实践

### KubeRay联动Volcano异构清洗作业清单

在已部署`KubeRay v1.5.1`与`Volcano v1.15+`的`Ubuntu 26.04 LTS`集群中，平台`dataops`模块渲染下发的**“高密`CPU`清洗去重池 + 潮汐可抢占`GPU`质量精排池”**异构`RayJob`生产参考配置如下：

```yaml
# rayjob-hetero-data-juicer.yaml —— 分离通用 CPU 池与潮汐可抢占 GPU 池的 Data-Juicer 语料提纯作业
apiVersion: ray.io/v1
kind: RayJob
metadata:
  name: dj-pretrain-curation-v1
  namespace: ws-llm-dataops
  labels:
    volcano.sh/queue-name: tidal-batch-pool
spec:
  shutdownAfterJobFinishes: true
  ttlSecondsAfterFinished: 3600
  entrypoint: >
    python3 /opt/platform-dataops/run_curation_with_ckpt.py
    --config /etc/dj-recipe/recipe.yaml
    --checkpoint-uri s3://ai-landing/checkpoints/dj-pretrain-curation-v1/
  rayClusterSpec:
    rayVersion: "2.43.0"
    enableInTreeAutoscaling: true
    headGroupSpec:
      rayStartParams:
        num-cpus: "0" # Head 节点仅负责 GCS 协调与驱动编排，不混跑重计算防止 OOM
        dashboard-host: "0.0.0.0"
      template:
        spec:
          securityContext:
            runAsNonRoot: true
            runAsUser: 10001
            runAsGroup: 10001
          containers:
            - name: ray-head
              image: harbor.ai.internal/dataops/data-juicer-ray:v1.4-ubuntu26.04@sha256:8f41c2...
              resources:
                requests:
                  cpu: "8"
                  memory: "32Gi"
                limits:
                  cpu: "8"
                  memory: "32Gi"
    workerGroupSpecs:
      # 角色组 1：高密通用 CPU 池 —— 承载 HTML 清洗、启发式粗筛、分布式 MinHash 去重与分词
      - groupName: cpu-clean-dedup-pool
        replicas: 8
        minReplicas: 4
        maxReplicas: 16
        rayStartParams: {}
        template:
          spec:
            nodeSelector:
              platform.ai/node-pool: "general-cpu"
            volumes:
              - name: dshm
                emptyDir:
                  medium: Memory
                  sizeLimit: 64Gi # 支撑 Apache Arrow 零拷贝列式共享内存块
              - name: recipe-vol
                configMap:
                  name: dj-pretrain-recipe-v1
            containers:
              - name: ray-cpu-worker
                image: harbor.ai.internal/dataops/data-juicer-ray:v1.4-ubuntu26.04@sha256:8f41c2...
                volumeMounts:
                  - name: dshm
                    mountPath: /dev/shm
                  - name: recipe-vol
                    mountPath: /etc/dj-recipe
                resources:
                  requests:
                    cpu: "64"
                    memory: "256Gi"
                  limits:
                    cpu: "64"
                    memory: "256Gi"
      # 角色组 2：潮汐弹性 GPU 池 —— 仅承载质量分类模型批打分与向量去重，容忍波峰抢占缩容
      - groupName: gpu-quality-scorer-pool
        replicas: 2
        minReplicas: 1
        maxReplicas: 4
        rayStartParams: {}
        template:
          spec:
            tolerations:
              - key: "platform.ai/pool-type"
                operator: "Equal"
                value: "hybrid-reclaimable"
                effect: "NoSchedule"
            volumes:
              - name: dshm
                emptyDir:
                  medium: Memory
                  sizeLimit: 32Gi
            containers:
              - name: ray-gpu-worker
                image: harbor.ai.internal/dataops/data-juicer-ray:v1.4-ubuntu26.04@sha256:8f41c2...
                volumeMounts:
                  - name: dshm
                    mountPath: /dev/shm
                resources:
                  requests:
                    cpu: "16"
                    memory: "64Gi"
                    nvidia.com/gpu: "2"
                  limits:
                    cpu: "16"
                    memory: "64Gi"
                    nvidia.com/gpu: "2"
```

配套挂载进容器的声明式`Data-Juicer`配方配置（`recipe.yaml`）遵循“先`CPU`粗筛去重、后`GPU`质量过滤与隐私脱敏”顺序：

```yaml
# recipe.yaml —— 面向分布式 Ray 引擎的声明式语料提纯配方示例
project_name: "domain-pretrain-corpus-v1"
executor_type: "ray"
ray_address: "auto"
dataset_path: "s3://ai-landing/raw-corpus/tech-docs-2026/"
export_path: "s3://ai-assets-staging/datasets/domain-pretrain-v1/part.parquet"
export_shard_size: 1073741824 # 按 1 GiB 自动切分输出 Parquet 分片，契合下游流式训练加载

process:
  # 阶段一：CPU 算子融合粗筛与格式规范化
  - clean_html_mapper: {}
  - fix_unicode_mapper: {}
  - text_length_filter:
      min_len: 120
      max_len: 131072
  - alphanumeric_filter:
      min_ratio: 0.25
  - character_repetition_filter:
      rep_len: 10
      max_ratio: 0.2

  # 阶段二：跨节点分布式 MinHash-LSH 近似模糊去重（CPU Shuffle）
  - ray_document_deduplicator:
      lowercase: true
      ignore_non_character: true
      num_perm: 128
      jaccard_threshold: 0.75

  # 阶段三：GPU Actor 批处理质量评分与入库前 PII 隐私脱敏护栏
  - language_id_score_filter:
      lang: ["zh", "en"]
      min_score: 0.85
  - presidio_pii_redactor:
      entities: ["PHONE_NUMBER", "EMAIL_ADDRESS", "CN_ID_CARD", "CREDIT_CARD", "CRYPTO"]
      mask_token: "<REDACTED_PII>"
```

### 分片级断点续跑与合成拒采样核心参考代码

为确保在潮汐可抢占队列运行合成蒸馏或增量清洗时具备**中断无损恢复能力**，启动脚本按确定性分片清单过滤已完成输入块，并在每批样本通过校验后幂等提交结果分片：

```python
# /opt/platform-dataops/chunked_synth_pipeline_ref.py —— 分片幂等断点续跑与拒采样合成蒸馏参考示例
import hashlib
import json
import os
import pyarrow.parquet as pq
import ray
import s3fs

def shard_id_for_uri(uri: str) -> str:
    return hashlib.sha256(uri.encode("utf-8")).hexdigest()[:16]

@ray.remote(num_gpus=1)
class OfflineVLLMSynthesizer:
    """常驻潮汐 GPU Worker 的离线批量蒸馏 Actor，单次加载权重持续消费分片批次"""

    def __init__(self, model_local_path: str):
        from vllm import LLM, SamplingParams
        self.llm = LLM(model=model_local_path, tensor_parallel_size=1, gpu_memory_utilization=0.90)
        self.params = SamplingParams(n=4, temperature=0.7, max_tokens=2048)

    def synthesize_and_verify(self, batch: dict) -> dict:
        prompts = batch["seed_prompt"].tolist()
        outputs = self.llm.generate(prompts, self.params, use_tqdm=False)
        accepted_prompts, chosen_cot, rejected_cot = [], [], []

        for prompt, req_out, expected_ans in zip(prompts, outputs, batch["ground_truth"]):
            passed, failed = [], []
            for cand in req_out.outputs:
                text = cand.text.strip()
                # 确定性答案/规则校验：仅保留推演过程完整且最终结果严格吻合金标的轨迹
                if f"\\boxed{{{expected_ans}}}" in text and len(text) >= 64:
                    passed.append(text)
                else:
                    failed.append(text)
            if passed:
                accepted_prompts.append(prompt)
                chosen_cot.append(passed[0])
                rejected_cot.append(failed[0] if failed else "")

        return {
            "prompt": accepted_prompts,
            "chosen": chosen_cot,
            "rejected": rejected_cot,
        }

def run_incremental_shards(source_shards: list[str], out_prefix: str, model_path: str) -> None:
    fs = s3fs.S3FileSystem()
    pending_shards = [
        uri for uri in source_shards
        if not fs.exists(f"{out_prefix}/_committed/{shard_id_for_uri(uri)}.done")
    ]
    if not pending_shards:
        print("All shards already committed, skipping execution.")
        return

    for uri in pending_shards:
        sid = shard_id_for_uri(uri)
        ds = ray.data.read_parquet(uri)
        # 通过 ActorPoolStrategy 动态复用存活潮汐 GPU 副本，单副本被抢占时 Ray 自动重排剩余分片
        synthesized = ds.map_batches(
            OfflineVLLMSynthesizer,
            fn_constructor_args=(model_path,),
            batch_size=128,
            compute=ray.data.ActorPoolStrategy(min_size=1, max_size=4),
        )
        synthesized.write_parquet(f"{out_prefix}/data/shard-{sid}/")
        with fs.open(f"{out_prefix}/_committed/{sid}.done", "w") as f:
            f.write(json.dumps({"source": uri, "shard_id": sid}))
```

作业在`Ubuntu 26.04 LTS`终端提交后，研发人员可通过`platform-cli dataops logs`或内嵌`Ray Dashboard`实时观测各算子阶段的输入输出样本削减比、`Arrow`对象存储内存水位与每秒处理`Token`速率；待全部分片`.done`标记齐备并通过控制面质量合规门禁，即可一键定稿进入下游`5.3`节统一资产平台供千卡训练集群消费。

## 总结

落地大规模语料清洗与合成蒸馏流水线，本质上是一场算力特征精细匹配与流式容错设计：

1. **坚持异构解耦与漏斗前置裁剪**：利用`KubeRay + Data-Juicer`将高并发文本规则清洗与跨节点`MinHash-LSH`去重锁死在通用`CPU`池，先滤除过半废料后再通过`Apache Arrow`零拷贝流式反压管道送入常驻权重的`GPU Actor`池，彻底终结“昂贵显卡空等正则脚本”的资源错配。
2. **用潮汐离线批推理加分片幂等机制支撑数据飞轮**：将后训练合成蒸馏与拒采样工作负载引导至夜间潮汐可抢占队列，配合`ActorPool`弹性伸缩与输入分片`.done`幂等断点标记，在零冲击线上实时推理的前提下低成本量产高纯度对齐语料。

## 参考资料

- [Ray Data Documentation: Streaming Execution & Heterogeneous CPU/GPU Pipelines](https://docs.ray.io/en/latest/data/data-internals.html)
- [Data-Juicer Distributed Processing on Ray & Operator Zoo Reference](https://modelscope.github.io/data-juicer/)
- [Distilabel Documentation: Using Offline vLLM for Synthetic Data & Rejection Sampling](https://distilabel.argilla.io/)
