utils.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # Copyright (c) Meta Platforms, Inc. and affiliates.
  2. # This software may be used and distributed according to the terms of the Llama 2 Community License Agreement.
  3. from tqdm import tqdm
  4. from itertools import chain
  5. from torch.utils.data import Dataset
  6. class Concatenator(object):
  7. def __init__(self, chunk_size=2048):
  8. self.chunk_size=chunk_size
  9. self.residual = {"input_ids": [], "attention_mask": []}
  10. def __call__(self, batch):
  11. concatenated_samples = {
  12. k: v + list(chain(*batch[k])) for k, v in self.residual.items()
  13. }
  14. total_length = len(concatenated_samples[list(concatenated_samples.keys())[0]])
  15. if total_length >= self.chunk_size:
  16. chunk_num = total_length // self.chunk_size
  17. result = {
  18. k: [
  19. v[i : i + self.chunk_size]
  20. for i in range(0, chunk_num * self.chunk_size, self.chunk_size)
  21. ]
  22. for k, v in concatenated_samples.items()
  23. }
  24. self.residual = {
  25. k: v[(chunk_num * self.chunk_size) :]
  26. for k, v in concatenated_samples.items()
  27. }
  28. else:
  29. result = concatenated_samples
  30. self.residual = {k: [] for k in concatenated_samples.keys()}
  31. result["labels"] = result["input_ids"].copy()
  32. return result
  33. class ConcatDataset(Dataset):
  34. def __init__(self, dataset, chunk_size=4096):
  35. self.dataset = dataset
  36. self.chunk_size = chunk_size
  37. self.samples = []
  38. buffer = {
  39. "input_ids": [],
  40. "attention_mask": [],
  41. "labels": [],
  42. }
  43. for sample in tqdm(self.dataset, desc="Preprocessing dataset"):
  44. buffer = {k: v + sample[k] for k,v in buffer.items()}
  45. while len(next(iter(buffer.values()))) > self.chunk_size:
  46. self.samples.append({k: v[:self.chunk_size] for k,v in buffer.items()})
  47. buffer = {k: v[self.chunk_size:] for k,v in buffer.items()}
  48. def __getitem__(self, idx):
  49. return self.samples[idx]
  50. def __len__(self):
  51. return len(self.samples)