You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

dataset.py 2.5 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. # Copyright 2021 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """create tinybert dataset"""
  16. from enum import Enum
  17. import mindspore.common.dtype as mstype
  18. import mindspore.dataset.engine.datasets as de
  19. import mindspore.dataset.transforms.c_transforms as C
  20. class DataType(Enum):
  21. """Enumerate supported dataset format"""
  22. TFRECORD = 1
  23. MINDRECORD = 2
  24. def create_dataset(batch_size=32, device_num=1, rank=0, do_shuffle="true", data_dir=None,
  25. data_type='tfrecord', seq_length=128, task_type=mstype.int32, drop_remainder=True):
  26. """create tinybert dataset"""
  27. if isinstance(data_dir, list):
  28. data_files = data_dir
  29. else:
  30. data_files = [data_dir]
  31. columns_list = ["input_ids", "input_mask", "segment_ids", "label_ids"]
  32. shuffle = (do_shuffle == "true")
  33. if data_type == 'mindrecord':
  34. ds = de.MindDataset(data_files, columns_list=columns_list, shuffle=shuffle, num_shards=device_num,
  35. shard_id=rank)
  36. else:
  37. ds = de.TFRecordDataset(data_files, columns_list=columns_list, shuffle=shuffle, num_shards=device_num,
  38. shard_id=rank, shard_equal_rows=(device_num == 1))
  39. if device_num == 1 and shuffle is True:
  40. ds = ds.shuffle(10000)
  41. type_cast_op = C.TypeCast(mstype.int32)
  42. slice_op = C.Slice(slice(0, seq_length, 1))
  43. label_type = mstype.int32 if task_type == 'classification' else mstype.float32
  44. ds = ds.map(operations=[type_cast_op, slice_op], input_columns=["segment_ids"])
  45. ds = ds.map(operations=[type_cast_op, slice_op], input_columns=["input_mask"])
  46. ds = ds.map(operations=[type_cast_op, slice_op], input_columns=["input_ids"])
  47. ds = ds.map(operations=[C.TypeCast(label_type), slice_op], input_columns=["label_ids"])
  48. # apply batch operations
  49. ds = ds.batch(batch_size, drop_remainder=drop_remainder)
  50. return ds