Custom distillation

Updated at:

Custom distillation allows you to define the processing logic for each row of data by using a Python processor, and to call a teacher model and an optional judge model to build ShareGPT, Alpaca, or DPO training data.

Overview

You can use the custom distillation template when scenario-based distillation templates cannot meet your specific requirements for data generation, transformation, or quality filtering. You need only to write a Python class that inherits from BaseProcessor and implements process(sample). The platform handles model access, task scheduling, concurrency, retries, timeouts, resumable runs, and dataset building.

Important

Custom distillation only builds the distillation data and does not include student model training. Calling the teacher model and the judge model incurs the corresponding model service fees.

The typical processing workflow is as follows:

  1. The platform reads the JSONL input data row by row.

  2. The processor validates the input, renders the prompt, and calls the teacher model or the judge model as needed.

  3. The processor returns one or more results, or actively filters out the current row.

  4. The builder builds the results into a dataset in the specified format, and the platform manages the delivery location in a unified manner.

Quick start: Build question-and-answer data for library customer service

Task goal: Prepare training data for an intelligent customer service assistant for a library. A small number of 'user question + standard reference material' pairs are already available, and you want the teacher model to rewrite the reference materials into natural, concise replies that suit the customer service scenario and finally generate an SFT dataset (in the OpenAI Chat messages format).

Distillation strategy: The teacher model is called only once for each valid input, and no judge model is required. The processor filters out empty inputs and discards truncated or overly short replies.

Step 1: Prepare the input data

On your local machine, create seeds.jsonl with the following content.

{"id":"faq-001","question":"How many books can I borrow at a time?","reference":"With each valid library card, you can borrow up to 5 books at the same time."}
{"id":"faq-002","question":"How long can I borrow a book?","reference":"The loan period for regular books is 30 days, counted from the day of borrowing."}
{"id":"faq-003","question":"Can I renew a book that is about to be due?","reference":"A book can be renewed 1 time before its due date, and the renewal period is 15 days; books that are reserved by other readers cannot be renewed."}
{"id":"faq-004","question":"What should I do if I lose my library card?","reference":"If you lose your library card, report the loss immediately at the library service desk or through the online service. The cardholder is responsible for the borrowing activity that occurs before the loss is reported."}
{"id":"faq-005","question":"Is the library open on weekends?","reference":"The library is open from Monday to Sunday, the opening hours are 9:00 to 21:00, and the schedule for statutory holidays is subject to notifications."}
{"id":"faq-006","question":"","reference":"This row is used to test empty question filtering, and the teacher model should not be called."}

The first 5 rows are used to generate training data, and row 6 is used to verify the active filtering logic.

Step 2: Write the processor

Create library_faq_processor.py and copy the following complete code.

from __future__ import annotations

from typing import Any, Dict, Optional

from easydistill.operators.custom import BaseProcessor


class LibraryFAQProcessor(BaseProcessor):
    """Generate customer service question-and-answer training data based on library reference materials."""

    prompts: Dict[str, str] = {
        "answer": (
            "You are a library customer service assistant. Answer user questions strictly based on the given reference material.\n"
            "Requirements:\n"
            "1. Use natural, friendly, and concise Chinese.\n"
            "2. Keep the key conditions and numbers in the reference material.\n"
            "3. Do not make up rules that are not in the reference material.\n"
            "4. Do not mention 'reference material', and give the answer directly.\n\n"
            "User question: {question}\n"
            "Reference material: {reference}"
        ),
    }

    def process(self, sample: Dict[str, Any]) -> Optional[Dict[str, Any]]:
        question = str(sample.get("question") or "").strip()
        reference = str(sample.get("reference") or "").strip()

        # Active filtering: not counted as a failure and does not consume a retry.
        if not question or not reference:
            return None

        prompt = self.render_prompt(
            "answer", question=question, reference=reference
        )
        result = self.generate(
            prompt=prompt,
            system="You are an accurate and concise library customer service assistant.",
            temperature=float(self.params.get("temperature", 0.3)),
            max_tokens=int(self.params.get("max_tokens", 512)),
        )

        if result.metadata.get("finish_reason") == "length":
            self.logger.warning("row %s: answer truncated", sample.get("id"))
            return None

        answer = result.response.strip()
        min_chars = int(self.params.get("min_answer_chars", 10))
        if len(answer) < min_chars:
            self.logger.warning("row %s: answer too short", sample.get("id"))
            return None

        return {
            "id": sample.get("id"),
            "messages": [
                {"role": "user", "content": question},
                {"role": "assistant", "content": answer},
            ],
        }

