Documentation

SFT Text Data Processing

Convert text or structured files into model training data. Select your files, then configure cleaning, synthesis, and export steps.


Table of Contents


Environment Requirements

This feature requires installing CPU or GPU environment dependencies in the settings.

  • Go to the Settings page of ModxAI Studio
  • Under System, in Environment Configuration, select and install the required environment (CPU/GPU)
  • After installation, return to the data processing page to use the related features

Feature Introduction

SFT data processing is used to convert raw text into structured datasets usable for model fine-tuning training. Choose a workflow template and adjust it as needed. To prepare a dataset from a code repository, use Code Analysis (CODE).

Applicable Scenarios:

  • Domain knowledge fine-tuning dataset construction
  • Automatic generation of Q&A pair data
  • Pre-training corpus preparation

Core Features:

  • Supports AI-assisted data synthesis, automatically generating high-quality Q&A pairs
  • Multi-threaded parallel processing, fully utilizing hardware resources
  • Incremental processing support, resumable from breakpoints
  • Comprehensive error recovery mechanism

Data Type Selection

Text Data (Text)

Suitable for processing various documents, articles, technical materials, and other text content.

Supported File Formats:

  • Documents: PDF, Word (.doc/.docx), PowerPoint (.ppt/.pptx), Excel (.xls/.xlsx)
  • Web Pages: HTML (.html/.htm)
  • Text: TXT, Markdown, CSV, JSON, XML
  • Archives: ZIP (automatically decompresses and processes)

Structured Data (JSON):

For existing JSON/JSONL, open Self Improvement → Dataset → TRN → Text, select the structured JSON file type, and choose the training format: SFT, Pretrain, or DPO. This route runs only Convert/Parse → Output (steps 0 and 10), without text cleaning or AI synthesis.

  1. Select input and output directories and the JSON file type.
  2. Select the training format.
  3. Open Convert/Parse parameters and enter the source field names. Only mappings for the selected format are shown.
  4. Configure the dataset split under Output. SFT and pretraining also need a tokenizer matching the target model.
  5. Start processing, check valid, invalid, and warning counts in progress, and inspect the output manifest when complete.
Training formatAccepted samples and mappings
SFTA messages array, or instruction, optional input, and output; custom fields use SFT instruction, SFT input, and SFT output mappings
PretrainA text field; custom fields use the Pretrain text mapping
DPOprompt, chosen, and rejected; custom fields use DPO prompt, Chosen response, and Rejected response mappings

For a source record such as {"question":"Hello","answer":"Hello!"}, select SFT, map SFT instruction to question and SFT output to answer, and leave SFT input empty if there is no additional input.

Record ID Field identifies an existing record ID. Limit Count 0 means no limit. Source field names support dot-separated nested paths and comma-separated alternatives, selecting the first nonempty value in order.

SFT conversations accept only system, user, and assistant roles. They need a user question and must end with a nonempty assistant answer. Pretraining text and all three DPO fields must be nonempty strings, and DPO chosen and rejected responses must differ. Invalid records are excluded. If all records are invalid, processing fails; use the validation report to correct them and retry.

DPO preference data can be exported, but the current Training module provides only SFT and pretraining, not DPO training.

Workflow Templates

To simplify operations, the system presets several common workflow templates. You can choose according to your needs:

Template NameIncluded StepsApplicable ScenarioDescription
AI Synthesis0→1→2→3→4→5→7→10Need AI to generate Q&A pairsMost common complete flow
AI Quality0→1→2→3→4→5→7→8→9→10Need AI to filter low-quality dataIncludes quality assessment filtering
CustomSelect as neededSpecial needsManually select steps to execute

For unstructured text, choose the Export Format in AI Synthesis. Pretraining output retains both text samples and tokenized training files. Structured JSON instead uses the page's Training Format selection and the 0→10 workflow.


Processing Flow Overview

The following steps apply to unstructured text. Structured JSON training data uses only steps 0 and 10:

StepNameDescriptionRequiredConfigurable
0Convert/ParseRead and parse source files✓Code configurable
1CleanClean invalid content✓✓
2SplitSplit into appropriately sized chunks✓✓
3Analyze/OrganizeQuality assessment and complexity analysis✓-
4AI SynthesisUse AI to generate Q&A pairsOptional✓
5AI Synthesis ParseParse AI generation resultsOptional-
7Integrate DataAggregate all data and format✓-
8AI FilterAI quality assessment filteringOptional✓
9AI Filter ParseParse filtering resultsOptional-
10OutputGenerate final training data✓✓

Step Relationship Explanation:

  • The AI Synthesis template includes steps 4/5, and AI Quality also includes steps 8/9. In a custom workflow, include the required parsing steps rather than assuming an AI step adds them automatically.
  • Steps 8-9 require the output of Step 7 as input.

