|
Download docs/dataset_adapter.md from Heisenger/sft-benchmark-trajectories: direct link, hf CLI and curl.
- Browser
- Download file 14.2 kB
-
https://huggingface.co/datasets/Heisenger/sft-benchmark-trajectories/resolve/main/docs/dataset_adapter.md
- Command line
-
hf download hf://datasets/Heisenger/sft-benchmark-trajectories/docs/dataset_adapter.md
-
curl -L -o dataset_adapter.md https://huggingface.co/datasets/Heisenger/sft-benchmark-trajectories/resolve/main/docs/dataset_adapter.md
14.2 kB
| # Consumer-facing dataset adapter | |
| `agent_trajectories` has two intentionally separate adapter layers: | |
| 1. **Source adapters** acquire a pinned external release and normalize its | |
| benchmark-specific rows into the canonical `Trajectory` schema. They run | |
| during ingestion or an explicit refresh. | |
| 2. **The consumer adapter** reads only the persisted canonical library and its | |
| read-only metadata index. Training and evaluation jobs never import | |
| benchmark parsers, contact upstream hosts, or rewrite dataset files. | |
| The stable entry point is `CanonicalDatasetAdapter`. Its API version is `1.3`; | |
| the package version is `0.5.0`. Existing source, sampling and view interfaces | |
| remain supported. | |
| ```python | |
| from agent_trajectories import CanonicalDatasetAdapter | |
| dataset = CanonicalDatasetAdapter("data/library") | |
| print(dataset.available_benchmarks()) | |
| print(dataset.available_sources()) | |
| ``` | |
| The adapter validates `manifest.json`, requires the persisted `index.sqlite` | |
| and available canonical shards, and opens SQLite in read-only mode. A federated | |
| release can contain full-inventory metadata while marking some payloads as | |
| metadata-only. It keeps only lightweight selected index rows in memory. | |
| Unsampled event payloads are parsed one trajectory at a time. | |
| ## Query contract | |
| `DatasetQuery` fields use OR semantics within a field and AND semantics across | |
| fields: | |
| - `benchmarks`: stable families such as `swe-bench`, `swe-gym`, `swe-smith`, | |
| `terminal-bench`, `tau2-bench`, `tau3-bench`, `browsecomp`, `mind2web`, and | |
| `toolbench`; | |
| - `source_ids`: exact canonical sources such as `swegym_sampled` or | |
| `agentsuite_tau2`; | |
| - `source_versions`: exact immutable source revisions; | |
| - `agent_models` and `agent_scaffolds`; | |
| - `trajectory_ids`, `task_keys`, and compatible `environment_keys`; | |
| - task-level library `splits`: `train`, `validation`, `test`, or | |
| `protected_evaluation`; | |
| - `quality_tiers` and persisted task/environment `quality_ranks`; | |
| - `demonstration_provenance`: `expert_or_reference_demonstration` or | |
| `recorded_agent_completion`; | |
| - `curated_selections`: pinned original author training selections, enumerated | |
| by `available_curated_selections()`; | |
| - `supported_views`: records must support every requested view (`full_trajectory` | |
| or `assistant_turn`), checked before sampling; | |
| - dynamic `content_availability`: `hosted`, `overlay`, or `metadata_only`; | |
| - audited `research_permissions`, `training_permissions`, | |
| `training_verifications`, `commercial_training_permissions`, and | |
| transformed `redistribution_permissions`; | |
| - `structurally_eligible` and `training_eligible` gates; | |
| - `selection`: `all_attempts`, `all_successful`, or `best_verified`. | |
| The concise string aliases `all`, `successful`, and `best` are also accepted, | |
| as are `full`/`full-trajectory` and `turn`/`assistant-turn` view names. Enum | |
| members are preferred when static typing is available. | |
| `DatasetQuery.for_training(...)` enables both structural and training-source | |
| gates. This quality gate is not a legal-permission decision; combine it with | |
| the permission fields for the downstream project's policy. `best_verified` | |
| returns at most one successful source-evaluator or | |
| independently reproduced trajectory per selected task. Apply an | |
| `environment_keys` filter when alternatives from different environment | |
| versions must not compete. Quality rank itself is always calculated within a | |
| compatible task/environment group over the full canonical population; source | |
| filtering never silently rewrites the stored rank. | |
| `for_training` always excludes `protected_evaluation` task assignments, even | |
| when a training source also contains that task. AReaL's unreconstructed contexts | |
| are explicitly turn-only records: only their source answer is supervised, | |
| earlier assistant messages are context, and full view raises an error. Exact | |
| contiguous AReaL dialogs support both views. See | |
| [v0.5.0 SFT examples and author selections](v0.5.0_sft_expansion.md). | |
| Expert demonstrations and successful agent completions are deliberately | |
| separate filters: | |
| ```python | |
| experts = DatasetQuery( | |
| demonstration_provenance=("expert_or_reference_demonstration",), | |
| ) | |
| successful_agents = DatasetQuery( | |
| demonstration_provenance=("recorded_agent_completion",), | |
| selection=TrajectorySelection.ALL_SUCCESSFUL, | |
| ) | |
| ``` | |
| ## Full-trajectory SFT | |
| ```python | |
| from agent_trajectories import ( | |
| CanonicalDatasetAdapter, | |
| DatasetQuery, | |
| TrainingView, | |
| TrajectorySelection, | |
| ) | |
| dataset = CanonicalDatasetAdapter("data/library") | |
| query = DatasetQuery.for_training( | |
| benchmarks=("swe-gym", "swe-smith"), | |
| splits=("train",), | |
| selection=TrajectorySelection.ALL_SUCCESSFUL, | |
| ) | |
| for example in dataset.iter_examples(query, view=TrainingView.FULL_TRAJECTORY): | |
| row = example.to_dict() | |
| model_input = row["model_input"] | |
| loss_mask = row["loss_mask"] | |
| lineage = row["metadata"]["lineage"] | |
| # Apply a model-specific chat template/tokenizer downstream. | |
| ``` | |
| Each full example has the complete event sequence, assistant-only | |
| `target_event_ids`, and an aligned `loss_mask`. Outcomes, verification evidence | |
| and ranks are in metadata, never in `model_input`. | |
| ## Assistant-turn SFT | |
| ```python | |
| query = DatasetQuery.for_training( | |
| source_ids=("agentsuite_tau2",), | |
| splits=("train",), | |
| ) | |
| for turn in dataset.iter_examples(query, view=TrainingView.ASSISTANT_TURN): | |
| row = turn.to_dict() | |
| assert len(row["context"]) == row["target_index"] | |
| assert row["target_event_id"] == row["metadata"]["lineage"]["turn_id"] | |
| model_input = row["model_input"] # causal prefix only | |
| supervised_target = row["supervised_target"] | |
| ``` | |
| Full and turn views derive from the same canonical record, retain the same task | |
| split and source lineage, and have equivalent assistant targets. Turn context | |
| contains no target event, future observation, later action, outcome, or answer. | |
| ## Best trajectory and multiple completions | |
| Select the best verified trajectory for every selected task: | |
| ```python | |
| best = DatasetQuery( | |
| benchmarks=("swe-bench",), | |
| splits=("protected_evaluation",), | |
| selection=TrajectorySelection.BEST_VERIFIED, | |
| ) | |
| for record in dataset.iter_records(best): | |
| print(record.metadata.task_key, record.metadata.quality_rank) | |
| ``` | |
| Request one exact canonical trajectory: | |
| ```python | |
| record = dataset.get_trajectory("trajectory:...") | |
| print(record.trajectory.events) | |
| print(record.lineage()) | |
| ``` | |
| Collapsed duplicate IDs are resolved to their retained canonical trajectory; | |
| `contributing_trajectory_ids` preserves every original ID. | |
| Enumerate all completions for a task, in quality order: | |
| ```python | |
| first = next(dataset.metadata(DatasetQuery(source_ids=("agentsuite_tau2",)))) | |
| attempts = dataset.alternatives(first.task_key) | |
| for attempt in attempts: | |
| print( | |
| attempt.metadata.trajectory_id, | |
| attempt.metadata.quality_rank, | |
| attempt.metadata.outcome_category, | |
| attempt.metadata.agent_model, | |
| ) | |
| ``` | |
| `environment_key=` can restrict alternatives to one compatible environment. | |
| ## Deterministic sampling | |
| ```python | |
| from agent_trajectories import SamplingConfig, SamplingStrategy | |
| population = DatasetQuery.for_training(splits=("train",)) | |
| # Uniform trajectory sampling. | |
| random_sample = SamplingConfig(count=1_000, seed=42) | |
| # Uniform task sampling; the best matching attempt represents each drawn task. | |
| task_sample = SamplingConfig( | |
| count=1_000, seed=42, strategy=SamplingStrategy.TASK | |
| ) | |
| # Round-robin sources, then sample within each source. | |
| balanced_sample = SamplingConfig( | |
| count=1_000, seed=42, strategy=SamplingStrategy.SOURCE_BALANCED | |
| ) | |
| for record in dataset.iter_records(population, sampling=balanced_sample): | |
| print(record.metadata.trajectory_id, record.metadata.source_id) | |
| ``` | |
| Set `with_replacement=True` for repeated draws. The same persisted library, | |
| query, seed and sampling configuration produce the same ordered IDs. | |
| Task-level sampling prevents tasks with many recorded attempts from dominating. | |
| Source-balanced sampling distributes draws round-robin across non-empty sources | |
| and deterministically redistributes unused capacity when a source is exhausted. | |
| ## Streaming and batching | |
| ```python | |
| for batch in dataset.iter_batches( | |
| 8, | |
| DatasetQuery.for_training(splits=("train",)), | |
| view=TrainingView.ASSISTANT_TURN, | |
| ): | |
| rows = [example.to_dict() for example in batch] | |
| print(len(rows), rows[0]["sample_id"]) | |
| ``` | |
| These are bounded Python batches, not tensors. Canonical storage stays | |
| framework-independent and downstream code retains control of templates, | |
| tokenization, truncation, packing and collation. | |
| PyTorch is optional and imported lazily: | |
| ```python | |
| torch_dataset = dataset.as_torch_iterable( | |
| DatasetQuery.for_training(splits=("train",)), | |
| view=TrainingView.ASSISTANT_TURN, | |
| ) | |
| # Standard torch DataLoader worker processes are sharded by item index. | |
| from torch.utils.data import DataLoader | |
| loader = DataLoader(torch_dataset, batch_size=None, num_workers=2) | |
| ``` | |
| The core package has no ML-framework dependency. Install the optional extra | |
| only when needed: `pip install 'agent-trajectory-datasets[torch]'`. | |
| ## Evaluation over all trajectories | |
| Task splits are assigned once by canonical `task_key`, then joined into every | |
| source and both derived views. A task cannot appear in more than one of | |
| `train`, `validation`, `test`, and `protected_evaluation`. | |
| ```python | |
| evaluation = DatasetQuery( | |
| benchmarks=("tau2-bench",), | |
| splits=("validation", "test", "protected_evaluation"), | |
| selection=TrajectorySelection.ALL_ATTEMPTS, | |
| ) | |
| for record in dataset.iter_records(evaluation): | |
| print(record.metadata.task_key, record.trajectory.outcome.success) | |
| ``` | |
| For all references, source verdicts and verification evidence associated with | |
| one task: | |
| ```python | |
| task = next(dataset.metadata(evaluation)).task_key | |
| bundle = dataset.evaluation_bundle(task, query=evaluation) | |
| for reference in bundle.references: | |
| print( | |
| reference.trajectory_id, | |
| reference.outcome.success, | |
| reference.verification.method, | |
| reference.verification.evidence, | |
| reference.supervised_targets, | |
| ) | |
| ``` | |
| Historical source outcomes are evaluation references, not scores for a new | |
| model. Native environment success still requires running the corresponding | |
| benchmark evaluator. Unknown outcomes remain unknown rather than being counted | |
| as failures. | |
| ## Metadata and lineage | |
| Every `DatasetRecord` carries `TrajectoryMetadata`, including: | |
| - canonical task, trajectory and environment IDs; | |
| - benchmark family, source ID, immutable revision, upstream record locator and | |
| canonical/source split; | |
| - agent model and scaffold; | |
| - quality tier, numeric score and within-task quality rank; | |
| - structural/training eligibility; | |
| - current payload availability and the complete source permission audit, | |
| including verification state, commercial-training status and conditions; | |
| - outcome category, reward, verification method/strength and independent-replay | |
| status; | |
| - every duplicate source trajectory ID collapsed into the canonical record. | |
| `record.lineage()` adds the complete `SourceRef`, producer provenance, source | |
| outcome and full verification evidence. Derived examples store that object at | |
| `example.metadata["lineage"]`; assistant-turn examples also store `turn_id` and | |
| full examples store all supervised `turn_ids`. | |
| ## Federated payloads and authorized overlays | |
| `available_sources()` enumerates the complete indexed inventory; | |
| `content_sources()` lists sources whose event payload is currently readable. | |
| Inspect one permission record without loading trajectories: | |
| ```python | |
| rights = dataset.permissions("agentsuite_tau2") | |
| print(rights.dimensions["model_training"]) | |
| print(dataset.content_availability("agentsuite_tau2")) | |
| ``` | |
| When a project is separately authorized to retrieve a metadata-only source, | |
| run its explicit pinned source adapter and provide the resulting canonical | |
| file or directory as an overlay: | |
| ```python | |
| dataset = CanonicalDatasetAdapter( | |
| "./sft-benchmark-trajectories", | |
| content_overlays={ | |
| "agentsuite_tau2": "./authorized/canonical/agentsuite_tau2", | |
| }, | |
| ) | |
| query = DatasetQuery( | |
| source_ids=("agentsuite_tau2",), | |
| content_availability=("overlay",), | |
| ) | |
| for record in dataset.iter_records(query): | |
| ... | |
| ``` | |
| The overlay is read-only and is not copied or uploaded. Canonical IDs join it | |
| to the hosted full-inventory index. Selecting records whose payload is still | |
| absent raises `MissingTrajectoryContentError` with the missing source IDs; | |
| metadata queries never silently discard them. | |
| ## Initial ingestion and explicit refresh | |
| Normal consumption performs no downloads. Initial ingestion is a separate, | |
| explicit operation. For a hosted release: | |
| ```bash | |
| .venv/bin/python scripts/import_hf_release.py SOURCE_ID DATASET_ID \ | |
| --revision IMMUTABLE_SHA \ | |
| --output data/full/canonical/OUTPUT \ | |
| --cache data/cache/full/OUTPUT \ | |
| --config CONFIG --split SPLIT | |
| .venv/bin/python scripts/build_complete_library.py \ | |
| --input-dir data/full/canonical/OUTPUT \ | |
| --output data/library | |
| ``` | |
| The complete multi-source build command and source-specific revisions are in | |
| the root README and `docs/trajectory_sources.md`. | |
| A refresh is never implicit. Choose and audit a new upstream immutable SHA and | |
| write it to a new canonical output directory. For an existing published | |
| library, use the append workflow; it copies the old SQLite index, reads only | |
| the new canonical shards, preserves all old score rows and shard bytes, and | |
| updates only affected task assignments: | |
| ```bash | |
| .venv/bin/python scripts/import_hf_release.py SOURCE_ID DATASET_ID \ | |
| --revision NEW_IMMUTABLE_SHA \ | |
| --output data/full/canonical/OUTPUT_NEW_SHA \ | |
| --cache data/cache/full/OUTPUT_NEW_SHA \ | |
| --config CONFIG --split SPLIT | |
| # Review release-manifest.json and rejects before appending. | |
| .venv/bin/python scripts/append_library.py \ | |
| --base data/library \ | |
| --input-dir data/increment-v0.4.0/canonical \ | |
| --output data/library-v0.4.0 \ | |
| --release v0.4.0 | |
| ``` | |
| `append_report.json` explicitly records the base manifest hash, accepted and | |
| duplicate counts, affected tasks, and that base scores and shards were not | |
| reprocessed. This separation makes changes reviewable and keeps training runs | |
| pinned to the manifest and shard hashes they actually consumed. | |