self.generate() is used to generate text. You only need to pass in the prompt, and the platform injects the model configuration based on the selection on the page.

Step 3: Configure and create a task

  1. Log on to the PAI console. In the left-side navigation pane, choose Model Application > Model Distillation (ModelDistill).

  2. Click Create task to go to the Distillation Template tab, or go directly to the Distillation Template tab.

  3. Select Custom distillation, and then click Use Template to go to the Create Distillation Task page.

  4. Complete the basic configurations, and then configure the key parameters on the distillation data building page as described in the following table.

    Parameter

    How to configure

    Teacher model

    For Source, select Token Service:

    • Select a currently available Teacher Model, such as qwen3.8-max.

    • Judge Model: leave this field empty. This example does not use a judge model.

    Dataset

    Upload and select seeds.jsonl.

    Custom Processor

    : upload and select library_faq_processor.py.

    Compute Resource

    Resource TypeSelect General Computing, Source select Public Resources, and in Job Resource select a suitable Instance Type, such as ecs.c6.large.

  5. Click Create, and then, in the billing reminder that appears, click OK. The page automatically redirects to the Basic Configuration page of the task details, where you can track the task status. Switch to Create Distillation Data Job to view task details, logs, and monitoring.

Step 4: Verify the results

After the task succeeds, view the delivered dataset in the task details. When all model calls succeed and answer quality filtering is not triggered, the output should meet the following conditions:

  • The final JSONL contains 5 lines; the empty-question line faq-006 is filtered out and not counted as a failure.

  • Each line contains messages with both the user and assistant roles, and all content fields are non-empty.

  • Each answer is consistent with the corresponding reference material, key numbers and constraints are accurate, and no rules beyond the reference material are added.

{"id": "faq-001", "messages": [{"role": "user", "content": "How many books can I borrow at a time?"}, {"role": "assistant", "content": "Hello. Each valid library card allows you to borrow up to 5 books at a time."}]}
{"id": "faq-002", "messages": [{"role": "user", "content": "How long can I borrow books for?"}, {"role": "assistant", "content": "Regular books can be borrowed for 30 days, counted from the day of borrowing."}]}
{"id": "faq-003", "messages": [{"role": "user", "content": "My book is almost due. Can I renew it?"}, {"role": "assistant", "content": "Yes. You can renew a book 1 time before its due date, and the renewal period is 15 days. If the book has been reserved by another reader, it cannot be renewed."}]}
{"id": "faq-004", "messages": [{"role": "user", "content": "What should I do if I lose my library card?"}, {"role": "assistant", "content": "If you lose your library card, report the loss as soon as possible through the library service desk or the online service. The cardholder is responsible for any borrowing that occurs before the loss is reported."}]}
{"id": "faq-005", "messages": [{"role": "user", "content": "Are you open on weekends?"}, {"role": "assistant", "content": "Yes, the library is open on weekends. Opening hours are 9:00 to 21:00. On statutory holidays, the schedule is subject to announcements."}]}

The exact wording generated by the teacher model may differ. If an output is truncated or an answer is too short, the corresponding line is filtered out, and the final result may contain fewer than 5 lines. You can adjust max_tokens or min_answer_chars and then verify again.

Processor development notes

File structure

A complete processor file contains a prompt template and the processing logic, and is saved in a single .py file. The following is a minimal template:

from __future__ import annotations

from typing import Any, Dict, List, Optional, Union

from easydistill.operators.custom import BaseProcessor


