fn
default_collate
→Tensor or list or dict or tupledefault_collate(batch: list[object])Collate a list of samples into a batched tensor or nested structure.
The default collate_fn used by DataLoader. Walks the
first element of batch to decide how to combine the remaining
elements, preserving the original nested container structure.
Parameters
batchlist of objectSamples (one per dataset item) to combine into a single batch.
Every element must share the same structure / type as
batch[0].Returns
Tensor or list or dict or tupleTensorleaves → stacked along a new leading axis.np.ndarrayleaves → stacked then wrapped asTensor(numpy bridge —DataLoaderis an H4 carve-out).int/floatleaves → 1-DTensor.str/bytesleaves → kept as a Python list.dict/list/tuple/NamedTuplecontainers → walked recursively; original container type is preserved.
Notes
The recursion is structural: a batch of {"x": Tensor, "y": int}
becomes {"x": stacked_Tensor, "y": 1d_Tensor} of the same dict
shape. Heterogeneous batches (different keys / shapes) are not
supported — callers must normalise upstream.
Examples
>>> default_collate([(t1, 0), (t2, 1), (t3, 2)])
(<Tensor shape=(3, ...)>, <Tensor shape=(3,)>)