skip to content

In Hugging Face Datasets, what does with_format('torch') change about the rows a tokenized Dataset returns, and what does it leave alone?

level: juniorimportance: should knowfreq 15%

answer

  1. formatting on read, not a rewrite
  2. numbers become tensors, strings do not
  3. ragged columns stay a list
  4. columns= limits what comes out
  5. with_format new, set_format in place

basics

~20 s

with_format('torch') converts numeric columns to PyTorch tensors when rows are read, leaving the Arrow data unchanged. Strings stay strings, ragged columns come back as lists of tensors rather than one padded tensor, and columns= limits the output.

solid answer

~40 s

`with_format("torch")` sets an **output format** applied on the fly in `__getitem__` and iteration; the Arrow table on disk is not rewritten and nothing is recomputed. Integer columns become `int64` tensors and float columns `float32`; string and binary columns are returned unchanged. A slice or batch is stacked into one tensor only when every row has the same shape, so variable-length `input_ids` come back as a list of tensors: you pad in `map` or in the collate step. `columns=["input_ids", "attention_mask", "label"]` restricts the output (and `output_all_columns=True` keeps the rest as Python objects). `with_format` returns a new dataset; `set_format` changes this one in place; `with_format(None)` or `reset_format()` restores Python objects. The formatted dataset can be handed straight to a PyTorch `DataLoader`.

code

python · 13 lines
python
from datasets import Dataset

ds = Dataset.from_dict({
    "text": ["short", "a longer example"],
    "input_ids": [[101, 2460, 102], [101, 1037, 2936, 2742, 102]],
    "label": [0, 1],
})

torch_ds = ds.with_format("torch", columns=["input_ids", "label"])
print(torch_ds[0])                # input_ids and label as tensors, no text
print(torch_ds[:2]["label"])      # one tensor: same shape, stacked
print(torch_ds[:2]["input_ids"])  # list of two tensors: ragged, not padded
print(ds[0]["text"])              # original dataset is unchanged

go deeper

for a junior

Recall that with_format('torch') makes rows come back as tensors and that set_format does the same in place.

for a middle

Explain the on-the-fly conversion: default int64 and float32 dtypes, strings untouched, columns= and output_all_columns, and why ragged columns come back as lists.

for a senior

Debug the hand-off to a training loop: leftover string columns, unpadded ragged rows, padding at tokenization versus per batch, and keeping only the model's input columns.

for a principal

Decide where tensor conversion and padding live in a shared pipeline so every consumer formats the same prepared columns without each team re-tokenizing.

## What a format is Rows from a Hugging Face **Datasets** `Dataset` come back as plain Python objects by default: integers, floats, strings and lists. A **format** tells the dataset to convert rows into another type at the moment they are read. `with_format("torch")` selects PyTorch tensors; the same method accepts `"numpy"`, `"pandas"`, `"polars"`, `"arrow"` and others. The key word is **on the fly**. Formatting does not rewrite the Arrow table, does not create a cache file and does not change the dataset's contents. It changes only what `ds[i]`, `ds[a:b]` and iteration hand back. That is why it is cheap to switch formats and why it is the last step of preprocessing, after `map` has produced the columns you need. ## What changes - **Numeric columns become tensors**: integers default to `torch.int64` and floats to `torch.float32`, so a `float64` feature arrives as 32-bit. - **Fixed-shape slices are stacked**: `ds[:32]["label"]` is one tensor of shape `[32]`; a column declared with an `Array2D` feature stacks into a 3-D tensor. - **`ClassLabel`, `Image` and `Audio` features** convert too: labels to integer tensors, images to `uint8` tensors. - **Device placement**: on a map-style `Dataset`, `with_format("torch", device=device)` passes the device through to tensor creation, as the PyTorch usage guide shows. ## What stays the same - **Strings and binary values are returned unchanged**, because tensors hold only numbers. A leftover `text` column still comes out as Python strings and will trip a default collate step. - **Ragged columns are not padded.** If rows have different lengths, as tokenized `input_ids` usually do, a slice returns a **list of 1-D tensors** instead of one 2-D tensor. The dataset never invents padding values. - **The data on disk and the fingerprint** of the underlying table: no transform ran. - **Columns you hide**: a column left out of `columns=` is still in the table, so `ds.column_names` lists it and `with_format(None)` brings it back. The ragged-column rule is the one that surprises people in practice. A batch of eight tokenized rows of lengths 12 to 512 cannot become one rectangular tensor without choosing a padding value and a side, and those choices belong to the tokenizer and the model, not to the dataset. So the dataset returns exactly what it stores, as tensors, and leaves the shaping to the step that knows the pad token. ## Choosing the output columns The usual sequence for a classification fine-tune looks like this: 1. Tokenize with `map(..., batched=True)`, producing `input_ids` and `attention_mask`. 2. Drop raw text with `remove_columns=["text"]` in that `map`, or `remove_columns()` afterwards. 3. Call `with_format("torch", columns=["input_ids", "attention_mask", "label"])`. 4. Pad either during tokenization (`padding="max_length"`, wasteful for short rows) or per batch in the collate step, which is where dynamic padding belongs. 5. Hand the dataset to a PyTorch `DataLoader`. `columns=` lists which columns come out; other columns are hidden, not deleted. `output_all_columns=True` returns the unformatted columns as well, as Python objects, which helps when you need an id next to the tensors. ## with_format, set_format and friends | Call | Returns | Effect | |---|---|---| | `ds.with_format("torch")` | a new `Dataset` | the original keeps its format | | `ds.set_format("torch")` | nothing | changes `ds` in place | | `ds.with_format(None)` / `ds.reset_format()` | new / in place | back to Python objects | | `ds.with_transform(fn)` | a new `Dataset` | runs your own function at read time, replacing any format | Inspect the current state with `ds.format`, which shows the type, columns and options. Formats also carry through later operations: a `map` on a formatted dataset receives formatted batches, which is why a `"pandas"` or `"numpy"` format can speed up a numeric `map`, and why a `"torch"` format can surprise a function that expects Python lists. On a streaming `IterableDataset`, `with_format("torch")` also works and formats rows as they stream, but it takes only the format type. ## Why not convert by hand Calling `torch.tensor()` on every row inside a training loop copies data twice and turns every batch into Python lists first. The Arrow-backed formatter reads columns directly from the table and converts them in bulk, so letting the dataset format is both faster and less code. The remaining work, turning a list of variable-length tensors into one padded batch and spreading reading across worker processes, belongs to the PyTorch data-loading side and the tokenizer's padding options.

  • Your DataLoader fails with a stacking error after with_format('torch') in Hugging Face Datasets. What is the likely cause?
    The `input_ids` rows have different lengths, so the dataset returns separate tensors and the default collate step cannot stack them. Either pad to a fixed length during tokenization, or keep variable lengths and pad per batch in a collate function, which wastes less compute on short rows.
  • When would you use with_transform() instead of with_format() in Hugging Face Datasets?
    When the conversion is your own code, such as tokenizing or augmenting at read time instead of storing the result. `with_transform` runs your function on each accessed batch and replaces any format. It saves disk and allows random augmentation, but the work repeats on every read and is never cached.

  • with_format('torch') rewrites the Arrow cache as tensors
  • with_format('torch') pads ragged input_ids into one tensor automatically
  • String columns are encoded to tensors by with_format('torch')
  • set_format and with_format both return a new dataset
  • Columns not listed in columns= are deleted from the dataset