class MyProcessor(BaseProcessor):
    """Processor description."""

    # 1. Prompt template (inline, literal string)
    prompts: Dict[str, str] = {
        "generate": "Please answer the following question:\n\n{question}",
    }

    # 2. Optional initialization (when overriding, call super first)
    def setup(self, ctx) -> None:
        super().setup(ctx)

    # 3. Core processing logic (must be implemented)
    def process(
        self, sample: Dict[str, Any]
    ) -> Union[Dict[str, Any], List[Dict[str, Any]], None]:
        """Process one input line and return the output."""
        prompt = self.render_prompt("generate", question=sample.get("question"))
        result = self.generate(prompt=prompt, max_tokens=512)
        return {"id": sample.get("id"), "messages": [
            {"role": "user", "content": sample.get("question")},
            {"role": "assistant", "content": result.response},
        ]}

    # 4. Optional resource cleanup
    def teardown(self) -> None:
        return None

Mandatory constraints

Constraint

Description

Must inherit from BaseProcessor

The framework verifies this through type checking. The import path is from easydistill.operators.custom import BaseProcessor.

__init__Must be instantiable with zero arguments

The framework instantiates the class with cls(), so it cannot have required parameters.

process Must override

This is an abstract method. Failing to override it raises TypeError.

When you override setup, you must first call super().setup(ctx)

. Otherwise, attributes and methods such as self.backend and self.generate become unavailable.

Prompt template

You can store inline templates in the class-level prompts dictionary and render them by calling self.render_prompt(name, **variables). Under the hood, rendering uses str.format: write template variables as {question}, and literal braces must be written as {{ and }}.

class MyProcessor(BaseProcessor):
    prompts: Dict[str, str] = {
        "generate": "Please answer the following question:\n\n{question}",
    }

In the YAML configuration, the custom.prompts section can also define templates. Templates are resolved in the following order: class-level templates > the YAML configuration section.

Attributes and methods available in process()

setup() — after this, you can directly use the following attributes and methods in process() to get the prompt, generate text, read parameters, and write logs. When you need multi-turn conversations or a judge model, you can also call the backend API directly.

Generate text: self.generate()

In process(), use self.render_prompt to render the prompt template and return the text generated by the teacher model.

def process(self, sample):
    prompt = self.render_prompt("generate", question=sample["question"])
    result = self.generate(
        prompt=prompt,
        temperature=self.params.get("temperature", 0.7),
        max_tokens=self.params.get("max_tokens", 1024),
    )
    return {"id": sample.get("id"), "answer": result.response}

Method

Return type

Description

self.load_prompt(name)

str

Retrieves the raw template from the class-level prompts or from custom.prompts in the YAML file, with no variable substitution. Use this method when you need to assemble or process the template yourself.

self.render_prompt(name, **vars)

str

Reads the template and uses str.format to replace variables and return the rendered text. This is the most commonly used method.

self.generate(prompt, *, system, model_id, temperature, max_tokens)

GenerationResult

Key parameter prompt: str or content list.

Return value: GenerationResult

result.response     # str — the generated text
result.model        # Optional[str] — the model that actually responded ID
result.usage        # Optional[Dict] — token usage, e.g. {"prompt_tokens": 10, "completion_tokens": 50}
result.metadata     # Dict[str, Any] — additional metadata
                    #   metadata["finish_reason"] = "stop" | "length" | ...

metadata["finish_reason"] == "length" indicates truncation: the model stopped at max_tokens, so the JSON output may be incomplete. If the judge fails to parse the JSON, first check whether the output was truncated.

Read parameters and configuration, and write logs

Property

Return type

Description

self.params

dict

custom.paramsA dictionary of the custom parameters that you define in the YAML file. We recommend that you use self.params.get("key", default value) to read them.

self.config

dict

The fully expanded configuration, for read-only use.

self.logger

logging.Logger

A logger dedicated to the processor. Log entries are written to the task log, which makes it easier to locate a failed row.

self.ctx

ProcessorContext

The runtime context itself. Use it when you need framework-level information.

The following example shows the simplest way to read custom parameters, read the configuration, and write logs:

threshold = int(self.params.get("min_score", 4))      # custom.params custom parameters
model_id = self.config["backend"].get("model_id")     # fully expanded configuration, read-only
self.logger.info("min_score=%s, model=%s", threshold, model_id)

