Datasets:

Modalities:
Image
Text
Formats:
parquet
Languages:
Danish
ArXiv:
License:
V4ldeLund's picture
Updated euro-multisynth-and-human-da (#8)
7850f31
Raw History Blame Contribute Delete
9.85 kB
"""Build the da-human-instruct constituent of the Danish dyna-instruct collection.
Source: V4ldeLund/da-human-instruct
Revision: 012978f0c7b64a46177364e1991b96ac15dc62b2
The release is a Danish extract of two human-model conversation collections: the
Danish-labelled conversations of `allenai/WildChat-4.8M` (ODC-BY) and of
`ministere-culture/comparia-conversations` (Etalab 2.0). Its card excludes the
non-redistributable LMSYS-Chat-1M extension and that extension is not fetched, read
or converted here. The pinned Parquet shard publishes 2,633 conversations, not the
2,631 the card states; the shard itself is authoritative for this conversion.
Conversion ships every released conversation that ends on an assistant turn with
text, with every released user and assistant turn copied verbatim: no prompt
rewrite, quality, privacy, language, length or punctuation filtering, and no
de-duplication, so conversations that are also present in `ai-arena` stay in both
constituents. The shared schema requires a non-empty message list whose final
message is an assistant turn, so conversations that end on a user turn are excluded
for that structural reason and counted in the build report; nothing is fabricated to
fill a missing reply. The `source` and `model` columns are outside the shared chat
schema and are dropped; the contributing collection of each row is recorded in the
attribution notice instead. Staging files live in `tmp/<source>/` and the converter
deletes only the files it created there.
"""
from __future__ import annotations
import hashlib
import json
import logging
import os
from collections import Counter
from pathlib import Path
from typing import Any
import pyarrow as pa
import pyarrow.parquet as pq
from datasets import Dataset, load_dataset
from huggingface_hub import hf_hub_download
from dynainst.dataset_structure import SampleSchema
from dynainst.process_dataset import (
add_token_count,
ensure_column_order,
remove_empty_messages,
)
logger = logging.getLogger(__name__)
SOURCE = "da-human-instruct"
HF_DATASET = "V4ldeLund/da-human-instruct"
REVISION = "012978f0c7b64a46177364e1991b96ac15dc62b2"
SHARD_PATH = "data/train-00000-of-00001.parquet"
SHARD_SHA256 = "831326cc6b0e6c01e81b44ebf6e981f129cfc69a2c7638f08e623c2aacd41d88"
EXPECTED_ROWS = 2_633
ADDED = "2026-11-16"
TARGET_LANGUAGE = "dan"
TASK = "general"
# The release publishes no per-conversation timestamp. `created` spans the
# contributing collections at year-level start, from the beginning of the WildChat
# chat collection in 2023, through the pinned revision's upload date of the derivative.
CREATED_START = "2023-01-01"
CREATED_END = "2026-01-03"
TOKENIZER_NAME = "AI-Sweden-Models/Llama-3-8B-instruct"
TOKENIZER_REVISION = "88546994bd2b86c823a8f12238ac9236221979eb"
SAVE_DIR = Path(__file__).parent
TMP_DIR = SAVE_DIR.parents[1] / "tmp"
STAGING_DIR = TMP_DIR / SOURCE
ROWS_SCHEMA = pa.schema(
[
pa.field("id", pa.string()),
pa.field(
"messages",
pa.list_(
pa.struct(
[pa.field("role", pa.string()), pa.field("content", pa.string())]
)
),
),
pa.field("source", pa.string()),
pa.field("added", pa.string()),
pa.field("created", pa.string()),
pa.field("language", pa.list_(pa.string())),
pa.field("task", pa.string()),
pa.field("token_count", pa.int64()),
]
)
BATCH_SIZE = 2_000
def sha256(path: Path) -> str:
"""Return the SHA-256 digest of a file."""
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def source_path(relative_path: str) -> Path:
"""Download a pinned source file and return its local path."""
return Path(
hf_hub_download(
repo_id=HF_DATASET,
repo_type="dataset",
filename=relative_path,
revision=REVISION,
)
)
def convert(
raw: dict[str, Any], position: int, skipped: Counter
) -> dict[str, Any] | None:
"""Copy one released conversation into the shared chat schema."""
released = raw["messages"]
if not released:
skipped["empty_conversation"] += 1
return None
final = released[-1]
if final["role"] != "assistant" or not (final["content"] or "").strip():
skipped["ends_without_final_assistant_answer"] += 1
return None
messages = []
for message in released:
role = message["role"]
content = message["content"]
if role not in {"user", "assistant", "system"}:
raise ValueError(f"Row {position} has unexpected role {role!r}")
if not isinstance(content, str) or not content.strip():
raise ValueError(f"Row {position} has empty {role} content")
messages.append({"role": role, "content": content})
if not any(message["role"] == "user" for message in messages):
raise ValueError(f"Row {position} carries no user turn")
return {
"id": f"{SOURCE}_{position:05d}",
"messages": messages,
"source": SOURCE,
"added": ADDED,
"created": f"{CREATED_START}, {CREATED_END}",
"language": [TARGET_LANGUAGE],
"task": TASK,
"token_count": -1,
}
def stage_source(output_path: Path) -> dict[str, Any]:
"""Stream the pinned shard into an intermediate Parquet file."""
if output_path.exists():
output_path.unlink()
shard_path = source_path(SHARD_PATH)
digest = sha256(shard_path)
if digest != SHARD_SHA256:
raise ValueError(f"Checksum mismatch for {SHARD_PATH}: {digest}")
rows_exported = 0
skipped: Counter[str] = Counter()
released_sources: Counter[str] = Counter()
retained_sources: Counter[str] = Counter()
writer = pq.ParquetWriter(output_path, ROWS_SCHEMA, compression="zstd")
batch: list[dict[str, Any]] = []
try:
parquet_file = pq.ParquetFile(shard_path)
for record_batch in parquet_file.iter_batches(batch_size=BATCH_SIZE):
for raw in record_batch.to_pylist():
position = rows_exported
rows_exported += 1
released_sources[raw["source"]] += 1
row = convert(raw, position, skipped)
if row is None:
continue
retained_sources[raw["source"]] += 1
batch.append(row)
if len(batch) >= BATCH_SIZE:
writer.write_table(pa.Table.from_pylist(batch, schema=ROWS_SCHEMA))
batch.clear()
if batch:
writer.write_table(pa.Table.from_pylist(batch, schema=ROWS_SCHEMA))
batch.clear()
finally:
writer.close()
if rows_exported != EXPECTED_ROWS:
raise ValueError(f"Read {rows_exported:,} rows, expected {EXPECTED_ROWS:,}")
return {
"rows_exported": rows_exported,
"released_sources": dict(sorted(released_sources.items())),
"retained_sources": dict(sorted(retained_sources.items())),
"skipped": dict(sorted(skipped.items())),
}
def cleanup_staging(intermediate_path: Path) -> None:
"""Remove only the staging files this converter created."""
staging_dir = intermediate_path.parent
if intermediate_path.exists():
intermediate_path.unlink()
for leftover in staging_dir.glob(f"{SOURCE}_*"):
leftover.unlink()
try:
staging_dir.rmdir()
except OSError:
logger.info("Left foreign files in %s; not removing the directory", staging_dir)
def main() -> None:
logging.basicConfig(level=logging.INFO, format="%(message)s")
STAGING_DIR.mkdir(parents=True, exist_ok=True)
intermediate_path = STAGING_DIR / f"{SOURCE}_rows.parquet"
report = stage_source(intermediate_path)
logger.info("Exported %d rows", sum(report["retained_sources"].values()))
dataset: Dataset = load_dataset(
"parquet",
data_files=str(intermediate_path),
split="train",
) # type: ignore[assignment]
for row in dataset:
SampleSchema(**row)
dataset = remove_empty_messages(dataset, num_proc=1)
dataset = add_token_count(
dataset,
tokenizer_name=TOKENIZER_NAME,
tokenizer_revision=TOKENIZER_REVISION,
num_proc=1,
)
dataset = ensure_column_order(dataset)
identifiers = dataset["id"]
if len(identifiers) != len(set(identifiers)):
raise ValueError("Converted dataset contains duplicate IDs")
expected = sum(report["retained_sources"].values())
if len(dataset) != expected:
raise ValueError(f"Retained {len(dataset):,} rows, expected {expected:,}")
for row in dataset:
sample = SampleSchema(**row)
if sample.token_count <= 0:
raise ValueError(f"Sample {sample.id} has a non-positive token count")
output_path = SAVE_DIR / f"{SOURCE}.parquet"
staged_output = STAGING_DIR / output_path.name
if staged_output.exists():
staged_output.unlink()
dataset.to_parquet(str(staged_output))
if pq.read_metadata(staged_output).num_rows != len(dataset):
raise RuntimeError("Staged Parquet row count does not match the dataset")
if not pq.read_schema(staged_output).equals(ROWS_SCHEMA, check_metadata=False):
raise RuntimeError("Staged Parquet schema does not match the expected schema")
os.replace(staged_output, output_path)
cleanup_staging(intermediate_path)
report["rows_retained"] = len(dataset)
report["tokens_total"] = int(sum(dataset["token_count"]))
print(json.dumps(report, indent=2, sort_keys=True))
print(f"Wrote {len(dataset):,} samples to {output_path}")
if __name__ == "__main__":
main()