dataset.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. ## @package dataset
  2. # Module caffe2.python.dataset
  3. """
  4. Implementation of an in-memory dataset with structured schema.
  5. Use this to store and iterate through datasets with complex schema that
  6. fit in memory.
  7. Iterating through entries of this dataset is very fast since the dataset
  8. is stored as a set of native Caffe2 tensors, thus no type conversion or
  9. deserialization is necessary.
  10. """
  11. from caffe2.python import core, workspace
  12. from caffe2.python.dataio import Reader, Writer
  13. from caffe2.python.schema import (
  14. Struct, from_blob_list, from_column_list, InitEmptyRecord)
  15. import numpy as np
  16. class _DatasetReader(Reader):
  17. def __init__(self, dataset, name, batch_size=1, enforce_batch_size=False):
  18. """Don't call this directly. Instead, use dataset.reader()"""
  19. Reader.__init__(self, dataset.content())
  20. self.dataset = dataset
  21. self.name = name or (dataset.name + '_cursor')
  22. self.batch_size = batch_size
  23. self.enforce_batch_size = enforce_batch_size
  24. self.cursor = None
  25. def setup_ex(self, init_net, exit_net):
  26. if self.cursor is None:
  27. self.cursor = init_net.CreateTreeCursor(
  28. [],
  29. init_net.NextScopedBlob(self.name),
  30. fields=self.dataset.fields)
  31. def read(self, read_net):
  32. assert self.cursor, 'setup not called.'
  33. content = self.dataset.content()
  34. with core.NameScope(read_net.NextName(self.name)):
  35. fields = read_net.ReadNextBatch(
  36. [self.cursor] + content.field_blobs(),
  37. content.field_names(),
  38. batch_size=self.batch_size,
  39. enforce_batch_size=self.enforce_batch_size)
  40. fields = core.output_to_list(fields)
  41. return (read_net.IsEmpty([fields[0]]), fields)
  42. def reset(self, net):
  43. net.ResetCursor([self.cursor], [])
  44. class _DatasetRandomReader(Reader):
  45. def __init__(self, dataset, name, indices, batch_size=1, loop_over=False,
  46. enforce_batch_size=False):
  47. """Don't call this directly. Instead, use dataset.random_reader()"""
  48. Reader.__init__(self, dataset.content())
  49. self.dataset = dataset
  50. self.cursor = None
  51. self.name = name or (dataset.name + '_cursor')
  52. self.indices = indices
  53. self.batch_size = batch_size
  54. self.loop_over = loop_over
  55. self.enforce_batch_size = enforce_batch_size
  56. def setup_ex(self, init_net, exit_net):
  57. if self.cursor is None:
  58. self.cursor = init_net.CreateTreeCursor(
  59. [],
  60. init_net.NextScopedBlob(self.name),
  61. fields=self.dataset.fields)
  62. def reset(self, net):
  63. net.ResetCursor([self.cursor], [])
  64. def computeoffset(self, net):
  65. self.reset(net)
  66. offsets = net.ComputeOffset(
  67. [self.cursor] + self.dataset.content().field_blobs(),
  68. 'offsets')
  69. self.offsets = offsets
  70. def sort_and_shuffle(self, net, sort_by_field=None,
  71. shuffle_size=1, batch_size=1):
  72. # no sorting by default
  73. content = self.dataset.content()
  74. sort_by_field_idx = -1
  75. if sort_by_field:
  76. assert sort_by_field in content.field_names(), (
  77. 'Must be valid field.')
  78. sort_by_field_idx = content.field_names().index(sort_by_field)
  79. self.reset(net)
  80. indices = net.SortAndShuffle(
  81. [self.cursor] + content.field_blobs(),
  82. 'indices',
  83. sort_by_field_idx=sort_by_field_idx,
  84. shuffle_size=shuffle_size,
  85. batch_size=batch_size)
  86. self.indices = indices
  87. def read(self, read_net):
  88. assert self.cursor, 'setup_ex not called'
  89. assert self.indices, 'sort_and_shuffle not called'
  90. assert self.offsets, 'computeoffset not called'
  91. content = self.dataset.content()
  92. with core.NameScope(read_net.NextName(self.name)):
  93. fields = read_net.ReadRandomBatch(
  94. [self.cursor, self.indices, self.offsets] + (
  95. content.field_blobs()),
  96. content.field_names(),
  97. batch_size=self.batch_size,
  98. enforce_batch_size=self.enforce_batch_size,
  99. loop_over=self.loop_over)
  100. fields = core.output_to_list(fields)
  101. return (read_net.IsEmpty([fields[0]]), fields)
  102. class _DatasetWriter(Writer):
  103. def __init__(self, content):
  104. """Don't call this directly. Use dataset.writer() instead."""
  105. self._content = content
  106. self.mutex = None
  107. def setup_ex(self, init_net, exit_net):
  108. if self.mutex is None:
  109. self.mutex = init_net.CreateMutex([])
  110. def write(self, writer_net, fields):
  111. """
  112. Add operations to `net` that append the blobs in `fields` to the end
  113. of the dataset. An additional operator will also be added that checks
  114. the consistency of the data in `fields` against the dataset schema.
  115. Args:
  116. writer_net: The net that will contain the Append operators.
  117. fields: A list of BlobReference to be appeneded to this dataset.
  118. """
  119. assert self.mutex is not None, 'setup not called.'
  120. field_blobs = self._content.field_blobs()
  121. assert len(fields) == len(field_blobs), (
  122. 'Expected %s fields, got %s.' % (len(field_blobs), len(fields)))
  123. writer_net.CheckDatasetConsistency(
  124. fields, [], fields=self._content.field_names())
  125. writer_net.AtomicAppend(
  126. [self.mutex] + field_blobs + list(fields),
  127. field_blobs)
  128. def commit(self, finish_net):
  129. """Commit is a no-op for an in-memory dataset."""
  130. pass
  131. def Const(net, value, dtype=None, name=None):
  132. """
  133. Create a 'constant' by first creating an external input in the given
  134. net, and then feeding the corresponding blob with its provided value
  135. in the current workspace. The name is automatically generated in order
  136. to avoid clashes with existing blob names.
  137. """
  138. assert isinstance(net, core.Net), 'net must be a core.Net instance.'
  139. value = np.array(value, dtype=dtype)
  140. blob = net.AddExternalInput(net.NextName(prefix=name))
  141. workspace.FeedBlob(str(blob), value)
  142. return blob
  143. def execution_step_with_progress(name, init_net, substeps, rows_read):
  144. # progress reporter
  145. report_net = core.Net('report_net')
  146. report_net.Print([rows_read], [])
  147. return core.execution_step(
  148. name,
  149. substeps,
  150. report_net=report_net,
  151. concurrent_substeps=True,
  152. report_interval=5)
  153. class Dataset(object):
  154. """Represents an in-memory dataset with fixed schema.
  155. Use this to store and iterate through datasets with complex schema that
  156. fit in memory.
  157. Iterating through entries of this dataset is very fast since the dataset
  158. is stored as a set of native Caffe2 tensors, thus no type conversion or
  159. deserialization is necessary.
  160. """
  161. def __init__(self, fields, name=None):
  162. """Create an un-initialized dataset with schema provided by `fields`.
  163. Before this dataset can be used, it must be initialized, either by
  164. `init_empty` or `init_from_dataframe`.
  165. Args:
  166. fields: either a schema.Struct or a list of field names in a format
  167. compatible with the one described in schema.py.
  168. name: optional name to prepend to blobs that will store the data.
  169. """
  170. assert isinstance(fields, list) or isinstance(fields, Struct), (
  171. 'fields must be either a Struct or a list of raw field names.')
  172. if isinstance(fields, list):
  173. fields = from_column_list(fields)
  174. self.schema = fields
  175. self.fields = fields.field_names()
  176. self.field_types = fields.field_types()
  177. self.name = name or 'dataset'
  178. self.field_blobs = fields.field_blobs() if fields.has_blobs() else None
  179. def trim(self, net, multiple_of):
  180. """
  181. Trims the contents of this dataset so that the number of records is
  182. multiple of the given argument.
  183. """
  184. net.TrimDataset(
  185. self.field_blobs,
  186. self.field_blobs,
  187. fields=self.fields,
  188. multiple_of=multiple_of)
  189. def init_empty(self, init_net):
  190. """Initialize the blobs for this dataset with empty values.
  191. Empty arrays will be immediately fed into the current workspace,
  192. and `init_net` will take those blobs as external inputs.
  193. """
  194. self.field_blobs = InitEmptyRecord(
  195. init_net, self.schema.clone_schema()).field_blobs()
  196. def init_from_dataframe(self, net, dataframe):
  197. """Initialize the blobs for this dataset from a Pandas dataframe.
  198. Each column of the dataframe will be immediately fed into the current
  199. workspace, and the `net` will take this blobs as external inputs.
  200. """
  201. assert len(self.fields) == len(dataframe.columns)
  202. self.field_blobs = [
  203. Const(net, dataframe.as_matrix([col]).flatten(), name=field)
  204. for col, field in enumerate(self.fields)]
  205. def get_blobs(self):
  206. """
  207. Return the list of BlobReference pointing to the blobs that contain
  208. the data for this dataset.
  209. """
  210. assert self
  211. return self.field_blobs
  212. def content(self):
  213. """
  214. Return a Record of BlobReferences pointing to the full content of
  215. this dataset.
  216. """
  217. return from_blob_list(self.schema, self.field_blobs)
  218. def field_names(self):
  219. """Return the list of field names for this dataset."""
  220. return self.fields
  221. def field_types(self):
  222. """
  223. Return the list of field dtypes for this dataset.
  224. If a list of strings, not a schema.Struct, was passed to the
  225. constructor, this will return a list of dtype(np.void).
  226. """
  227. return self.field_types
  228. def reader(self, init_net=None, cursor_name=None, batch_size=1,
  229. enforce_batch_size=False):
  230. """Create a Reader object that is used to iterate through the dataset.
  231. This will append operations to `init_net` that create a TreeCursor,
  232. used to iterate through the data.
  233. NOTE: Currently, it is not safe to append to a dataset while reading.
  234. Args:
  235. init_net: net that will be run once to create the cursor.
  236. cursor_name: optional name for the blob containing a pointer
  237. to the cursor.
  238. batch_size: how many samples to read per iteration.
  239. Returns:
  240. A _DatasetReader that can be used to create operators that will
  241. iterate through the dataset.
  242. """
  243. assert self.field_blobs, 'Dataset not initialized.'
  244. reader = _DatasetReader(self, cursor_name, batch_size,
  245. enforce_batch_size)
  246. if init_net is not None:
  247. reader.setup_ex(init_net, None)
  248. return reader
  249. def random_reader(self, init_net=None, indices=None, cursor_name=None,
  250. batch_size=1, loop_over=False, enforce_batch_size=False):
  251. """Create a Reader object that is used to iterate through the dataset.
  252. NOTE: The reader order depends on the order in indices.
  253. Args:
  254. init_net: net that will be run once to create the cursor.
  255. indices: blob of reading order
  256. cursor_name: optional name for the blob containing a pointer
  257. to the cursor.
  258. batch_size: how many samples to read per iteration.
  259. loop_over: repeat the dataset indefinitely (in the same order)
  260. Returns:
  261. A DatasetReader that can be used to create operators that will
  262. iterate through the dataset according to indices.
  263. """
  264. assert self.field_blobs, 'Dataset not initialized.'
  265. reader = _DatasetRandomReader(
  266. self, cursor_name, indices, batch_size, loop_over,
  267. enforce_batch_size)
  268. if init_net is not None:
  269. reader.setup_ex(init_net, None)
  270. return reader
  271. def writer(self, init_net=None):
  272. """Create a Writer that can be used to append entries into the dataset.
  273. NOTE: Currently, it is not safe to append to a dataset
  274. while reading from it.
  275. NOTE: Currently implementation of writer is not thread safe.
  276. TODO: fixme
  277. Args:
  278. init_net: net that will be run once in order to create the writer.
  279. (currently not used)
  280. """
  281. assert self.field_blobs, 'Dataset not initialized.'
  282. writer = _DatasetWriter(self.content())
  283. if init_net is not None:
  284. writer.setup_ex(init_net, None)
  285. return writer