Call the backend API directly

self.generate() is not enough, you can work with the backend directly:

Property

Type

Description

self.backend

ModelBackend

The main model backend. Guaranteed to be non-None.

self.eval_backend

Optional[ModelBackend]

The optional judge model backend. It is None when no judge model is configured in the console, so check whether it exists before you call it.

Multi-turn conversation example:

# ── Multi-turn conversation (the convenience methods support single turns only) ──
result = self.backend.generate(
    messages=[
        {"role": "system", "content": "You are an assistant"},
        {"role": "user", "content": "Hello"},
        {"role": "assistant", "content": "Hello!"},
        {"role": "user", "content": "Explain deep learning"},
    ],
    model_id="kimi-k2.6",       # None = use the backend default model
    temperature=0.7,            # float, default 0.7
    max_tokens=2048,            # int, default 2048
)

# ── ModelBackend.generate full signature ──
# def generate(
#     self,
#     messages: List[Dict[str, Any]],  # OpenAI compatible message list
#     model_id: Optional[str] = None,  # Model ID, None uses the default
#     temperature: float = 0.7,        # Sampling temperature
#     max_tokens: int = 2048,          # Maximum number of tokens
#     **kwargs: Any,                   # Backend-specific parameters
# ) -> GenerationResult

The return value is also a GenerationResult. For the fields, see Generate text: self.generate().

process() return value protocol

What you return for one input row determines the number of output rows and the resulting behavior:

Return method

Platform behavior

dict

One input row produces one output row.

list[dict]

One input row fans out into multiple output rows.

None

Actively filters out the current row. The row is not counted as a failure and does not consume a retry. Use this method for intentional filtering; do not raise an exception instead.

Raise an exception

The current row fails to be processed and consumes a retry.

Other types

Triggers TypeError and consumes a retry.

Note

Whether you return a dict or a list[dict], every field that you return must be JSON-serializable. A value that cannot be serialized (such as a datetime object or an instance of a custom class) causes the row to fail with TypeError.

Concurrency and shared state

process() may be called concurrently by multiple threads. If you use mutable state such as a shared counter or a cache, you must create a thread lock in setup() and use with self._lock when you access the shared state.

import threading

def setup(self, ctx):
    super().setup(ctx)
    self._lock = threading.Lock()
    self._kept = 0

def process(self, sample):
    with self._lock:
        self._kept += 1
        seq = self._kept
    return {"id": sample.get("id"), "seq": seq}

YAML configuration in detail

Complete configuration template

The following template covers the main configuration items for custom distillation. Copy it and trim it to fit your task. Before you start, note these rules:

  • The console form and the YAML together produce the final configuration: the form injects the teacher model, the judge model, and their credentials, and it also selects the input file and the processor file; the YAML and the processor together determine the processing logic, the execution behavior, and the output format.

  • You do not need to configure the pipeline section. The flow is fixed: process always runs first, and build is appended after it only when custom.builder is configured.

job_type: custom_distill

dataset:
  input_path: input.jsonl
  output_path: distillation_dataset.jsonl

processor:
  path: processor.py
  # class: MyProcessor
  # requirements: [pandas>=2.0]

backend:
  timeout: 1200.0
  max_retries: 3

custom:
  params:
    temperature: 0.7
    max_tokens: 1024
    # min_score: 4
  # prompts:
  #   answer: |
  #     Answer the following questions:
  #     {question}
  max_workers: 8
  show_progress: true
  max_retries: 2
  retry_backoff: 2.0
  row_timeout: null
  raise_on_error: true
  resume: false
  builder:
    format: sharegpt

dataset: inputs and deliverables

  • input_path : the input data file, one JSON object per line, with field names of your choice; the processor's process() receives them line by line. If the form already selects an input file, the form takes precedence.

  • output_path : determines the result file name and the delivery form. With .jsonl, the complete output of the processor or builder is kept line by line; with .json, it is flattened into single-turn question-and-answer data. Multi-turn conversations and preference-pair data must use .jsonl so that no structure is lost.