Step-by-Step Details

Step 0: Convert/Parse

Function: Read source files and extract content.

Text Data Processing

Automatically identify file formats and extract plain text content, preserving original paragraph structure.

Step 1: Clean

Function: Clean noisy content in data to improve data quality.

Processing Content:

  • Remove repetitive content such as headers, footers, navigation bars.
  • Clean special symbols and garbled characters.
  • Filter out meaningless paragraphs that are too short.

Configurable Parameters:

ParameterDescriptionDefaultSuggestion
Min Paragraph LengthParagraphs below this character count will be filtered3Technical documents can be set to 5-10
Sample ScopeScope of cleaning rules applicationStructureStructure - Only clean structural areas<br>Full Text - Apply to full text
Noise Phrases ModeMatching mode for cleaning samplesplainplain=prefix match; wildcard=supports *; regex=regex match
Noise SamplesCustom content to be removedEmptySeparate multiple samples with |
Link Line Removal LevelDeletion level for lines containing links20=keep all; 1=remove local/private paths; 2=remove all links

Advanced Parameters (Collapsible):

ParameterDescriptionDefaultSuggestion
Strip Private IP URLsWhether to strip lines containing private IP URLsEnabledRecommended to enable to avoid internal address leakage
Preserve Rich Link LinesWhether to preserve lines with links but rich contentDisabledEnable to preserve valuable reference descriptions
Strip URLs in Code BlocksWhether to replace URLs in code blocks with [REDACTED_URL]DisabledDecide based on security requirements
Rich Words ThresholdWords threshold to determine rich text12Used to judge whether to preserve link lines
Rich Length ThresholdCharacter length threshold for rich text80Works with words threshold for comprehensive judgment

Step 2: Split

Function: Split long text into chunks suitable for processing.

Processing Logic:

  • Split by natural boundaries (titles, paragraphs, functions).
  • Maintain semantic integrity.
  • Super long chunks will be split again, and associated hash recorded.

Configurable Parameters:

ParameterDescriptionDefaultSuggestion
Min Paragraph LengthMinimum character count for a single chunk3-
Doc Min TokensMinimum Token count for the entire document10Documents too short will be skipped
Chunk Min TokensMinimum Token count for a single chunk15Avoid generating overly fragmented chunks

Step 3: Analyze/Organize

Function: Perform quality analysis on data chunks and group by complexity.

Text Data Analysis Dimensions:

  • Effective content ratio (after removing stop words)
  • Vocabulary richness (TTR indicator)
  • Sentence complexity (average sentence length)
  • Structural degree (number of titles, lists, code blocks)

Complexity Grouping:

  • high: High complexity, suitable for generating in-depth analysis content.
  • mid: Medium complexity, suitable for regular Q&A.
  • low: Low complexity, suitable for simple Q&A or skipping.

Configurable Parameters

ParameterDescriptionDefaultRecommendation
Enable quality filteringWhether to use an embedding model for quality filteringOnRecommended to enable for better data quality. Can be disabled if false positives occur.

Embedding Model Dependency

Near-duplicate detection in this step can use an embedding model to improve accuracy. By default, the system uses the all-MiniLM-L6-v2 model, if it cannot be installed, an alternative algorithm is used for near-duplicate detection:

  • Local first: Tries to load a locally downloaded model first
  • Automatic fallback: Falls back to TF-IDF if an embedding model is unavailable

Resource Tip: This step is multi-threaded parallel processing, which will consume significant CPU and memory resources. Please pay attention to system load when processing large amounts of data.


Step 4: AI Synthesis (Optional)

Function: Use AI models to analyze data chunks and generate Q&A pairs or analysis content for training.

Automatically convert raw text into structured data such as analysis, Q&A pairs, or even custom-styled structured data through AI capabilities.

Task Types:

TypeDescriptionOutput Content
AnalysisIn-depth interpretation of contentStructured analysis text
QAGenerate Q&A pairsQuestion-Answer pairs
AllExecute both tasks simultaneouslyAnalysis + QA

Complexity Matching:

The system matches different AI prompts for data chunks of different complexities based on the complexity grouping in Step 3:

ComplexityAnalysis FocusQA Generation Quantity
highIn-depth analysis of core concepts and implementation principles5-8 pairs
midExplain main functions and usage3-5 pairs
lowBriefly describe basic information1-3 pairs

See AI Node Configuration chapter for detailed AI parameter configuration.


Step 5: AI Synthesis Parse (Optional)

Function: Parse AI output from Step 4 and extract structured data. Exclude invalid content.

This step is recommended to be executed after Step 4 completes, cleaning the AI output to ensure high-quality data for subsequent steps.

Configurable Parameters

ParameterDescriptionDefaultRecommendation
Enable quality filteringWhether to use an embedding model for quality filteringOnRecommended to enable for better data quality. Can be disabled if false positives occur.

