Are you going to prepare the Emilia-Yodas dataset?

#2
by kadirnar - opened

Can you share the sample code for this process? I want to do this for other languages and Emilia-Yodas.

Something like this should work for the base dataset + YODAS with all langs:

# /// script
# requires-python = ">=3.12"
# dependencies = ["huggingface_hub", "datasets", "torchcodec", "soundfile", "torch", "snac", "tqdm", "pyarrow"]
# ///
import argparse
import os
from fnmatch import fnmatch

import pyarrow as pa
import pyarrow.parquet as pq
import torch
from datasets import Audio, Features, disable_progress_bars, load_dataset
from huggingface_hub import list_repo_files
from snac import SNAC
from torch.utils.data import DataLoader
from tqdm import tqdm


def as_chunks(my_list, chunk_size):
    for i in range(0, len(my_list), chunk_size):
        yield my_list[i : i + chunk_size]


def convert(r):
    id = "_id" if "_id" in r["json"] else "id"

    return {
        "id": r["json"][id],
        "language": r["json"]["language"],
        "speaker": r["json"]["speaker"],
        "text": r["json"]["text"].strip(),
        "audio": r["mp3"].get_all_samples().data,
    }


def load_shard(data_files, num_workers, streaming=True):
    cols = ["json", "__key__", "__url__", "mp3"]
    feat = Features({"mp3": Audio(sampling_rate=24000, decode=True)})
    ds = load_dataset("amphion/Emilia-Dataset", data_files=data_files, streaming=streaming)["train"]
    ds = ds.map(convert, remove_columns=cols, features=feat)
    dl = DataLoader(
        ds, batch_size=256, num_workers=num_workers, pin_memory=True, collate_fn=lambda rows: rows
    )
    return dl




@torch
	.compile()
def encode(codec, audio):
    return codec.encode(audio)




@torch
	.inference_mode()
def process_shard(codec, schema, path, shard, num_workers, pbar):
    pbar.write(path)
    wr = pq.ParquetWriter(path, schema=schema)

    with torch.autocast(device_type="cuda"):
        for batch in load_shard(shard, num_workers, streaming=True):
            for row in batch:
                codes = encode(codec, row["audio"].to(device="cuda", non_blocking=True).unsqueeze(0))
                del row["audio"]
                row["c_12"] = codes[0].flatten().tolist()
                row["c_24"] = codes[1].flatten().tolist()
                row["c_48"] = codes[2].flatten().tolist()

            table = pa.Table.from_pylist(batch, schema=schema)
            wr.write_table(table, row_group_size=args.row_group_size)
            pbar.update(len(batch))

    wr.close()


def main(args) -> None:
    disable_progress_bars()  # so datasets dont spam us with per shard bars
    torch.set_float32_matmul_precision("medium")  # gotta go fast

    codec = SNAC.from_pretrained("hubertsiuzdak/snac_24khz").to(device="cuda").eval()

    paths = list_repo_files("amphion/Emilia-Dataset", repo_type="dataset")
    pbar = tqdm(total=54_792_590, unit="rows")  # total taken from estimate on the hf repo

    schema = {
        "id": pa.string(),
        "language": pa.string(),
        "speaker": pa.string(),
        "text": pa.string(),
        "c_12": pa.list_(pa.int16()),
        "c_24": pa.list_(pa.int16()),
        "c_48": pa.list_(pa.int16()),
    }

    schema = pa.schema(schema)

    for lang in ["DE", "EN", "FR", "JA", "KO", "ZH"]:
        os.makedirs(f"{args.path}/Emilia/{lang}", exist_ok=True)
        shards = list(as_chunks([p for p in paths if fnmatch(p, f"Emilia/{lang}/*.tar")], args.chunk))

        for i, shard in enumerate(shards):
            path = f"{args.path}/Emilia/{lang}/{lang}-{i:03d}-of-{len(shards) - 1:03d}.parquet"
            process_shard(codec, schema, path, shard, args.chunk, pbar)

        os.makedirs(f"{args.path}/Emilia-YODAS/{lang}", exist_ok=True)
        shards = list(as_chunks([p for p in paths if fnmatch(p, f"Emilia-YODAS/{lang}/*.tar")], args.chunk))

        for i, shard in enumerate(shards):
            path = f"{args.path}/Emilia-YODAS/{lang}/{lang}-{i:03d}-of-{len(shards) - 1:03d}.parquet"
            process_shard(codec, schema, path, shard, args.chunk, pbar)

    pbar.close()


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--row-group-size", type=int, default=200, help="parquet row group size")
    parser.add_argument("--chunk", type=int, default=8, help="src shards per dst shard (concurrency)")
    parser.add_argument("--path", default=".", help="output path")
    args = parser.parse_args()

    main(args)

The output format is a bit diff from what I have in this repo but is better. Multiple shards so can be read with n>1 workers afterward, and has more of the original metadata apart from just transcripts. Can also add dnsmos, duration and phone_count if you want those.

Thanks. Have you ever tried training? I’ve tried training with the qwen3 and SmolLM3 models. However, I’m getting an error related to the snac model during the inference stage. Could there be an issue with the dataset?

Yes I've trained on this dataset, and it roundtrips through SNAC as well. I would assume the issue is in transformation from SNAC ids -> tokenizer -> SNAC ids for your architecture. This dataset is not specialized to any particular frame layout or tokenizer offset, it is raw SNAC codes as they come out of SNAC.

Sign up or log in to comment