processor: declaration and dependencies

  • path corresponds to the processor file uploaded through the form; the platform mounts the file automatically.

  • classWhen it is omitted, the platform auto-detects the processor in this order:

    1. The class named Processor is preferred.

    2. Otherwise, the only concrete BaseProcessor subclass in the module is used.

    3. If several candidates exist, an error is reported and the candidate class names are listed; you must then configure class explicitly.

  • requirements declares additional pip dependencies, which are installed automatically before the processor is imported. If dependency installation fails, the task is aborted before any data is read, so no incomplete results are produced.

backend: model request behavior

  • The console form injects the teacher model, the judge model, and the access credentials, so you do not need to specify a model ID, a service address, or a key in the YAML.

  • timeout is the maximum wait time for a single request, in seconds; it defaults to 1200 seconds, so leave enough headroom for the slowest call.

  • backend.max_retries is the request-level retry after a single HTTP request fails; custom.max_retries is the row-level retry after a whole row fails to process. The two take effect independently, as described in Reliability below.

custom: execution parameters

Free-form parameters and prompts

  • params: the key names and values are determined by the processing logic, and the processor reads them through self.params.get("temperature", 0.7) and similar calls. This is the right place for sampling parameters, quality thresholds, and business switches; adjusting only these values requires no processor changes and no re-upload.

  • prompts: a value can be written in 2 ways, as an inline template string or as the relative path of a template file. When a name is looked up, the prompts defined in the processor class is used first; if the class does not define it, the template of the same name in the YAML is used. Adjusting only the templates in the YAML requires no processor re-upload. For the complete rules and examples, see Prompt template in the processor chapter.

Concurrency and progress

  • max_workers: controls the number of row-level concurrent threads; the default is 8. process() may be called by multiple threads at the same time, so you must lock shared state such as accumulated counters and shared lists yourself; see Concurrency and shared state.

  • show_progress: controls whether the processing progress bar is displayed; it does not affect the output.

Reliability

In the template, max_retries, retry_backoff, row_timeout, raise_on_error, and resume control row-level retries, backoff, per-row timeout, the error strategy, and resume respectively.

Parameter

Default

Description

Retry mechanism

max_retries

2

The number of row-level retries. A value of 2 means each row is attempted at most 3 times. Both timeouts and exceptions consume retries.

retry_backoff

2.0

The retry backoff base, in seconds. The wait time grows exponentially: retry_backoff × 2^(attempt-1).

Row-level timeout

row_timeout

None

The timeout for a single attempt on one row, in seconds. Leave it empty for no limit. If you set it, set it well above the normal time a row takes. A timeout only stops the waiting: the row still runs until the blocking call returns, and its result is discarded.

Error strategy

raise_on_error

true

true: fail-fast. The task is aborted at the first failed row, and the checkpoint file is kept for resuming.

false: lenient mode. Failed rows are written to <output_path>.errors.jsonl and the task continues. After you fix the error file, you can rerun it directly as input.

Resume

resume

false

Set it to true to enable resume. The checkpoint file is written to <output_path>.ckpt.jsonl: successful rows are reused as they are and never recomputed, failed rows are retried, and the final output is merged in the original input order. The checkpoint file is deleted automatically after the task succeeds and kept for the next resume if it fails.

custom.builder: dataset construction

After you configure builder, the platform runs build after process and organizes the training data in sharegpt, alpaca, or dpo format. If you omit this entire section, the processor output is written as is (suitable for scenarios such as intermediate results and debugging data). The output path is still determined by dataset.output_path. Do not set it again in the builder.

custom:
  builder:
    format: sharegpt               # alpaca / sharegpt / dpo
    include_system_prompt: true    # Only valid for alpaca

Output formats

Format

Processor output requirements

Builder behavior

sharegpt

Contains the messages field:{"messages": [{"role": ..., "content": ...}, ...]}

Passes the data through as is.

alpaca

Contains the messages field.

Automatically converted to the {"instruction": ..., "output": ...} structure. include_system_prompt takes effect only for this format and defaults to true.

dpo