Embedding Model Dependency

Near-duplicate detection in this step can use an embedding model to improve accuracy. By default, the system uses the all-MiniLM-L6-v2 model, if it cannot be installed, an alternative algorithm is used for near-duplicate detection:

  • Local first: Tries to load a locally downloaded model first
  • Automatic fallback: Falls back to TF-IDF if an embedding model is unavailable

Export Format & Pre-training

Set Export Format in Step 4 (AI Synthesis) to choose the final output format:

Export FormatOutput ContentUse Case
sft_chatmlChatML dialogue format (system/user/assistant)SFT fine-tuning
pretrainPlain text corpus (single assistant message)Pre-training / Continued pre-training
dpoPreference pair format (prompt/chosen/rejected)DPO preference alignment training

Field mapping for structured JSON/JSONL (see Structured Data above) is written into one of these three outputs. Choosing sft_chatml, pretrain, or dpo selects the sample shape. The mapping does not send that input back through the unstructured cleaning path.


Step 7: Integrate Data

Function: Aggregate output from previous steps and convert to ChatML conversation format.

Processing Content:

  • Merge multiple data chunks from the same source.
  • Construct System-User-Assistant conversation structure.
  • Handle chunking and overlapping of super long content.

Output Format Example:

{ "messages": [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Question content..."}, {"role": "assistant", "content": "Answer content..."} ] }

Step 8: AI Filter (Optional, Use with Caution)

Function: Use AI to assess the quality of integrated data and filter low-quality entries.

Assessment Criteria:

  • Content accuracy and relevance
  • Expression clarity
  • Completeness and consistency

Output Judgment:

  • <P>: Pass, retain this data entry.
  • <F>: Fail, filter out this data entry.

⚠️ Important Warning:

Test AI filtering on a small, representative sample before using it on the full dataset. Using a model with insufficient capabilities may:

  • Incorrectly mark high-quality data as low quality.
  • Retain actually problematic data.
  • Lead to a decline in final dataset quality.

Suggestion: Unless you have sufficient computing resources and high-quality models, it is recommended to skip this step and control output quality by adjusting prompt parameters in Step 4.


Step 9: AI Filter Parse (Automatic)

Function: Parse filtering results from Step 8 and remove entries marked as <F>.


Step 10: Output

Split valid records into training, validation, and test sets, and write JSONL files and a manifest. This step does not offer JSON/NPY format selection or a parallel-thread setting.

ParameterDescriptionDefault
Dataset SplitTraining/validation/test proportions0.8 / 0.1 / 0.1
Tokenizer PathTokenizer directory for SFT and pretraining; match it to the target model. DPO export does not need oneCurrently configured tokenizer
System PromptSystem message used when tokenizing SFT; not used for pretraining or DPOEmpty
Split SeedControls the random split order; available in advanced settings42

After completion, inspect training_dataset_manifest.json and the files it lists. Only nonempty splits produce files; a small dataset may leave a split empty.

  • SFT/pretraining: each nonempty split contains data.jsonl and final_dataset.jsonl.
  • DPO: each nonempty split contains only data.jsonl, with no tokenized file for the current training module.
  • For training: select train/final_dataset.jsonl. For evaluation during training, select eval/final_dataset.jsonl and enable an evaluation strategy in the training parameters.

AI Node Configuration

Step 4 (AI Synthesis) and Step 8 (AI Filter) both require configuring AI model parameters.

Basic Parameters

ParameterDescriptionDefault
AI ModelSelect model to useRequired
Task TypeAnalysis / QA / AllAnalysis
Complexity MatchWhich complexity levels of data to processAll
Export FormatOutput format for final training datasft_chatml
Chain of Thought ModeInject CoT reasoning prompt to guide model thinking processOff

Export Format Options: sft_chatml (SFT ChatML dialogue format), pretrain (pre-training plain text), dpo (DPO preference pair format).

Chain of Thought Mode: When enabled, automatically injects content reasoning CoT prompts and disables the model's native thinking function to avoid dual thinking tag pollution. Suitable for analysis tasks where the model needs to show reasoning steps.

Advanced Parameters (Collapsible Area)

ParameterDescriptionDefaultRange
TemperatureGeneration diversity0.70-1
Max TokensMaximum output length10241-8192
Top KSampling candidates200-100
Top PNucleus sampling threshold0.950-1
Repeat PenaltyAvoid repetition1.10-2
Min PMinimum probability threshold0.00-1
Enable ThinkingUse model native thinkingNo-
Server AddressRemote inference service URL, format http://ip:port/v1/chat/completionsEmpty-

Custom System Prompt

You can customize AI behavior guidance in the System Prompt field. If left empty, the system uses default prompts based on task type:

Analysis Task Default Prompt (Overview):

  • Act as a professional technical analyst.
  • Perform structured in-depth analysis of content.
  • Output includes core concepts, key points, code examples (if applicable).

QA Task Default Prompt (Overview):

  • Act as a professional technical documentation writer.
  • Generate high-quality Q&A pairs.
  • Questions should cover different difficulty levels.

Incremental Processing and Error Repair

AI Synthesis step (Step 4) supports incremental processing and automatic error repair, which is very useful when processing large amounts of data.

Incremental Processing

When you pause processing or restart after an unexpected program interruption:

  1. Auto Detect: System detects processed data chunks.
  2. Skip Completed: Successfully processed chunks will not be requested again.
  3. Continue Processing: Only process new or incomplete data.

Implementation Mechanism:

  • Use WAL (Write-Ahead Logging) to record each processing result.
  • Track processing status of each data chunk via Hash value.
  • Periodic automatic backup (every 15 minutes).

Error Repair Mechanism

When an AI request fails, the system automatically retries and repairs:

Retry Strategy:

  • Max retries: 3 times
  • Retry interval: 60 seconds
  • Timeout: Dynamically adjusted based on Token count (120-600 seconds)

Error Recovery:

  • Failed requests are recorded in the error list.
  • Automatically attempt to repair previous errors on next execution.
  • Support manual triggering of error repair.

Status Tracking:

{ "total_groups": 100, "processed_count": 85, "processed_groups": { "file_a.txt__abc123": { "total_chunks": 10, "processed_chunks": ["hash1", "hash2", ...], "error_chunks": ["hash9"], "is_done": false } } }

Output Formats

Output location

Text output normally uses output directory/datasets/text_dataset/final. Existing tasks may retain an earlier layout; follow the locations in progress messages and the output manifest.

Raw samples and training files

FileContents
train/data.jsonl, eval/data.jsonl, test/data.jsonlNormalized raw samples: messages for SFT, text for pretraining, or prompt, chosen, and rejected for DPO, with a sample identifier
final_dataset.jsonl in each splitTokenized SFT/pretraining records containing input_ids, label, and length; these are training files, not raw ChatML conversations
training_dataset_manifest.jsonData format, split information, sample counts, validation summary, and artifact paths
training_validation.jsonlWritten when a validation report is available; includes record locations, field issues, and warnings
training_metadata.jsonlWritten separately when additional metadata is present

Raw and tokenized files serve different purposes. Pretraining data.jsonl cannot replace final_dataset.jsonl. JSONL export does not mean the training page accepts every JSON/JSONL structure.

Check the output

  1. Confirm that the task finished and produced a manifest.
  2. Check valid counts, invalid records, and warnings, not just whether files exist.
  3. Inspect raw samples to confirm that questions, answers, or text were mapped correctly.
  4. Use the training file listed in the manifest and retain its matching model tokenizer.

Notes

Performance and Resources

  1. Multi-threaded Processing: Step 0 and Step 1 use multi-threaded parallel processing, consuming significant CPU and memory.
  2. AI Request Overhead: Steps 4 and 8 require massive AI requests; processing time depends on data volume and model speed.
  3. Disk Space: Intermediate files occupy some disk space; suggest reserving sufficient space.

AI Model Selection

  1. Synthesis Step: Check questions and answers on a small sample before choosing a model.
  2. Filter Step: Inspect both retained and rejected samples to confirm that filtering matches your criteria.

FAQ

Q: What if processing is interrupted?

A: Directly re-execute the same steps. The system automatically detects processed content and continues from the breakpoint.

Q: AI synthesis content quality is not ideal?

A: Try the following methods:

  1. Adjust temperature parameter (lowering increases consistency).
  2. Customize system prompt.
  3. Use a larger model.
  4. Adjust complexity matching, process high-complexity data first.

Q: Why is there no separate pre-training entry?

A: Pretraining and SFT use the same data-processing page. The selection depends on the input type:

  • For structured JSON, choose pretraining under Training Format on the page, configure the fields, then run conversion and output.
  • For unstructured text, set Export Format to pretrain in the AI synthesis step.

The exported data.jsonl preserves raw samples with a text field; final_dataset.jsonl contains tokenized training records. For training, select train/final_dataset.jsonl from a nonempty training split rather than using the raw text samples directly. See Output Formats for file purposes.

Q: AI filtering causes significant data reduction?

A: This usually means:

  1. The model used has insufficient capabilities; suggest switching to a stronger model.
  2. Original data quality indeed has issues.
  3. Can temporarily skip AI filtering step and manually spot-check data quality.

Q: How to process ultra-large datasets?

A: Suggest batch processing:

  1. Split data into multiple subdirectories.
  2. Process each subdirectory separately.
  3. Finally merge output files.
  4. Utilize incremental processing function to execute in multiple batches.