SFT Dataset Creation
Overview
The SFT extraction module provides tools for creating Supervised Fine-Tuning (SFT) datasets from generated completions. It filters, ranks, and formats model completions into structured conversation samples suitable for training, with support for reward-based filtering, diversity-aware selection, and customizable prompt templates.
Key Concepts
Extraction Pipeline
The SFT extraction pipeline follows these steps:
- Correctness filtering — Remove completions that are invalid (e.g., malformed SMILES, failed extractions)
- Grouping — Group completions by their originating prompt ID
- Diversity-aware filtering (optional) — Deduplicate chemically similar completions using molecular fingerprints (see Diversity-Aware Top-k)
- Reward threshold filtering (optional) — Keep only completions whose reward exceeds a minimum threshold
- Post-processing — Optionally inject reward and source information into the prompt messages
Reward & Source Templating
After building conversation samples, the extractor can enrich prompts with reward and source information using configurable templates. For example, with the default reward_info_template:
# Original system message:
"Generate a molecule with high binding affinity."
# After reward templating (reward=0.85):
"Generate a molecule with high binding affinity.\nPropose an answer whose reward is: 0.85"
Usage Examples
Basic SFT Extraction
from mol_gen_docking.evaluation.sft_extraction import (
SFTExtractionConfig,
SFTExtractor,
Completion,
)
from mol_gen_docking.data.pydantic_dataset import Sample, Conversation, Message
# Define the extraction configuration
config = SFTExtractionConfig(
min_reward_threshold=0.5,
div_threshold=None, # No diversity filtering
reward_info_template={}, # No reward injection
source_info_template={}, # No source injection
)
extractor = SFTExtractor(config)
# Build a prompt sample
prompt = Sample(
identifier="prompt_0",
conversations=[
Conversation(
messages=[
Message(role="system", content="You are a molecular generation assistant."),
Message(role="user", content="Generate a molecule with high docking score."),
]
)
],
)
# Build completions (e.g., from a generation run)
completions = [
Completion(
output="<answer>CCO</answer>",
reward=0.8,
metadata={"prompt_id": "prompt_0"},
reward_meta={
"generation_verifier_metadata": {"all_smi": ["CCO"]}
},
source="my_model_v1",
),
Completion(
output="<answer>invalid</answer>",
reward=0.1,
metadata={"prompt_id": "prompt_0"},
reward_meta={
"generation_verifier_metadata": {"all_smi": ["invalid"]}
},
source="my_model_v1",
),
]
# Extract SFT samples
samples = extractor.extract(completions, [prompt])
print(len(samples))
# Output:
# >>> 1
With Diversity-Aware Filtering
config = SFTExtractionConfig(
min_reward_threshold=0.3,
div_threshold=0.7, # Tanimoto similarity threshold
fingerprint_name="ecfp4-1024",
reward_info_template={},
source_info_template={},
)
extractor = SFTExtractor(config)
samples = extractor.extract(completions, [prompt])
With Reward-Conditioned Prompts
config = SFTExtractionConfig(
min_reward_threshold=0.5,
div_threshold=None,
reward_info_template={
"system": "{content}\nPropose an answer whose reward is: {reward:.2f}"
},
source_info_template={
"system": "{content}\nThe source of this conversation is: {source}"
},
)
extractor = SFTExtractor(config)
samples = extractor.extract(completions, [prompt])
# The system message of each conversation now includes reward and source info
print(samples[0].conversations[0].messages[0].content)
# Output:
# >>> "You are a molecular generation assistant.
# >>> Propose an answer whose reward is: 0.80
# >>> The source of this conversation is: my_model_v1"
Using a Custom System Prompt File
config = SFTExtractionConfig(
system_prompt_path="system_prompts/vanilla.json",
min_reward_threshold=0.5,
div_threshold=None,
reward_info_template={},
source_info_template={},
)
extractor = SFTExtractor(config)
# The system prompt from the JSON file will replace the existing system message
samples = extractor.extract(completions, [prompt])
Inspecting Extraction Metadata
After extraction, the SFTExtractor tracks metadata about the retained completions:
extractor = SFTExtractor(config)
samples = extractor.extract(completions, [prompt])
# Prompt IDs of all retained completions
print(extractor.metadata.prompt_ids)
# Rewards of retained completions
print(extractor.metadata.rewards)
# Estimated token counts
print(extractor.metadata.n_tokens)
Class & Function Reference
Completion
Bases: BaseModel
A single model completion with associated reward and metadata.
Represents one generated output for a given prompt, together with the reward score assigned by the reward model and any verifier metadata needed for correctness filtering and diversity-aware selection.
Attributes:
| Name | Type | Description |
|---|---|---|
output |
str
|
The raw generated text (e.g., containing |
reward |
Optional[float]
|
Reward score assigned to this completion, or |
metadata |
Dict[str, Any]
|
Arbitrary metadata dict; must contain a |
reward_meta |
Dict[str, Any]
|
Verifier metadata produced by the reward pipeline. Expected to
contain one of |
source |
Optional[str]
|
Optional label identifying the model or method that produced the
completion (e.g., |
Example
Source code in mol_gen_docking/evaluation/sft_extraction.py
SFTExtractionConfig
Bases: BaseModel
Configuration for SFT dataset extraction.
Controls how completions are filtered, selected, and formatted into training samples. Supports reward thresholding, diversity-aware deduplication, and prompt enrichment via reward/source templates.
Attributes:
| Name | Type | Description |
|---|---|---|
system_prompt_path |
Optional[str]
|
Path to a JSON file containing a system prompt template. If specified, the content replaces the system message in all conversations. |
min_reward_threshold |
Optional[float]
|
Minimum reward score a completion must achieve to be
retained. Set to |
div_threshold |
Optional[float]
|
Tanimoto similarity threshold for diversity-aware filtering.
Completions more similar than this threshold to an already-selected
completion are discarded. Set to |
fingerprint_name |
Optional[str]
|
Molecular fingerprint type used for diversity computation
(e.g., |
reward_info_template |
Dict[str, str]
|
Per-role templates for injecting reward information into
prompt messages. Keys are message roles (e.g., |
source_info_template |
Dict[str, str]
|
Per-role templates for injecting source information into
prompt messages. Keys are message roles, values are format strings with
|
Example
Source code in mol_gen_docking/evaluation/sft_extraction.py
SFTExtractionMetadata
Bases: BaseModel
Metadata accumulated during SFT extraction.
Tracks per-completion statistics (prompt IDs, rewards, estimated token counts) for all completions that passed filtering and were included in the final dataset.
Attributes:
| Name | Type | Description |
|---|---|---|
prompt_ids |
List[str]
|
Prompt identifiers for each retained completion, preserving the order in which completions were processed. |
rewards |
List[float]
|
Reward scores for each retained completion. Defaults to |
n_tokens |
List[int]
|
Rough token-count estimates for each retained completion,
computed as |
Source code in mol_gen_docking/evaluation/sft_extraction.py
SFTExtractor
Extracts SFT training samples from a collection of completions and prompts.
Orchestrates the full extraction pipeline: correctness filtering, per-prompt grouping, diversity-aware selection, reward thresholding, conversation formatting, and post-processing (reward/source injection).
Attributes:
| Name | Type | Description |
|---|---|---|
config |
The |
|
metadata |
An |
Example
from mol_gen_docking.evaluation.sft_extraction import (
SFTExtractionConfig, SFTExtractor, Completion,
)
config = SFTExtractionConfig(
min_reward_threshold=0.5,
div_threshold=None,
reward_info_template={},
source_info_template={},
)
extractor = SFTExtractor(config)
samples = extractor.extract(completions, prompts)
Source code in mol_gen_docking/evaluation/sft_extraction.py
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 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 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 | |
__init__(config)
Initialise the SFT extractor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
SFTExtractionConfig
|
Extraction configuration controlling filtering thresholds, diversity parameters, and prompt templates. |
required |
Source code in mol_gen_docking/evaluation/sft_extraction.py
completion_to_conv(completions, prompt)
Convert filtered completions into a multi-conversation Sample.
For each completion, creates a new Conversation by copying the
prompt messages and appending the completion text as an assistant message.
Metadata such as source, rating, and training_masks_strategy
are carried over from the original conversation / completion.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
completions
|
List[Completion]
|
Filtered completions to convert. All must have
|
required |
prompt
|
Sample
|
The original prompt |
required |
Returns:
| Type | Description |
|---|---|
Sample | None
|
A new |
Sample | None
|
completion, or |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If any completion's prompt ID does not match
|
Source code in mol_gen_docking/evaluation/sft_extraction.py
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 | |
extract(completions, prompts)
Run the full SFT extraction pipeline.
Executes the following steps:
- Correctness filtering — removes invalid completions via
:meth:
filter_is_correct. - Grouping — groups surviving completions by
prompt_id. - System prompt override — if
config.system_prompt_pathis set, replaces or inserts the system message in every prompt conversation. - Per-prompt extraction — calls :meth:
get_samplefor each prompt that has at least one completion.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
completions
|
List[Completion]
|
All completions across all prompts. |
required |
prompts
|
List[Sample]
|
The original prompt |
required |
Returns:
| Type | Description |
|---|---|
List[Sample]
|
List of |
List[Sample]
|
sample may contain multiple conversations (one per retained |
List[Sample]
|
completion). |
Source code in mol_gen_docking/evaluation/sft_extraction.py
filter_completions_single_id(completions)
Filter and rank completions that share a single prompt ID.
Applies the following filters in order:
- Diversity-aware selection — if
config.div_thresholdis set, uses :func:~mol_gen_docking.evaluation.diversity_aware_top_k.diversity_aware_top_kto remove chemically redundant completions. - Reward threshold — if
config.min_reward_thresholdis set, discards completions whose reward is below the threshold.
Side-effects: appends per-completion statistics (reward, token count,
prompt ID) to self.metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
completions
|
List[Completion]
|
List of completions that must all share the same
|
required |
Returns:
| Type | Description |
|---|---|
List[Completion]
|
The filtered list of completions. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If completions do not share the same prompt ID, or if diversity filtering is requested but reward metadata is missing. |
Source code in mol_gen_docking/evaluation/sft_extraction.py
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 | |
filter_is_correct(completions)
Filter completions to keep only those that are semantically correct.
Automatically detects the task type from the verifier metadata and applies the appropriate correctness check:
- Molecular generation (
generation_verifier_metadata): keeps completions with exactly one extracted SMILES. - Property prediction (
mol_prop_verifier_metadata): keeps completions where value extraction succeeded. - Retro-synthesis (
reaction_verifier_metadata): keeps completions whose validity score is strictly positive.
If any completion has empty reward_meta, all completions are returned
unfiltered (graceful fallback).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
completions
|
List[Completion]
|
List of completions to filter. |
required |
Returns:
| Type | Description |
|---|---|
List[Completion]
|
A new list containing only the completions that passed the |
List[Completion]
|
task-specific correctness check. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If none of the known verifier metadata keys are found in the completions. |
Source code in mol_gen_docking/evaluation/sft_extraction.py
get_sample(completions, prompt)
Build a single SFT sample from completions and their originating prompt.
Convenience method that chains :meth:filter_completions_single_id,
:meth:completion_to_conv, and :meth:post_process_sample.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
completions
|
List[Completion]
|
Completions for one prompt ID. |
required |
prompt
|
Sample
|
The corresponding prompt |
required |
Returns:
| Type | Description |
|---|---|
Sample | None
|
A fully processed |
Sample | None
|
if no completions survive filtering. |
Source code in mol_gen_docking/evaluation/sft_extraction.py
post_process_sample(sample)
Enrich a sample's messages with reward and source information.
Iterates over every conversation and message in sample and applies:
config.reward_info_template— injects the conversation's reward into matching messages (keyed by role).config.source_info_template— injects the conversation's source into matching messages (keyed by role). Always applied after the reward template.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sample
|
Sample
|
The |
required |
Returns:
| Type | Description |
|---|---|
Sample
|
The same |