Contains the prompt, chosen, and rejected fields.

Writes preference pair data directly.

Complete example: two-stage DPO processor

The following is a complete implementation of a production-grade processor that demonstrates how to use all the core APIs:

"""Two-stage DPO builder: generate two candidates → the judge evaluates them → output a preference pair."""

from __future__ import annotations

import json
from typing import Any, Dict, Optional

from easydistill.operators.custom import BaseProcessor


class TwoStageDPOProcessor(BaseProcessor):
    prompts: Dict[str, str] = {
        "generate": (
            "Answer the following question clearly and completely.\n\n"
            "Question: {question}"
        ),
        "judge": (
            "You are a strict judge. Two candidate answers to the same question are provided below.\n\n"
            "Question: {question}\n\n"
            "Answer A: \n{answer_a}\n\n"
            "Answer B: \n{answer_b}\n\n"
            'Reply with strict JSON and nothing else:'
            '{{"winner": "A"}} or {{"winner": "B"}} or {{"winner": "tie"}}'
        ),
    }

    def process(self, sample: Dict[str, Any]) -> Optional[Dict[str, Any]]:
        question = (sample.get("question") or "").strip()
        if not question:
            return None  # Drop empty question rows

        # ── Stage 1: the main backend generates two candidate answers ──
        prompt = self.render_prompt("generate", question=question)
        model_id = self.config["backend"].get("model_id")
        temp = self.params.get("temperature", 0.9)
        max_tok = self.params.get("max_tokens", 1024)

        answer_a = self.backend.generate(
            messages=[{"role": "user", "content": prompt}],
            model_id=model_id,
            temperature=temp,
            max_tokens=max_tok,
        ).response

        answer_b = self.backend.generate(
            messages=[{"role": "user", "content": prompt}],
            model_id=model_id,
            temperature=temp,
            max_tokens=max_tok,
        ).response

        # ── Stage 2: the judge backend evaluates the candidates ──
        judge_backend = self.eval_backend or self.backend
        judge_cfg = self.config.get("eval_backend") or self.config["backend"]

        verdict_prompt = self.render_prompt(
            "judge", question=question, answer_a=answer_a, answer_b=answer_b
        )
        verdict = judge_backend.generate(
            messages=[{"role": "user", "content": verdict_prompt}],
            model_id=judge_cfg.get("model_id"),
            temperature=self.params.get("judge_temperature", 0.1),
            max_tokens=self.params.get("judge_max_tokens", 512),
        )

        # Check for truncation
        if verdict.metadata.get("finish_reason") == "length":
            self.logger.warning(
                "row %s: judge verdict truncated, raise judge_max_tokens",
                sample.get("id"),
            )
            return None

        # Parse the verdict
        winner = self._parse_winner(verdict.response)
        if winner is None or winner == "tie":
            return None  # Tie or parse failure → no preference signal → discard

        # Build the preference pair
        chosen, rejected = (answer_a, answer_b) if winner == "A" else (answer_b, answer_a)
        return {"prompt": question, "chosen": chosen, "rejected": rejected}

    @staticmethod
    def _parse_winner(text: str) -> Optional[str]:
        start = text.find("{")
        end = text.rfind("}") + 1
        if start == -1 or end <= start:
            return None
        try:
            data = json.loads(text[start:end])
        except json.JSONDecodeError:
            return None
        winner = data.get("winner")
        return winner if winner in {"A", "B", "tie"} else None

Corresponding YAML configuration:

job_type: custom_distill

processor:
  path: two_stage_dpo.py
  class: TwoStageDPOProcessor

backend:
  type: pai_token
  api_key: ${PAI_TOKEN_API_KEY}
  base_url: ${PAI_TOKEN_BASE_URL}
  model_id: kimi-k2.6

eval_backend:
  type: pai_token
  model_id: deepseek-v4-pro

dataset:
  input_path: seeds.jsonl
  output_path: outputs/dpo_output.jsonl

custom:
  params:
    temperature: 0.9
    judge_temperature: 0.1
    max_tokens: 1024
    judge_max_tokens: 512
  builder:
    format: dpo