MCPcopy Create free account
hub / github.com/FreeformRobotics/OTS / default_collate

Function default_collate

lib/utils/data/dataloader.py:104–142  ·  view source on GitHub ↗

Puts each data field into a tensor with outer dimension batch size

(batch)

Source from the content-addressed store, hash-verified

102
103
104def default_collate(batch):
105 "Puts each data field into a tensor with outer dimension batch size"
106
107 error_msg = "batch must contain tensors, numbers, dicts or lists; found {}"
108 elem_type = type(batch[0])
109 if torch.is_tensor(batch[0]):
110 out = None
111 if _use_shared_memory:
112 # If we're in a background process, concatenate directly into a
113 # shared memory tensor to avoid an extra copy
114 numel = sum([x.numel() for x in batch])
115 storage = batch[0].storage()._new_shared(numel)
116 out = batch[0].new(storage)
117 return torch.stack(batch, 0, out=out)
118 elif elem_type.__module__ == 'numpy' and elem_type.__name__ != 'str_' \
119 and elem_type.__name__ != 'string_':
120 elem = batch[0]
121 if elem_type.__name__ == 'ndarray':
122 # array of string classes and object
123 if re.search('[SaUO]', elem.dtype.str) is not None:
124 raise TypeError(error_msg.format(elem.dtype))
125
126 return torch.stack([torch.from_numpy(b) for b in batch], 0)
127 if elem.shape == (): # scalars
128 py_type = float if elem.dtype.name.startswith('float') else int
129 return numpy_type_map[elem.dtype.name](list(map(py_type, batch)))
130 elif isinstance(batch[0], int_classes):
131 return torch.LongTensor(batch)
132 elif isinstance(batch[0], float):
133 return torch.DoubleTensor(batch)
134 elif isinstance(batch[0], string_classes):
135 return batch
136 elif isinstance(batch[0], collections.Mapping):
137 return {key: default_collate([d[key] for d in batch]) for key in batch[0]}
138 elif isinstance(batch[0], collections.Sequence):
139 transposed = zip(*batch)
140 return [default_collate(samples) for samples in transposed]
141
142 raise TypeError((error_msg.format(type(batch[0]))))
143
144
145def pin_memory_batch(batch):

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected