custom_dataset.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import importlib
  2. from pathlib import Path
  3. def load_module_from_py_file(py_file: str) -> object:
  4. """
  5. This method loads a module from a py file which is not in the Python path
  6. """
  7. module_name = Path(py_file).name
  8. loader = importlib.machinery.SourceFileLoader(module_name, py_file)
  9. spec = importlib.util.spec_from_loader(module_name, loader)
  10. module = importlib.util.module_from_spec(spec)
  11. loader.exec_module(module)
  12. return module
  13. def get_custom_dataset(dataset_config, tokenizer, split: str):
  14. if ":" in dataset_config.file:
  15. module_path, func_name = dataset_config.file.split(":")
  16. else:
  17. module_path, func_name = dataset_config.file, "get_custom_dataset"
  18. if not module_path.endswith(".py"):
  19. raise ValueError(f"Dataset file {module_path} is not a .py file.")
  20. module_path = Path(module_path)
  21. if not module_path.is_file():
  22. raise FileNotFoundError(f"Dataset py file {module_path.as_posix()} does not exist or is not a file.")
  23. module = load_module_from_py_file(module_path.as_posix())
  24. try:
  25. return getattr(module, func_name)(dataset_config, tokenizer, split)
  26. except AttributeError as e:
  27. print(f"It seems like the given method name ({func_name}) is not present in the dataset .py file ({module_path.as_posix()}).")
  28. raise e
  29. def get_data_collator(dataset_processer,dataset_config):
  30. if ":" in dataset_config.file:
  31. module_path, func_name = dataset_config.file.split(":")
  32. else:
  33. module_path, func_name = dataset_config.file, "get_data_collator"
  34. if not module_path.endswith(".py"):
  35. raise ValueError(f"Dataset file {module_path} is not a .py file.")
  36. module_path = Path(module_path)
  37. if not module_path.is_file():
  38. raise FileNotFoundError(f"Dataset py file {module_path.as_posix()} does not exist or is not a file.")
  39. module = load_module_from_py_file(module_path.as_posix())
  40. try:
  41. return getattr(module, func_name)(dataset_processer)
  42. except AttributeError as e:
  43. print(f"Can not find the custom data_collator in the dataset.py file ({module_path.as_posix()}).")
  44. print("Using the default data_collator instead.")
  45. return None