html_url
stringlengths
48
51
title
stringlengths
5
155
comments
stringlengths
63
15.7k
body
stringlengths
0
17.7k
comment_length
int64
16
949
text
stringlengths
164
23.7k
https://github.com/huggingface/datasets/issues/720
OSError: Cannot find data file when not using the dummy dataset in RAG
Same issue here. I will be digging further, but it looks like the [script](https://github.com/huggingface/datasets/blob/master/datasets/wiki_dpr/wiki_dpr.py#L132) is attempting to open a file that is not downloaded yet. ``` 99dcbca09109e58502e6b9271d4d3f3791b43f61f3161a76b25d2775ab1a4498.lock ``` ``` --------------------------------------------------------------------------- UnpicklingError Traceback (most recent call last) ~/anaconda3/envs/eqa/lib/python3.7/site-packages/numpy/lib/npyio.py in load(file, mmap_mode, allow_pickle, fix_imports, encoding) 446 try: --> 447 return pickle.load(fid, **pickle_kwargs) 448 except Exception: UnpicklingError: pickle data was truncated During handling of the above exception, another exception occurred: OSError Traceback (most recent call last) ~/src/datasets/src/datasets/builder.py in _download_and_prepare(self, dl_manager, verify_infos, **prepare_split_kwargs) 559 --> 560 if verify_infos: 561 verify_splits(self.info.splits, split_dict) ~/src/datasets/src/datasets/builder.py in _prepare_split(self, split_generator) 847 writer.write(example) --> 848 finally: 849 num_examples, num_bytes = writer.finalize() ~/anaconda3/envs/eqa/lib/python3.7/site-packages/tqdm/notebook.py in __iter__(self, *args, **kwargs) 227 try: --> 228 for obj in super(tqdm_notebook, self).__iter__(*args, **kwargs): 229 # return super(tqdm...) will not catch exception ~/anaconda3/envs/eqa/lib/python3.7/site-packages/tqdm/std.py in __iter__(self) 1132 try: -> 1133 for obj in iterable: 1134 yield obj /hdd/rag/cache/huggingface/modules/datasets_modules/datasets/wiki_dpr/14b973bf2a456087ff69c0fd34526684eed22e48e0dfce4338f9a22b965ce7c2/wiki_dpr.py in _generate_examples(self, data_file, vectors_files) 131 break --> 132 vecs = np.load(open(vectors_files.pop(0), "rb"), allow_pickle=True) 133 vec_idx = 0 ~/anaconda3/envs/eqa/lib/python3.7/site-packages/numpy/lib/npyio.py in load(file, mmap_mode, allow_pickle, fix_imports, encoding) 449 raise IOError( --> 450 "Failed to interpret file %s as a pickle" % repr(file)) 451 OSError: Failed to interpret file <_io.BufferedReader name='/hdd/rag/downloads/99dcbca09109e58502e6b9271d4d3f3791b43f61f3161a76b25d2775ab1a4498'> as a pickle During handling of the above exception, another exception occurred: OSError Traceback (most recent call last) <ipython-input-8-24351ff8ce44> in <module> 4 retriever = RagRetriever.from_pretrained("facebook/rag-sequence-nq", 5 index_name="exact", ----> 6 use_dummy_dataset=False) ~/src/transformers/src/transformers/retrieval_rag.py in from_pretrained(cls, retriever_name_or_path, **kwargs) 321 generator_tokenizer = rag_tokenizer.generator 322 return cls( --> 323 config, question_encoder_tokenizer=question_encoder_tokenizer, generator_tokenizer=generator_tokenizer 324 ) 325 ~/src/transformers/src/transformers/retrieval_rag.py in __init__(self, config, question_encoder_tokenizer, generator_tokenizer) 310 self.config = config 311 if self._init_retrieval: --> 312 self.init_retrieval() 313 314 @classmethod ~/src/transformers/src/transformers/retrieval_rag.py in init_retrieval(self) 338 339 logger.info("initializing retrieval") --> 340 self.index.init_index() 341 342 def postprocess_docs(self, docs, input_strings, prefix, n_docs, return_tensors=None): ~/src/transformers/src/transformers/retrieval_rag.py in init_index(self) 248 split=self.dataset_split, 249 index_name=self.index_name, --> 250 dummy=self.use_dummy_dataset, 251 ) 252 self.dataset.set_format("numpy", columns=["embeddings"], output_all_columns=True) ~/src/datasets/src/datasets/load.py in load_dataset(path, name, data_dir, data_files, split, cache_dir, features, download_config, download_mode, ignore_verifications, save_infos, script_version, **config_kwargs) 615 builder_instance.download_and_prepare( 616 download_config=download_config, --> 617 download_mode=download_mode, 618 ignore_verifications=ignore_verifications, 619 ) ~/src/datasets/src/datasets/builder.py in download_and_prepare(self, download_config, download_mode, ignore_verifications, try_from_hf_gcs, dl_manager, **download_and_prepare_kwargs) 481 # Sync info 482 self.info.dataset_size = sum(split.num_bytes for split in self.info.splits.values()) --> 483 self.info.download_checksums = dl_manager.get_recorded_sizes_checksums() 484 self.info.size_in_bytes = self.info.dataset_size + self.info.download_size 485 # Save info ~/src/datasets/src/datasets/builder.py in _download_and_prepare(self, dl_manager, verify_infos, **prepare_split_kwargs) 560 if verify_infos: 561 verify_splits(self.info.splits, split_dict) --> 562 563 # Update the info object with the splits. 564 self.info.splits = split_dict OSError: Cannot find data file. ``` Thank you.
## Environment info transformers version: 3.3.1 Platform: Linux-4.19 Python version: 3.7.7 PyTorch version (GPU?): 1.6.0 Tensorflow version (GPU?): No Using GPU in script?: Yes Using distributed or parallel set-up in script?: No ## To reproduce Steps to reproduce the behaviour: ``` import os os.environ['HF_DATASETS_CACHE'] = '/workspace/notebooks/POCs/cache' from transformers import RagTokenizer, RagRetriever, RagTokenForGeneration tokenizer = RagTokenizer.from_pretrained("facebook/rag-token-nq") retriever = RagRetriever.from_pretrained("facebook/rag-token-nq", index_name="exact", use_dummy_dataset=False) ``` Plese note that I'm using the whole dataset: **use_dummy_dataset=False** After around 4 hours (downloading and some other things) this is returned: ``` Downloading and preparing dataset wiki_dpr/psgs_w100.nq.exact (download: Unknown size, generated: Unknown size, post-processed: Unknown size, total: Unknown size) to /workspace/notebooks/POCs/cache/wiki_dpr/psgs_w100.nq.exact/0.0.0/14b973bf2a456087ff69c0fd34526684eed22e48e0dfce4338f9a22b965ce7c2... --------------------------------------------------------------------------- UnpicklingError Traceback (most recent call last) /opt/conda/lib/python3.7/site-packages/numpy/lib/npyio.py in load(file, mmap_mode, allow_pickle, fix_imports, encoding) 459 try: --> 460 return pickle.load(fid, **pickle_kwargs) 461 except Exception: UnpicklingError: pickle data was truncated During handling of the above exception, another exception occurred: OSError Traceback (most recent call last) /opt/conda/lib/python3.7/site-packages/datasets/builder.py in _download_and_prepare(self, dl_manager, verify_infos, **prepare_split_kwargs) 552 # Prepare split will record examples associated to the split --> 553 self._prepare_split(split_generator, **prepare_split_kwargs) 554 except OSError: /opt/conda/lib/python3.7/site-packages/datasets/builder.py in _prepare_split(self, split_generator) 840 for key, record in utils.tqdm( --> 841 generator, unit=" examples", total=split_info.num_examples, leave=False, disable=not_verbose 842 ): /opt/conda/lib/python3.7/site-packages/tqdm/notebook.py in __iter__(self, *args, **kwargs) 217 try: --> 218 for obj in super(tqdm_notebook, self).__iter__(*args, **kwargs): 219 # return super(tqdm...) will not catch exception /opt/conda/lib/python3.7/site-packages/tqdm/std.py in __iter__(self) 1128 try: -> 1129 for obj in iterable: 1130 yield obj ~/.cache/huggingface/modules/datasets_modules/datasets/wiki_dpr/14b973bf2a456087ff69c0fd34526684eed22e48e0dfce4338f9a22b965ce7c2/wiki_dpr.py in _generate_examples(self, data_file, vectors_files) 131 break --> 132 vecs = np.load(open(vectors_files.pop(0), "rb"), allow_pickle=True) 133 vec_idx = 0 /opt/conda/lib/python3.7/site-packages/numpy/lib/npyio.py in load(file, mmap_mode, allow_pickle, fix_imports, encoding) 462 raise IOError( --> 463 "Failed to interpret file %s as a pickle" % repr(file)) 464 finally: OSError: Failed to interpret file <_io.BufferedReader name='/workspace/notebooks/POCs/cache/downloads/f34d5f091294259b4ca90e813631e69a6ded660d71b6cbedf89ddba50df94448'> as a pickle During handling of the above exception, another exception occurred: OSError Traceback (most recent call last) <ipython-input-10-f28df370ac47> in <module> 1 # ln -s /workspace/notebooks/POCs/cache /root/.cache/huggingface/datasets ----> 2 retriever = RagRetriever.from_pretrained("facebook/rag-token-nq", index_name="exact", use_dummy_dataset=False) /opt/conda/lib/python3.7/site-packages/transformers/retrieval_rag.py in from_pretrained(cls, retriever_name_or_path, **kwargs) 307 generator_tokenizer = rag_tokenizer.generator 308 return cls( --> 309 config, question_encoder_tokenizer=question_encoder_tokenizer, generator_tokenizer=generator_tokenizer 310 ) 311 /opt/conda/lib/python3.7/site-packages/transformers/retrieval_rag.py in __init__(self, config, question_encoder_tokenizer, generator_tokenizer) 298 self.config = config 299 if self._init_retrieval: --> 300 self.init_retrieval() 301 302 @classmethod /opt/conda/lib/python3.7/site-packages/transformers/retrieval_rag.py in init_retrieval(self) 324 325 logger.info("initializing retrieval") --> 326 self.index.init_index() 327 328 def postprocess_docs(self, docs, input_strings, prefix, n_docs, return_tensors=None): /opt/conda/lib/python3.7/site-packages/transformers/retrieval_rag.py in init_index(self) 238 split=self.dataset_split, 239 index_name=self.index_name, --> 240 dummy=self.use_dummy_dataset, 241 ) 242 self.dataset.set_format("numpy", columns=["embeddings"], output_all_columns=True) /opt/conda/lib/python3.7/site-packages/datasets/load.py in load_dataset(path, name, data_dir, data_files, split, cache_dir, features, download_config, download_mode, ignore_verifications, save_infos, script_version, **config_kwargs) 609 download_config=download_config, 610 download_mode=download_mode, --> 611 ignore_verifications=ignore_verifications, 612 ) 613 /opt/conda/lib/python3.7/site-packages/datasets/builder.py in download_and_prepare(self, download_config, download_mode, ignore_verifications, try_from_hf_gcs, dl_manager, **download_and_prepare_kwargs) 474 if not downloaded_from_gcs: 475 self._download_and_prepare( --> 476 dl_manager=dl_manager, verify_infos=verify_infos, **download_and_prepare_kwargs 477 ) 478 # Sync info /opt/conda/lib/python3.7/site-packages/datasets/builder.py in _download_and_prepare(self, dl_manager, verify_infos, **prepare_split_kwargs) 553 self._prepare_split(split_generator, **prepare_split_kwargs) 554 except OSError: --> 555 raise OSError("Cannot find data file. " + (self.manual_download_instructions or "")) 556 557 if verify_infos: OSError: Cannot find data file. ``` Thanks
387
OSError: Cannot find data file when not using the dummy dataset in RAG ## Environment info transformers version: 3.3.1 Platform: Linux-4.19 Python version: 3.7.7 PyTorch version (GPU?): 1.6.0 Tensorflow version (GPU?): No Using GPU in script?: Yes Using distributed or parallel set-up in script?: No ## To reproduce Steps to reproduce the behaviour: ``` import os os.environ['HF_DATASETS_CACHE'] = '/workspace/notebooks/POCs/cache' from transformers import RagTokenizer, RagRetriever, RagTokenForGeneration tokenizer = RagTokenizer.from_pretrained("facebook/rag-token-nq") retriever = RagRetriever.from_pretrained("facebook/rag-token-nq", index_name="exact", use_dummy_dataset=False) ``` Plese note that I'm using the whole dataset: **use_dummy_dataset=False** After around 4 hours (downloading and some other things) this is returned: ``` Downloading and preparing dataset wiki_dpr/psgs_w100.nq.exact (download: Unknown size, generated: Unknown size, post-processed: Unknown size, total: Unknown size) to /workspace/notebooks/POCs/cache/wiki_dpr/psgs_w100.nq.exact/0.0.0/14b973bf2a456087ff69c0fd34526684eed22e48e0dfce4338f9a22b965ce7c2... --------------------------------------------------------------------------- UnpicklingError Traceback (most recent call last) /opt/conda/lib/python3.7/site-packages/numpy/lib/npyio.py in load(file, mmap_mode, allow_pickle, fix_imports, encoding) 459 try: --> 460 return pickle.load(fid, **pickle_kwargs) 461 except Exception: UnpicklingError: pickle data was truncated During handling of the above exception, another exception occurred: OSError Traceback (most recent call last) /opt/conda/lib/python3.7/site-packages/datasets/builder.py in _download_and_prepare(self, dl_manager, verify_infos, **prepare_split_kwargs) 552 # Prepare split will record examples associated to the split --> 553 self._prepare_split(split_generator, **prepare_split_kwargs) 554 except OSError: /opt/conda/lib/python3.7/site-packages/datasets/builder.py in _prepare_split(self, split_generator) 840 for key, record in utils.tqdm( --> 841 generator, unit=" examples", total=split_info.num_examples, leave=False, disable=not_verbose 842 ): /opt/conda/lib/python3.7/site-packages/tqdm/notebook.py in __iter__(self, *args, **kwargs) 217 try: --> 218 for obj in super(tqdm_notebook, self).__iter__(*args, **kwargs): 219 # return super(tqdm...) will not catch exception /opt/conda/lib/python3.7/site-packages/tqdm/std.py in __iter__(self) 1128 try: -> 1129 for obj in iterable: 1130 yield obj ~/.cache/huggingface/modules/datasets_modules/datasets/wiki_dpr/14b973bf2a456087ff69c0fd34526684eed22e48e0dfce4338f9a22b965ce7c2/wiki_dpr.py in _generate_examples(self, data_file, vectors_files) 131 break --> 132 vecs = np.load(open(vectors_files.pop(0), "rb"), allow_pickle=True) 133 vec_idx = 0 /opt/conda/lib/python3.7/site-packages/numpy/lib/npyio.py in load(file, mmap_mode, allow_pickle, fix_imports, encoding) 462 raise IOError( --> 463 "Failed to interpret file %s as a pickle" % repr(file)) 464 finally: OSError: Failed to interpret file <_io.BufferedReader name='/workspace/notebooks/POCs/cache/downloads/f34d5f091294259b4ca90e813631e69a6ded660d71b6cbedf89ddba50df94448'> as a pickle During handling of the above exception, another exception occurred: OSError Traceback (most recent call last) <ipython-input-10-f28df370ac47> in <module> 1 # ln -s /workspace/notebooks/POCs/cache /root/.cache/huggingface/datasets ----> 2 retriever = RagRetriever.from_pretrained("facebook/rag-token-nq", index_name="exact", use_dummy_dataset=False) /opt/conda/lib/python3.7/site-packages/transformers/retrieval_rag.py in from_pretrained(cls, retriever_name_or_path, **kwargs) 307 generator_tokenizer = rag_tokenizer.generator 308 return cls( --> 309 config, question_encoder_tokenizer=question_encoder_tokenizer, generator_tokenizer=generator_tokenizer 310 ) 311 /opt/conda/lib/python3.7/site-packages/transformers/retrieval_rag.py in __init__(self, config, question_encoder_tokenizer, generator_tokenizer) 298 self.config = config 299 if self._init_retrieval: --> 300 self.init_retrieval() 301 302 @classmethod /opt/conda/lib/python3.7/site-packages/transformers/retrieval_rag.py in init_retrieval(self) 324 325 logger.info("initializing retrieval") --> 326 self.index.init_index() 327 328 def postprocess_docs(self, docs, input_strings, prefix, n_docs, return_tensors=None): /opt/conda/lib/python3.7/site-packages/transformers/retrieval_rag.py in init_index(self) 238 split=self.dataset_split, 239 index_name=self.index_name, --> 240 dummy=self.use_dummy_dataset, 241 ) 242 self.dataset.set_format("numpy", columns=["embeddings"], output_all_columns=True) /opt/conda/lib/python3.7/site-packages/datasets/load.py in load_dataset(path, name, data_dir, data_files, split, cache_dir, features, download_config, download_mode, ignore_verifications, save_infos, script_version, **config_kwargs) 609 download_config=download_config, 610 download_mode=download_mode, --> 611 ignore_verifications=ignore_verifications, 612 ) 613 /opt/conda/lib/python3.7/site-packages/datasets/builder.py in download_and_prepare(self, download_config, download_mode, ignore_verifications, try_from_hf_gcs, dl_manager, **download_and_prepare_kwargs) 474 if not downloaded_from_gcs: 475 self._download_and_prepare( --> 476 dl_manager=dl_manager, verify_infos=verify_infos, **download_and_prepare_kwargs 477 ) 478 # Sync info /opt/conda/lib/python3.7/site-packages/datasets/builder.py in _download_and_prepare(self, dl_manager, verify_infos, **prepare_split_kwargs) 553 self._prepare_split(split_generator, **prepare_split_kwargs) 554 except OSError: --> 555 raise OSError("Cannot find data file. " + (self.manual_download_instructions or "")) 556 557 if verify_infos: OSError: Cannot find data file. ``` Thanks Same issue here. I will be digging further, but it looks like the [script](https://github.com/huggingface/datasets/blob/master/datasets/wiki_dpr/wiki_dpr.py#L132) is attempting to open a file that is not downloaded yet. ``` 99dcbca09109e58502e6b9271d4d3f3791b43f61f3161a76b25d2775ab1a4498.lock ``` ``` --------------------------------------------------------------------------- UnpicklingError Traceback (most recent call last) ~/anaconda3/envs/eqa/lib/python3.7/site-packages/numpy/lib/npyio.py in load(file, mmap_mode, allow_pickle, fix_imports, encoding) 446 try: --> 447 return pickle.load(fid, **pickle_kwargs) 448 except Exception: UnpicklingError: pickle data was truncated During handling of the above exception, another exception occurred: OSError Traceback (most recent call last) ~/src/datasets/src/datasets/builder.py in _download_and_prepare(self, dl_manager, verify_infos, **prepare_split_kwargs) 559 --> 560 if verify_infos: 561 verify_splits(self.info.splits, split_dict) ~/src/datasets/src/datasets/builder.py in _prepare_split(self, split_generator) 847 writer.write(example) --> 848 finally: 849 num_examples, num_bytes = writer.finalize() ~/anaconda3/envs/eqa/lib/python3.7/site-packages/tqdm/notebook.py in __iter__(self, *args, **kwargs) 227 try: --> 228 for obj in super(tqdm_notebook, self).__iter__(*args, **kwargs): 229 # return super(tqdm...) will not catch exception ~/anaconda3/envs/eqa/lib/python3.7/site-packages/tqdm/std.py in __iter__(self) 1132 try: -> 1133 for obj in iterable: 1134 yield obj /hdd/rag/cache/huggingface/modules/datasets_modules/datasets/wiki_dpr/14b973bf2a456087ff69c0fd34526684eed22e48e0dfce4338f9a22b965ce7c2/wiki_dpr.py in _generate_examples(self, data_file, vectors_files) 131 break --> 132 vecs = np.load(open(vectors_files.pop(0), "rb"), allow_pickle=True) 133 vec_idx = 0 ~/anaconda3/envs/eqa/lib/python3.7/site-packages/numpy/lib/npyio.py in load(file, mmap_mode, allow_pickle, fix_imports, encoding) 449 raise IOError( --> 450 "Failed to interpret file %s as a pickle" % repr(file)) 451 OSError: Failed to interpret file <_io.BufferedReader name='/hdd/rag/downloads/99dcbca09109e58502e6b9271d4d3f3791b43f61f3161a76b25d2775ab1a4498'> as a pickle During handling of the above exception, another exception occurred: OSError Traceback (most recent call last) <ipython-input-8-24351ff8ce44> in <module> 4 retriever = RagRetriever.from_pretrained("facebook/rag-sequence-nq", 5 index_name="exact", ----> 6 use_dummy_dataset=False) ~/src/transformers/src/transformers/retrieval_rag.py in from_pretrained(cls, retriever_name_or_path, **kwargs) 321 generator_tokenizer = rag_tokenizer.generator 322 return cls( --> 323 config, question_encoder_tokenizer=question_encoder_tokenizer, generator_tokenizer=generator_tokenizer 324 ) 325 ~/src/transformers/src/transformers/retrieval_rag.py in __init__(self, config, question_encoder_tokenizer, generator_tokenizer) 310 self.config = config 311 if self._init_retrieval: --> 312 self.init_retrieval() 313 314 @classmethod ~/src/transformers/src/transformers/retrieval_rag.py in init_retrieval(self) 338 339 logger.info("initializing retrieval") --> 340 self.index.init_index() 341 342 def postprocess_docs(self, docs, input_strings, prefix, n_docs, return_tensors=None): ~/src/transformers/src/transformers/retrieval_rag.py in init_index(self) 248 split=self.dataset_split, 249 index_name=self.index_name, --> 250 dummy=self.use_dummy_dataset, 251 ) 252 self.dataset.set_format("numpy", columns=["embeddings"], output_all_columns=True) ~/src/datasets/src/datasets/load.py in load_dataset(path, name, data_dir, data_files, split, cache_dir, features, download_config, download_mode, ignore_verifications, save_infos, script_version, **config_kwargs) 615 builder_instance.download_and_prepare( 616 download_config=download_config, --> 617 download_mode=download_mode, 618 ignore_verifications=ignore_verifications, 619 ) ~/src/datasets/src/datasets/builder.py in download_and_prepare(self, download_config, download_mode, ignore_verifications, try_from_hf_gcs, dl_manager, **download_and_prepare_kwargs) 481 # Sync info 482 self.info.dataset_size = sum(split.num_bytes for split in self.info.splits.values()) --> 483 self.info.download_checksums = dl_manager.get_recorded_sizes_checksums() 484 self.info.size_in_bytes = self.info.dataset_size + self.info.download_size 485 # Save info ~/src/datasets/src/datasets/builder.py in _download_and_prepare(self, dl_manager, verify_infos, **prepare_split_kwargs) 560 if verify_infos: 561 verify_splits(self.info.splits, split_dict) --> 562 563 # Update the info object with the splits. 564 self.info.splits = split_dict OSError: Cannot find data file. ``` Thank you.
https://github.com/huggingface/datasets/issues/720
OSError: Cannot find data file when not using the dummy dataset in RAG
An update on my end. This seems like a transient issue. Reran the script from scratch overnight with no errors.
## Environment info transformers version: 3.3.1 Platform: Linux-4.19 Python version: 3.7.7 PyTorch version (GPU?): 1.6.0 Tensorflow version (GPU?): No Using GPU in script?: Yes Using distributed or parallel set-up in script?: No ## To reproduce Steps to reproduce the behaviour: ``` import os os.environ['HF_DATASETS_CACHE'] = '/workspace/notebooks/POCs/cache' from transformers import RagTokenizer, RagRetriever, RagTokenForGeneration tokenizer = RagTokenizer.from_pretrained("facebook/rag-token-nq") retriever = RagRetriever.from_pretrained("facebook/rag-token-nq", index_name="exact", use_dummy_dataset=False) ``` Plese note that I'm using the whole dataset: **use_dummy_dataset=False** After around 4 hours (downloading and some other things) this is returned: ``` Downloading and preparing dataset wiki_dpr/psgs_w100.nq.exact (download: Unknown size, generated: Unknown size, post-processed: Unknown size, total: Unknown size) to /workspace/notebooks/POCs/cache/wiki_dpr/psgs_w100.nq.exact/0.0.0/14b973bf2a456087ff69c0fd34526684eed22e48e0dfce4338f9a22b965ce7c2... --------------------------------------------------------------------------- UnpicklingError Traceback (most recent call last) /opt/conda/lib/python3.7/site-packages/numpy/lib/npyio.py in load(file, mmap_mode, allow_pickle, fix_imports, encoding) 459 try: --> 460 return pickle.load(fid, **pickle_kwargs) 461 except Exception: UnpicklingError: pickle data was truncated During handling of the above exception, another exception occurred: OSError Traceback (most recent call last) /opt/conda/lib/python3.7/site-packages/datasets/builder.py in _download_and_prepare(self, dl_manager, verify_infos, **prepare_split_kwargs) 552 # Prepare split will record examples associated to the split --> 553 self._prepare_split(split_generator, **prepare_split_kwargs) 554 except OSError: /opt/conda/lib/python3.7/site-packages/datasets/builder.py in _prepare_split(self, split_generator) 840 for key, record in utils.tqdm( --> 841 generator, unit=" examples", total=split_info.num_examples, leave=False, disable=not_verbose 842 ): /opt/conda/lib/python3.7/site-packages/tqdm/notebook.py in __iter__(self, *args, **kwargs) 217 try: --> 218 for obj in super(tqdm_notebook, self).__iter__(*args, **kwargs): 219 # return super(tqdm...) will not catch exception /opt/conda/lib/python3.7/site-packages/tqdm/std.py in __iter__(self) 1128 try: -> 1129 for obj in iterable: 1130 yield obj ~/.cache/huggingface/modules/datasets_modules/datasets/wiki_dpr/14b973bf2a456087ff69c0fd34526684eed22e48e0dfce4338f9a22b965ce7c2/wiki_dpr.py in _generate_examples(self, data_file, vectors_files) 131 break --> 132 vecs = np.load(open(vectors_files.pop(0), "rb"), allow_pickle=True) 133 vec_idx = 0 /opt/conda/lib/python3.7/site-packages/numpy/lib/npyio.py in load(file, mmap_mode, allow_pickle, fix_imports, encoding) 462 raise IOError( --> 463 "Failed to interpret file %s as a pickle" % repr(file)) 464 finally: OSError: Failed to interpret file <_io.BufferedReader name='/workspace/notebooks/POCs/cache/downloads/f34d5f091294259b4ca90e813631e69a6ded660d71b6cbedf89ddba50df94448'> as a pickle During handling of the above exception, another exception occurred: OSError Traceback (most recent call last) <ipython-input-10-f28df370ac47> in <module> 1 # ln -s /workspace/notebooks/POCs/cache /root/.cache/huggingface/datasets ----> 2 retriever = RagRetriever.from_pretrained("facebook/rag-token-nq", index_name="exact", use_dummy_dataset=False) /opt/conda/lib/python3.7/site-packages/transformers/retrieval_rag.py in from_pretrained(cls, retriever_name_or_path, **kwargs) 307 generator_tokenizer = rag_tokenizer.generator 308 return cls( --> 309 config, question_encoder_tokenizer=question_encoder_tokenizer, generator_tokenizer=generator_tokenizer 310 ) 311 /opt/conda/lib/python3.7/site-packages/transformers/retrieval_rag.py in __init__(self, config, question_encoder_tokenizer, generator_tokenizer) 298 self.config = config 299 if self._init_retrieval: --> 300 self.init_retrieval() 301 302 @classmethod /opt/conda/lib/python3.7/site-packages/transformers/retrieval_rag.py in init_retrieval(self) 324 325 logger.info("initializing retrieval") --> 326 self.index.init_index() 327 328 def postprocess_docs(self, docs, input_strings, prefix, n_docs, return_tensors=None): /opt/conda/lib/python3.7/site-packages/transformers/retrieval_rag.py in init_index(self) 238 split=self.dataset_split, 239 index_name=self.index_name, --> 240 dummy=self.use_dummy_dataset, 241 ) 242 self.dataset.set_format("numpy", columns=["embeddings"], output_all_columns=True) /opt/conda/lib/python3.7/site-packages/datasets/load.py in load_dataset(path, name, data_dir, data_files, split, cache_dir, features, download_config, download_mode, ignore_verifications, save_infos, script_version, **config_kwargs) 609 download_config=download_config, 610 download_mode=download_mode, --> 611 ignore_verifications=ignore_verifications, 612 ) 613 /opt/conda/lib/python3.7/site-packages/datasets/builder.py in download_and_prepare(self, download_config, download_mode, ignore_verifications, try_from_hf_gcs, dl_manager, **download_and_prepare_kwargs) 474 if not downloaded_from_gcs: 475 self._download_and_prepare( --> 476 dl_manager=dl_manager, verify_infos=verify_infos, **download_and_prepare_kwargs 477 ) 478 # Sync info /opt/conda/lib/python3.7/site-packages/datasets/builder.py in _download_and_prepare(self, dl_manager, verify_infos, **prepare_split_kwargs) 553 self._prepare_split(split_generator, **prepare_split_kwargs) 554 except OSError: --> 555 raise OSError("Cannot find data file. " + (self.manual_download_instructions or "")) 556 557 if verify_infos: OSError: Cannot find data file. ``` Thanks
20
OSError: Cannot find data file when not using the dummy dataset in RAG ## Environment info transformers version: 3.3.1 Platform: Linux-4.19 Python version: 3.7.7 PyTorch version (GPU?): 1.6.0 Tensorflow version (GPU?): No Using GPU in script?: Yes Using distributed or parallel set-up in script?: No ## To reproduce Steps to reproduce the behaviour: ``` import os os.environ['HF_DATASETS_CACHE'] = '/workspace/notebooks/POCs/cache' from transformers import RagTokenizer, RagRetriever, RagTokenForGeneration tokenizer = RagTokenizer.from_pretrained("facebook/rag-token-nq") retriever = RagRetriever.from_pretrained("facebook/rag-token-nq", index_name="exact", use_dummy_dataset=False) ``` Plese note that I'm using the whole dataset: **use_dummy_dataset=False** After around 4 hours (downloading and some other things) this is returned: ``` Downloading and preparing dataset wiki_dpr/psgs_w100.nq.exact (download: Unknown size, generated: Unknown size, post-processed: Unknown size, total: Unknown size) to /workspace/notebooks/POCs/cache/wiki_dpr/psgs_w100.nq.exact/0.0.0/14b973bf2a456087ff69c0fd34526684eed22e48e0dfce4338f9a22b965ce7c2... --------------------------------------------------------------------------- UnpicklingError Traceback (most recent call last) /opt/conda/lib/python3.7/site-packages/numpy/lib/npyio.py in load(file, mmap_mode, allow_pickle, fix_imports, encoding) 459 try: --> 460 return pickle.load(fid, **pickle_kwargs) 461 except Exception: UnpicklingError: pickle data was truncated During handling of the above exception, another exception occurred: OSError Traceback (most recent call last) /opt/conda/lib/python3.7/site-packages/datasets/builder.py in _download_and_prepare(self, dl_manager, verify_infos, **prepare_split_kwargs) 552 # Prepare split will record examples associated to the split --> 553 self._prepare_split(split_generator, **prepare_split_kwargs) 554 except OSError: /opt/conda/lib/python3.7/site-packages/datasets/builder.py in _prepare_split(self, split_generator) 840 for key, record in utils.tqdm( --> 841 generator, unit=" examples", total=split_info.num_examples, leave=False, disable=not_verbose 842 ): /opt/conda/lib/python3.7/site-packages/tqdm/notebook.py in __iter__(self, *args, **kwargs) 217 try: --> 218 for obj in super(tqdm_notebook, self).__iter__(*args, **kwargs): 219 # return super(tqdm...) will not catch exception /opt/conda/lib/python3.7/site-packages/tqdm/std.py in __iter__(self) 1128 try: -> 1129 for obj in iterable: 1130 yield obj ~/.cache/huggingface/modules/datasets_modules/datasets/wiki_dpr/14b973bf2a456087ff69c0fd34526684eed22e48e0dfce4338f9a22b965ce7c2/wiki_dpr.py in _generate_examples(self, data_file, vectors_files) 131 break --> 132 vecs = np.load(open(vectors_files.pop(0), "rb"), allow_pickle=True) 133 vec_idx = 0 /opt/conda/lib/python3.7/site-packages/numpy/lib/npyio.py in load(file, mmap_mode, allow_pickle, fix_imports, encoding) 462 raise IOError( --> 463 "Failed to interpret file %s as a pickle" % repr(file)) 464 finally: OSError: Failed to interpret file <_io.BufferedReader name='/workspace/notebooks/POCs/cache/downloads/f34d5f091294259b4ca90e813631e69a6ded660d71b6cbedf89ddba50df94448'> as a pickle During handling of the above exception, another exception occurred: OSError Traceback (most recent call last) <ipython-input-10-f28df370ac47> in <module> 1 # ln -s /workspace/notebooks/POCs/cache /root/.cache/huggingface/datasets ----> 2 retriever = RagRetriever.from_pretrained("facebook/rag-token-nq", index_name="exact", use_dummy_dataset=False) /opt/conda/lib/python3.7/site-packages/transformers/retrieval_rag.py in from_pretrained(cls, retriever_name_or_path, **kwargs) 307 generator_tokenizer = rag_tokenizer.generator 308 return cls( --> 309 config, question_encoder_tokenizer=question_encoder_tokenizer, generator_tokenizer=generator_tokenizer 310 ) 311 /opt/conda/lib/python3.7/site-packages/transformers/retrieval_rag.py in __init__(self, config, question_encoder_tokenizer, generator_tokenizer) 298 self.config = config 299 if self._init_retrieval: --> 300 self.init_retrieval() 301 302 @classmethod /opt/conda/lib/python3.7/site-packages/transformers/retrieval_rag.py in init_retrieval(self) 324 325 logger.info("initializing retrieval") --> 326 self.index.init_index() 327 328 def postprocess_docs(self, docs, input_strings, prefix, n_docs, return_tensors=None): /opt/conda/lib/python3.7/site-packages/transformers/retrieval_rag.py in init_index(self) 238 split=self.dataset_split, 239 index_name=self.index_name, --> 240 dummy=self.use_dummy_dataset, 241 ) 242 self.dataset.set_format("numpy", columns=["embeddings"], output_all_columns=True) /opt/conda/lib/python3.7/site-packages/datasets/load.py in load_dataset(path, name, data_dir, data_files, split, cache_dir, features, download_config, download_mode, ignore_verifications, save_infos, script_version, **config_kwargs) 609 download_config=download_config, 610 download_mode=download_mode, --> 611 ignore_verifications=ignore_verifications, 612 ) 613 /opt/conda/lib/python3.7/site-packages/datasets/builder.py in download_and_prepare(self, download_config, download_mode, ignore_verifications, try_from_hf_gcs, dl_manager, **download_and_prepare_kwargs) 474 if not downloaded_from_gcs: 475 self._download_and_prepare( --> 476 dl_manager=dl_manager, verify_infos=verify_infos, **download_and_prepare_kwargs 477 ) 478 # Sync info /opt/conda/lib/python3.7/site-packages/datasets/builder.py in _download_and_prepare(self, dl_manager, verify_infos, **prepare_split_kwargs) 553 self._prepare_split(split_generator, **prepare_split_kwargs) 554 except OSError: --> 555 raise OSError("Cannot find data file. " + (self.manual_download_instructions or "")) 556 557 if verify_infos: OSError: Cannot find data file. ``` Thanks An update on my end. This seems like a transient issue. Reran the script from scratch overnight with no errors.
https://github.com/huggingface/datasets/issues/709
How to use similarity settings other then "BM25" in Elasticsearch index ?
Datasets does not use elasticsearch API to define custom similarity. If you want to use a custom similarity, the best would be to run a curl request directly to your elasticsearch instance (see sample hereafter, directly from ES documentation), then you should be able to use `my_similarity` in your configuration passed to datasets ``` curl -X PUT "localhost:9200/index?pretty" -H 'Content-Type: application/json' -d' { "settings": { "index": { "similarity": { "my_similarity": { "type": "DFR", "basic_model": "g", "after_effect": "l", "normalization": "h2", "normalization.h2.c": "3.0" } } } } } ' ```
**QUESTION : How should we use other similarity algorithms supported by Elasticsearch other than "BM25" ?** **ES Reference** https://www.elastic.co/guide/en/elasticsearch/reference/current/index-modules-similarity.html **HF doc reference:** https://huggingface.co/docs/datasets/faiss_and_ea.html **context :** ======== I used the latest Elasticsearch server version 7.9.2 When I set DFR which is one of the other similarity algorithms supported by elasticsearch in the mapping, I get an error For example DFR that I had tried in the first instance in mappings as below., `"mappings": {"properties": {"text": {"type": "text", "analyzer": "standard", "similarity": "DFR"}}},` I get the following error RequestError: RequestError(400, 'mapper_parsing_exception', 'Unknown Similarity type [DFR] for field [text]') The other thing as another option I had tried was to declare "similarity": "my_similarity" within settings and then assigning "my_similarity" inside the mappings as below `es_config = { "settings": { "number_of_shards": 1, **"similarity": "my_similarity"**: { "type": "DFR", "basic_model": "g", "after_effect": "l", "normalization": "h2", "normalization.h2.c": "3.0" } , "analysis": {"analyzer": {"stop_standard": {"type": "standard", " stopwords": "_english_"}}}, }, "mappings": {"properties": {"text": {"type": "text", "analyzer": "standard", "similarity": "my_similarity"}}}, }` For this , I got the following error RequestError: RequestError(400, 'illegal_argument_exception', 'unknown setting [index.similarity] please check that any required plugins are installed, or check the breaking changes documentation for removed settings')
88
How to use similarity settings other then "BM25" in Elasticsearch index ? **QUESTION : How should we use other similarity algorithms supported by Elasticsearch other than "BM25" ?** **ES Reference** https://www.elastic.co/guide/en/elasticsearch/reference/current/index-modules-similarity.html **HF doc reference:** https://huggingface.co/docs/datasets/faiss_and_ea.html **context :** ======== I used the latest Elasticsearch server version 7.9.2 When I set DFR which is one of the other similarity algorithms supported by elasticsearch in the mapping, I get an error For example DFR that I had tried in the first instance in mappings as below., `"mappings": {"properties": {"text": {"type": "text", "analyzer": "standard", "similarity": "DFR"}}},` I get the following error RequestError: RequestError(400, 'mapper_parsing_exception', 'Unknown Similarity type [DFR] for field [text]') The other thing as another option I had tried was to declare "similarity": "my_similarity" within settings and then assigning "my_similarity" inside the mappings as below `es_config = { "settings": { "number_of_shards": 1, **"similarity": "my_similarity"**: { "type": "DFR", "basic_model": "g", "after_effect": "l", "normalization": "h2", "normalization.h2.c": "3.0" } , "analysis": {"analyzer": {"stop_standard": {"type": "standard", " stopwords": "_english_"}}}, }, "mappings": {"properties": {"text": {"type": "text", "analyzer": "standard", "similarity": "my_similarity"}}}, }` For this , I got the following error RequestError: RequestError(400, 'illegal_argument_exception', 'unknown setting [index.similarity] please check that any required plugins are installed, or check the breaking changes documentation for removed settings') Datasets does not use elasticsearch API to define custom similarity. If you want to use a custom similarity, the best would be to run a curl request directly to your elasticsearch instance (see sample hereafter, directly from ES documentation), then you should be able to use `my_similarity` in your configuration passed to datasets ``` curl -X PUT "localhost:9200/index?pretty" -H 'Content-Type: application/json' -d' { "settings": { "index": { "similarity": { "my_similarity": { "type": "DFR", "basic_model": "g", "after_effect": "l", "normalization": "h2", "normalization.h2.c": "3.0" } } } } } ' ```
https://github.com/huggingface/datasets/issues/708
Datasets performance slow? - 6.4x slower than in memory dataset
Facing a similar issue here. My model using SQuAD dataset takes about 1h to process with in memory data and more than 2h with datasets directly.
I've been very excited about this amazing datasets project. However, I've noticed that the performance can be substantially slower than using an in-memory dataset. Now, this is expected I guess, due to memory mapping data using arrow files, and you don't get anything for free. But I was surprised at how much slower. For example, in the `yelp_polarity` dataset (560000 datapoints, or 17500 batches of 32), it was taking me 3:31 to just get process the data and get it on the GPU (no model involved). Whereas, the equivalent in-memory dataset would finish in just 0:33. Is this expected? Given that one of the goals of this project is also accelerate dataset processing, this seems a bit slower than I would expect. I understand the advantages of being able to work on datasets that exceed memory, and that's very exciting to me, but thought I'd open this issue to discuss. For reference I'm running a AMD Ryzen Threadripper 1900X 8-Core Processor CPU, with 128 GB of RAM and an NVME SSD Samsung 960 EVO. I'm running with an RTX Titan 24GB GPU. I can see with `iotop` that the dataset gets quickly loaded into the system read buffers, and thus doesn't incur any additional IO reads. Thus in theory, all the data *should* be in RAM, but in my benchmark code below it's still 6.4 times slower. What am I doing wrong? And is there a way to force the datasets to completely load into memory instead of being memory mapped in cases where you want maximum performance? At 3:31 for 17500 batches, that's 12ms per batch. Does this 12ms just become insignificant as a proportion of forward and backward passes in practice, and thus it's not worth worrying about this in practice? In any case, here's my code `benchmark.py`. If you run it with an argument of `memory` it will copy the data into memory before executing the same test. ``` py import sys from datasets import load_dataset from transformers import DataCollatorWithPadding, BertTokenizerFast from torch.utils.data import DataLoader from tqdm import tqdm if __name__ == '__main__': tokenizer = BertTokenizerFast.from_pretrained('bert-base-cased') collate_fn = DataCollatorWithPadding(tokenizer, padding=True) ds = load_dataset('yelp_polarity') def do_tokenize(x): return tokenizer(x['text'], truncation=True) ds = ds.map(do_tokenize, batched=True) ds.set_format('torch', ['input_ids', 'token_type_ids', 'attention_mask']) if len(sys.argv) == 2 and sys.argv[1] == 'memory': # copy to memory - probably a faster way to do this - but demonstrates the point # approximately 530 batches per second - 17500 batches in 0:33 print('using memory') _ds = [data for data in tqdm(ds['train'])] else: # approximately 83 batches per second - 17500 batches in 3:31 print('using datasets') _ds = ds['train'] dl = DataLoader(_ds, shuffle=True, collate_fn=collate_fn, batch_size=32, num_workers=4) for data in tqdm(dl): for k, v in data.items(): data[k] = v.to('cuda') ``` For reference, my conda environment is [here](https://gist.github.com/05b6101518ff70ed42a858b302a0405d) Once again, I'm very excited about this library, and how easy it is to load datasets, and to do so without worrying about system memory constraints. Thanks for all your great work.
26
Datasets performance slow? - 6.4x slower than in memory dataset I've been very excited about this amazing datasets project. However, I've noticed that the performance can be substantially slower than using an in-memory dataset. Now, this is expected I guess, due to memory mapping data using arrow files, and you don't get anything for free. But I was surprised at how much slower. For example, in the `yelp_polarity` dataset (560000 datapoints, or 17500 batches of 32), it was taking me 3:31 to just get process the data and get it on the GPU (no model involved). Whereas, the equivalent in-memory dataset would finish in just 0:33. Is this expected? Given that one of the goals of this project is also accelerate dataset processing, this seems a bit slower than I would expect. I understand the advantages of being able to work on datasets that exceed memory, and that's very exciting to me, but thought I'd open this issue to discuss. For reference I'm running a AMD Ryzen Threadripper 1900X 8-Core Processor CPU, with 128 GB of RAM and an NVME SSD Samsung 960 EVO. I'm running with an RTX Titan 24GB GPU. I can see with `iotop` that the dataset gets quickly loaded into the system read buffers, and thus doesn't incur any additional IO reads. Thus in theory, all the data *should* be in RAM, but in my benchmark code below it's still 6.4 times slower. What am I doing wrong? And is there a way to force the datasets to completely load into memory instead of being memory mapped in cases where you want maximum performance? At 3:31 for 17500 batches, that's 12ms per batch. Does this 12ms just become insignificant as a proportion of forward and backward passes in practice, and thus it's not worth worrying about this in practice? In any case, here's my code `benchmark.py`. If you run it with an argument of `memory` it will copy the data into memory before executing the same test. ``` py import sys from datasets import load_dataset from transformers import DataCollatorWithPadding, BertTokenizerFast from torch.utils.data import DataLoader from tqdm import tqdm if __name__ == '__main__': tokenizer = BertTokenizerFast.from_pretrained('bert-base-cased') collate_fn = DataCollatorWithPadding(tokenizer, padding=True) ds = load_dataset('yelp_polarity') def do_tokenize(x): return tokenizer(x['text'], truncation=True) ds = ds.map(do_tokenize, batched=True) ds.set_format('torch', ['input_ids', 'token_type_ids', 'attention_mask']) if len(sys.argv) == 2 and sys.argv[1] == 'memory': # copy to memory - probably a faster way to do this - but demonstrates the point # approximately 530 batches per second - 17500 batches in 0:33 print('using memory') _ds = [data for data in tqdm(ds['train'])] else: # approximately 83 batches per second - 17500 batches in 3:31 print('using datasets') _ds = ds['train'] dl = DataLoader(_ds, shuffle=True, collate_fn=collate_fn, batch_size=32, num_workers=4) for data in tqdm(dl): for k, v in data.items(): data[k] = v.to('cuda') ``` For reference, my conda environment is [here](https://gist.github.com/05b6101518ff70ed42a858b302a0405d) Once again, I'm very excited about this library, and how easy it is to load datasets, and to do so without worrying about system memory constraints. Thanks for all your great work. Facing a similar issue here. My model using SQuAD dataset takes about 1h to process with in memory data and more than 2h with datasets directly.
https://github.com/huggingface/datasets/issues/708
Datasets performance slow? - 6.4x slower than in memory dataset
Thanks for the tip @thomwolf ! I did not see that flag in the docs. I'll try with that.
I've been very excited about this amazing datasets project. However, I've noticed that the performance can be substantially slower than using an in-memory dataset. Now, this is expected I guess, due to memory mapping data using arrow files, and you don't get anything for free. But I was surprised at how much slower. For example, in the `yelp_polarity` dataset (560000 datapoints, or 17500 batches of 32), it was taking me 3:31 to just get process the data and get it on the GPU (no model involved). Whereas, the equivalent in-memory dataset would finish in just 0:33. Is this expected? Given that one of the goals of this project is also accelerate dataset processing, this seems a bit slower than I would expect. I understand the advantages of being able to work on datasets that exceed memory, and that's very exciting to me, but thought I'd open this issue to discuss. For reference I'm running a AMD Ryzen Threadripper 1900X 8-Core Processor CPU, with 128 GB of RAM and an NVME SSD Samsung 960 EVO. I'm running with an RTX Titan 24GB GPU. I can see with `iotop` that the dataset gets quickly loaded into the system read buffers, and thus doesn't incur any additional IO reads. Thus in theory, all the data *should* be in RAM, but in my benchmark code below it's still 6.4 times slower. What am I doing wrong? And is there a way to force the datasets to completely load into memory instead of being memory mapped in cases where you want maximum performance? At 3:31 for 17500 batches, that's 12ms per batch. Does this 12ms just become insignificant as a proportion of forward and backward passes in practice, and thus it's not worth worrying about this in practice? In any case, here's my code `benchmark.py`. If you run it with an argument of `memory` it will copy the data into memory before executing the same test. ``` py import sys from datasets import load_dataset from transformers import DataCollatorWithPadding, BertTokenizerFast from torch.utils.data import DataLoader from tqdm import tqdm if __name__ == '__main__': tokenizer = BertTokenizerFast.from_pretrained('bert-base-cased') collate_fn = DataCollatorWithPadding(tokenizer, padding=True) ds = load_dataset('yelp_polarity') def do_tokenize(x): return tokenizer(x['text'], truncation=True) ds = ds.map(do_tokenize, batched=True) ds.set_format('torch', ['input_ids', 'token_type_ids', 'attention_mask']) if len(sys.argv) == 2 and sys.argv[1] == 'memory': # copy to memory - probably a faster way to do this - but demonstrates the point # approximately 530 batches per second - 17500 batches in 0:33 print('using memory') _ds = [data for data in tqdm(ds['train'])] else: # approximately 83 batches per second - 17500 batches in 3:31 print('using datasets') _ds = ds['train'] dl = DataLoader(_ds, shuffle=True, collate_fn=collate_fn, batch_size=32, num_workers=4) for data in tqdm(dl): for k, v in data.items(): data[k] = v.to('cuda') ``` For reference, my conda environment is [here](https://gist.github.com/05b6101518ff70ed42a858b302a0405d) Once again, I'm very excited about this library, and how easy it is to load datasets, and to do so without worrying about system memory constraints. Thanks for all your great work.
19
Datasets performance slow? - 6.4x slower than in memory dataset I've been very excited about this amazing datasets project. However, I've noticed that the performance can be substantially slower than using an in-memory dataset. Now, this is expected I guess, due to memory mapping data using arrow files, and you don't get anything for free. But I was surprised at how much slower. For example, in the `yelp_polarity` dataset (560000 datapoints, or 17500 batches of 32), it was taking me 3:31 to just get process the data and get it on the GPU (no model involved). Whereas, the equivalent in-memory dataset would finish in just 0:33. Is this expected? Given that one of the goals of this project is also accelerate dataset processing, this seems a bit slower than I would expect. I understand the advantages of being able to work on datasets that exceed memory, and that's very exciting to me, but thought I'd open this issue to discuss. For reference I'm running a AMD Ryzen Threadripper 1900X 8-Core Processor CPU, with 128 GB of RAM and an NVME SSD Samsung 960 EVO. I'm running with an RTX Titan 24GB GPU. I can see with `iotop` that the dataset gets quickly loaded into the system read buffers, and thus doesn't incur any additional IO reads. Thus in theory, all the data *should* be in RAM, but in my benchmark code below it's still 6.4 times slower. What am I doing wrong? And is there a way to force the datasets to completely load into memory instead of being memory mapped in cases where you want maximum performance? At 3:31 for 17500 batches, that's 12ms per batch. Does this 12ms just become insignificant as a proportion of forward and backward passes in practice, and thus it's not worth worrying about this in practice? In any case, here's my code `benchmark.py`. If you run it with an argument of `memory` it will copy the data into memory before executing the same test. ``` py import sys from datasets import load_dataset from transformers import DataCollatorWithPadding, BertTokenizerFast from torch.utils.data import DataLoader from tqdm import tqdm if __name__ == '__main__': tokenizer = BertTokenizerFast.from_pretrained('bert-base-cased') collate_fn = DataCollatorWithPadding(tokenizer, padding=True) ds = load_dataset('yelp_polarity') def do_tokenize(x): return tokenizer(x['text'], truncation=True) ds = ds.map(do_tokenize, batched=True) ds.set_format('torch', ['input_ids', 'token_type_ids', 'attention_mask']) if len(sys.argv) == 2 and sys.argv[1] == 'memory': # copy to memory - probably a faster way to do this - but demonstrates the point # approximately 530 batches per second - 17500 batches in 0:33 print('using memory') _ds = [data for data in tqdm(ds['train'])] else: # approximately 83 batches per second - 17500 batches in 3:31 print('using datasets') _ds = ds['train'] dl = DataLoader(_ds, shuffle=True, collate_fn=collate_fn, batch_size=32, num_workers=4) for data in tqdm(dl): for k, v in data.items(): data[k] = v.to('cuda') ``` For reference, my conda environment is [here](https://gist.github.com/05b6101518ff70ed42a858b302a0405d) Once again, I'm very excited about this library, and how easy it is to load datasets, and to do so without worrying about system memory constraints. Thanks for all your great work. Thanks for the tip @thomwolf ! I did not see that flag in the docs. I'll try with that.
https://github.com/huggingface/datasets/issues/708
Datasets performance slow? - 6.4x slower than in memory dataset
We should add it indeed and also maybe a specific section with all the tips for maximal speed. What do you think @lhoestq @SBrandeis @yjernite ?
I've been very excited about this amazing datasets project. However, I've noticed that the performance can be substantially slower than using an in-memory dataset. Now, this is expected I guess, due to memory mapping data using arrow files, and you don't get anything for free. But I was surprised at how much slower. For example, in the `yelp_polarity` dataset (560000 datapoints, or 17500 batches of 32), it was taking me 3:31 to just get process the data and get it on the GPU (no model involved). Whereas, the equivalent in-memory dataset would finish in just 0:33. Is this expected? Given that one of the goals of this project is also accelerate dataset processing, this seems a bit slower than I would expect. I understand the advantages of being able to work on datasets that exceed memory, and that's very exciting to me, but thought I'd open this issue to discuss. For reference I'm running a AMD Ryzen Threadripper 1900X 8-Core Processor CPU, with 128 GB of RAM and an NVME SSD Samsung 960 EVO. I'm running with an RTX Titan 24GB GPU. I can see with `iotop` that the dataset gets quickly loaded into the system read buffers, and thus doesn't incur any additional IO reads. Thus in theory, all the data *should* be in RAM, but in my benchmark code below it's still 6.4 times slower. What am I doing wrong? And is there a way to force the datasets to completely load into memory instead of being memory mapped in cases where you want maximum performance? At 3:31 for 17500 batches, that's 12ms per batch. Does this 12ms just become insignificant as a proportion of forward and backward passes in practice, and thus it's not worth worrying about this in practice? In any case, here's my code `benchmark.py`. If you run it with an argument of `memory` it will copy the data into memory before executing the same test. ``` py import sys from datasets import load_dataset from transformers import DataCollatorWithPadding, BertTokenizerFast from torch.utils.data import DataLoader from tqdm import tqdm if __name__ == '__main__': tokenizer = BertTokenizerFast.from_pretrained('bert-base-cased') collate_fn = DataCollatorWithPadding(tokenizer, padding=True) ds = load_dataset('yelp_polarity') def do_tokenize(x): return tokenizer(x['text'], truncation=True) ds = ds.map(do_tokenize, batched=True) ds.set_format('torch', ['input_ids', 'token_type_ids', 'attention_mask']) if len(sys.argv) == 2 and sys.argv[1] == 'memory': # copy to memory - probably a faster way to do this - but demonstrates the point # approximately 530 batches per second - 17500 batches in 0:33 print('using memory') _ds = [data for data in tqdm(ds['train'])] else: # approximately 83 batches per second - 17500 batches in 3:31 print('using datasets') _ds = ds['train'] dl = DataLoader(_ds, shuffle=True, collate_fn=collate_fn, batch_size=32, num_workers=4) for data in tqdm(dl): for k, v in data.items(): data[k] = v.to('cuda') ``` For reference, my conda environment is [here](https://gist.github.com/05b6101518ff70ed42a858b302a0405d) Once again, I'm very excited about this library, and how easy it is to load datasets, and to do so without worrying about system memory constraints. Thanks for all your great work.
26
Datasets performance slow? - 6.4x slower than in memory dataset I've been very excited about this amazing datasets project. However, I've noticed that the performance can be substantially slower than using an in-memory dataset. Now, this is expected I guess, due to memory mapping data using arrow files, and you don't get anything for free. But I was surprised at how much slower. For example, in the `yelp_polarity` dataset (560000 datapoints, or 17500 batches of 32), it was taking me 3:31 to just get process the data and get it on the GPU (no model involved). Whereas, the equivalent in-memory dataset would finish in just 0:33. Is this expected? Given that one of the goals of this project is also accelerate dataset processing, this seems a bit slower than I would expect. I understand the advantages of being able to work on datasets that exceed memory, and that's very exciting to me, but thought I'd open this issue to discuss. For reference I'm running a AMD Ryzen Threadripper 1900X 8-Core Processor CPU, with 128 GB of RAM and an NVME SSD Samsung 960 EVO. I'm running with an RTX Titan 24GB GPU. I can see with `iotop` that the dataset gets quickly loaded into the system read buffers, and thus doesn't incur any additional IO reads. Thus in theory, all the data *should* be in RAM, but in my benchmark code below it's still 6.4 times slower. What am I doing wrong? And is there a way to force the datasets to completely load into memory instead of being memory mapped in cases where you want maximum performance? At 3:31 for 17500 batches, that's 12ms per batch. Does this 12ms just become insignificant as a proportion of forward and backward passes in practice, and thus it's not worth worrying about this in practice? In any case, here's my code `benchmark.py`. If you run it with an argument of `memory` it will copy the data into memory before executing the same test. ``` py import sys from datasets import load_dataset from transformers import DataCollatorWithPadding, BertTokenizerFast from torch.utils.data import DataLoader from tqdm import tqdm if __name__ == '__main__': tokenizer = BertTokenizerFast.from_pretrained('bert-base-cased') collate_fn = DataCollatorWithPadding(tokenizer, padding=True) ds = load_dataset('yelp_polarity') def do_tokenize(x): return tokenizer(x['text'], truncation=True) ds = ds.map(do_tokenize, batched=True) ds.set_format('torch', ['input_ids', 'token_type_ids', 'attention_mask']) if len(sys.argv) == 2 and sys.argv[1] == 'memory': # copy to memory - probably a faster way to do this - but demonstrates the point # approximately 530 batches per second - 17500 batches in 0:33 print('using memory') _ds = [data for data in tqdm(ds['train'])] else: # approximately 83 batches per second - 17500 batches in 3:31 print('using datasets') _ds = ds['train'] dl = DataLoader(_ds, shuffle=True, collate_fn=collate_fn, batch_size=32, num_workers=4) for data in tqdm(dl): for k, v in data.items(): data[k] = v.to('cuda') ``` For reference, my conda environment is [here](https://gist.github.com/05b6101518ff70ed42a858b302a0405d) Once again, I'm very excited about this library, and how easy it is to load datasets, and to do so without worrying about system memory constraints. Thanks for all your great work. We should add it indeed and also maybe a specific section with all the tips for maximal speed. What do you think @lhoestq @SBrandeis @yjernite ?
https://github.com/huggingface/datasets/issues/708
Datasets performance slow? - 6.4x slower than in memory dataset
By default the datasets loaded with `load_dataset` live on disk. It's possible to load them in memory by using some transforms like `.map(..., keep_in_memory=True)`. Small correction to @thomwolf 's comment above: currently we don't have the `keep_in_memory` parameter for `load_dataset` AFAIK but it would be nice to add it indeed :)
I've been very excited about this amazing datasets project. However, I've noticed that the performance can be substantially slower than using an in-memory dataset. Now, this is expected I guess, due to memory mapping data using arrow files, and you don't get anything for free. But I was surprised at how much slower. For example, in the `yelp_polarity` dataset (560000 datapoints, or 17500 batches of 32), it was taking me 3:31 to just get process the data and get it on the GPU (no model involved). Whereas, the equivalent in-memory dataset would finish in just 0:33. Is this expected? Given that one of the goals of this project is also accelerate dataset processing, this seems a bit slower than I would expect. I understand the advantages of being able to work on datasets that exceed memory, and that's very exciting to me, but thought I'd open this issue to discuss. For reference I'm running a AMD Ryzen Threadripper 1900X 8-Core Processor CPU, with 128 GB of RAM and an NVME SSD Samsung 960 EVO. I'm running with an RTX Titan 24GB GPU. I can see with `iotop` that the dataset gets quickly loaded into the system read buffers, and thus doesn't incur any additional IO reads. Thus in theory, all the data *should* be in RAM, but in my benchmark code below it's still 6.4 times slower. What am I doing wrong? And is there a way to force the datasets to completely load into memory instead of being memory mapped in cases where you want maximum performance? At 3:31 for 17500 batches, that's 12ms per batch. Does this 12ms just become insignificant as a proportion of forward and backward passes in practice, and thus it's not worth worrying about this in practice? In any case, here's my code `benchmark.py`. If you run it with an argument of `memory` it will copy the data into memory before executing the same test. ``` py import sys from datasets import load_dataset from transformers import DataCollatorWithPadding, BertTokenizerFast from torch.utils.data import DataLoader from tqdm import tqdm if __name__ == '__main__': tokenizer = BertTokenizerFast.from_pretrained('bert-base-cased') collate_fn = DataCollatorWithPadding(tokenizer, padding=True) ds = load_dataset('yelp_polarity') def do_tokenize(x): return tokenizer(x['text'], truncation=True) ds = ds.map(do_tokenize, batched=True) ds.set_format('torch', ['input_ids', 'token_type_ids', 'attention_mask']) if len(sys.argv) == 2 and sys.argv[1] == 'memory': # copy to memory - probably a faster way to do this - but demonstrates the point # approximately 530 batches per second - 17500 batches in 0:33 print('using memory') _ds = [data for data in tqdm(ds['train'])] else: # approximately 83 batches per second - 17500 batches in 3:31 print('using datasets') _ds = ds['train'] dl = DataLoader(_ds, shuffle=True, collate_fn=collate_fn, batch_size=32, num_workers=4) for data in tqdm(dl): for k, v in data.items(): data[k] = v.to('cuda') ``` For reference, my conda environment is [here](https://gist.github.com/05b6101518ff70ed42a858b302a0405d) Once again, I'm very excited about this library, and how easy it is to load datasets, and to do so without worrying about system memory constraints. Thanks for all your great work.
51
Datasets performance slow? - 6.4x slower than in memory dataset I've been very excited about this amazing datasets project. However, I've noticed that the performance can be substantially slower than using an in-memory dataset. Now, this is expected I guess, due to memory mapping data using arrow files, and you don't get anything for free. But I was surprised at how much slower. For example, in the `yelp_polarity` dataset (560000 datapoints, or 17500 batches of 32), it was taking me 3:31 to just get process the data and get it on the GPU (no model involved). Whereas, the equivalent in-memory dataset would finish in just 0:33. Is this expected? Given that one of the goals of this project is also accelerate dataset processing, this seems a bit slower than I would expect. I understand the advantages of being able to work on datasets that exceed memory, and that's very exciting to me, but thought I'd open this issue to discuss. For reference I'm running a AMD Ryzen Threadripper 1900X 8-Core Processor CPU, with 128 GB of RAM and an NVME SSD Samsung 960 EVO. I'm running with an RTX Titan 24GB GPU. I can see with `iotop` that the dataset gets quickly loaded into the system read buffers, and thus doesn't incur any additional IO reads. Thus in theory, all the data *should* be in RAM, but in my benchmark code below it's still 6.4 times slower. What am I doing wrong? And is there a way to force the datasets to completely load into memory instead of being memory mapped in cases where you want maximum performance? At 3:31 for 17500 batches, that's 12ms per batch. Does this 12ms just become insignificant as a proportion of forward and backward passes in practice, and thus it's not worth worrying about this in practice? In any case, here's my code `benchmark.py`. If you run it with an argument of `memory` it will copy the data into memory before executing the same test. ``` py import sys from datasets import load_dataset from transformers import DataCollatorWithPadding, BertTokenizerFast from torch.utils.data import DataLoader from tqdm import tqdm if __name__ == '__main__': tokenizer = BertTokenizerFast.from_pretrained('bert-base-cased') collate_fn = DataCollatorWithPadding(tokenizer, padding=True) ds = load_dataset('yelp_polarity') def do_tokenize(x): return tokenizer(x['text'], truncation=True) ds = ds.map(do_tokenize, batched=True) ds.set_format('torch', ['input_ids', 'token_type_ids', 'attention_mask']) if len(sys.argv) == 2 and sys.argv[1] == 'memory': # copy to memory - probably a faster way to do this - but demonstrates the point # approximately 530 batches per second - 17500 batches in 0:33 print('using memory') _ds = [data for data in tqdm(ds['train'])] else: # approximately 83 batches per second - 17500 batches in 3:31 print('using datasets') _ds = ds['train'] dl = DataLoader(_ds, shuffle=True, collate_fn=collate_fn, batch_size=32, num_workers=4) for data in tqdm(dl): for k, v in data.items(): data[k] = v.to('cuda') ``` For reference, my conda environment is [here](https://gist.github.com/05b6101518ff70ed42a858b302a0405d) Once again, I'm very excited about this library, and how easy it is to load datasets, and to do so without worrying about system memory constraints. Thanks for all your great work. By default the datasets loaded with `load_dataset` live on disk. It's possible to load them in memory by using some transforms like `.map(..., keep_in_memory=True)`. Small correction to @thomwolf 's comment above: currently we don't have the `keep_in_memory` parameter for `load_dataset` AFAIK but it would be nice to add it indeed :)
https://github.com/huggingface/datasets/issues/708
Datasets performance slow? - 6.4x slower than in memory dataset
Great! Thanks a lot. I did a test using `map(..., keep_in_memory=True)` and also a test using in-memory only data. ```python features = dataset.map(tokenize, batched=True, remove_columns=dataset['train'].column_names) features.set_format(type='torch', columns=['input_ids', 'token_type_ids', 'attention_mask']) features_in_memory = dataset.map(tokenize, batched=True, keep_in_memory=True, remove_columns=dataset['train'].column_names) features_in_memory.set_format(type='torch', columns=['input_ids', 'token_type_ids', 'attention_mask']) in_memory = [features['train'][i] for i in range(len(features['train']))] ``` For using the features without any tweak, I got **1min17s** for copying the entire DataLoader to CUDA: ``` %%time for i, batch in enumerate(DataLoader(features['train'], batch_size=16, num_workers=4)): batch['input_ids'].to(device) ``` For using the features mapped with `keep_in_memory=True`, I also got **1min17s** for copying the entire DataLoader to CUDA: ``` %%time for i, batch in enumerate(DataLoader(features_in_memory['train'], batch_size=16, num_workers=4)): batch['input_ids'].to(device) ``` And for the case using every element in memory, converted from the original dataset, I got **12.5s**: ``` %%time for i, batch in enumerate(DataLoader(in_memory, batch_size=16, num_workers=4)): batch['input_ids'].to(device) ``` Taking a closer look in my SQuAD code, using a profiler, I see a lot of calls to `posix read` api. It seems that it is really reliying on disk, which results in a very high train time.
I've been very excited about this amazing datasets project. However, I've noticed that the performance can be substantially slower than using an in-memory dataset. Now, this is expected I guess, due to memory mapping data using arrow files, and you don't get anything for free. But I was surprised at how much slower. For example, in the `yelp_polarity` dataset (560000 datapoints, or 17500 batches of 32), it was taking me 3:31 to just get process the data and get it on the GPU (no model involved). Whereas, the equivalent in-memory dataset would finish in just 0:33. Is this expected? Given that one of the goals of this project is also accelerate dataset processing, this seems a bit slower than I would expect. I understand the advantages of being able to work on datasets that exceed memory, and that's very exciting to me, but thought I'd open this issue to discuss. For reference I'm running a AMD Ryzen Threadripper 1900X 8-Core Processor CPU, with 128 GB of RAM and an NVME SSD Samsung 960 EVO. I'm running with an RTX Titan 24GB GPU. I can see with `iotop` that the dataset gets quickly loaded into the system read buffers, and thus doesn't incur any additional IO reads. Thus in theory, all the data *should* be in RAM, but in my benchmark code below it's still 6.4 times slower. What am I doing wrong? And is there a way to force the datasets to completely load into memory instead of being memory mapped in cases where you want maximum performance? At 3:31 for 17500 batches, that's 12ms per batch. Does this 12ms just become insignificant as a proportion of forward and backward passes in practice, and thus it's not worth worrying about this in practice? In any case, here's my code `benchmark.py`. If you run it with an argument of `memory` it will copy the data into memory before executing the same test. ``` py import sys from datasets import load_dataset from transformers import DataCollatorWithPadding, BertTokenizerFast from torch.utils.data import DataLoader from tqdm import tqdm if __name__ == '__main__': tokenizer = BertTokenizerFast.from_pretrained('bert-base-cased') collate_fn = DataCollatorWithPadding(tokenizer, padding=True) ds = load_dataset('yelp_polarity') def do_tokenize(x): return tokenizer(x['text'], truncation=True) ds = ds.map(do_tokenize, batched=True) ds.set_format('torch', ['input_ids', 'token_type_ids', 'attention_mask']) if len(sys.argv) == 2 and sys.argv[1] == 'memory': # copy to memory - probably a faster way to do this - but demonstrates the point # approximately 530 batches per second - 17500 batches in 0:33 print('using memory') _ds = [data for data in tqdm(ds['train'])] else: # approximately 83 batches per second - 17500 batches in 3:31 print('using datasets') _ds = ds['train'] dl = DataLoader(_ds, shuffle=True, collate_fn=collate_fn, batch_size=32, num_workers=4) for data in tqdm(dl): for k, v in data.items(): data[k] = v.to('cuda') ``` For reference, my conda environment is [here](https://gist.github.com/05b6101518ff70ed42a858b302a0405d) Once again, I'm very excited about this library, and how easy it is to load datasets, and to do so without worrying about system memory constraints. Thanks for all your great work.
170
Datasets performance slow? - 6.4x slower than in memory dataset I've been very excited about this amazing datasets project. However, I've noticed that the performance can be substantially slower than using an in-memory dataset. Now, this is expected I guess, due to memory mapping data using arrow files, and you don't get anything for free. But I was surprised at how much slower. For example, in the `yelp_polarity` dataset (560000 datapoints, or 17500 batches of 32), it was taking me 3:31 to just get process the data and get it on the GPU (no model involved). Whereas, the equivalent in-memory dataset would finish in just 0:33. Is this expected? Given that one of the goals of this project is also accelerate dataset processing, this seems a bit slower than I would expect. I understand the advantages of being able to work on datasets that exceed memory, and that's very exciting to me, but thought I'd open this issue to discuss. For reference I'm running a AMD Ryzen Threadripper 1900X 8-Core Processor CPU, with 128 GB of RAM and an NVME SSD Samsung 960 EVO. I'm running with an RTX Titan 24GB GPU. I can see with `iotop` that the dataset gets quickly loaded into the system read buffers, and thus doesn't incur any additional IO reads. Thus in theory, all the data *should* be in RAM, but in my benchmark code below it's still 6.4 times slower. What am I doing wrong? And is there a way to force the datasets to completely load into memory instead of being memory mapped in cases where you want maximum performance? At 3:31 for 17500 batches, that's 12ms per batch. Does this 12ms just become insignificant as a proportion of forward and backward passes in practice, and thus it's not worth worrying about this in practice? In any case, here's my code `benchmark.py`. If you run it with an argument of `memory` it will copy the data into memory before executing the same test. ``` py import sys from datasets import load_dataset from transformers import DataCollatorWithPadding, BertTokenizerFast from torch.utils.data import DataLoader from tqdm import tqdm if __name__ == '__main__': tokenizer = BertTokenizerFast.from_pretrained('bert-base-cased') collate_fn = DataCollatorWithPadding(tokenizer, padding=True) ds = load_dataset('yelp_polarity') def do_tokenize(x): return tokenizer(x['text'], truncation=True) ds = ds.map(do_tokenize, batched=True) ds.set_format('torch', ['input_ids', 'token_type_ids', 'attention_mask']) if len(sys.argv) == 2 and sys.argv[1] == 'memory': # copy to memory - probably a faster way to do this - but demonstrates the point # approximately 530 batches per second - 17500 batches in 0:33 print('using memory') _ds = [data for data in tqdm(ds['train'])] else: # approximately 83 batches per second - 17500 batches in 3:31 print('using datasets') _ds = ds['train'] dl = DataLoader(_ds, shuffle=True, collate_fn=collate_fn, batch_size=32, num_workers=4) for data in tqdm(dl): for k, v in data.items(): data[k] = v.to('cuda') ``` For reference, my conda environment is [here](https://gist.github.com/05b6101518ff70ed42a858b302a0405d) Once again, I'm very excited about this library, and how easy it is to load datasets, and to do so without worrying about system memory constraints. Thanks for all your great work. Great! Thanks a lot. I did a test using `map(..., keep_in_memory=True)` and also a test using in-memory only data. ```python features = dataset.map(tokenize, batched=True, remove_columns=dataset['train'].column_names) features.set_format(type='torch', columns=['input_ids', 'token_type_ids', 'attention_mask']) features_in_memory = dataset.map(tokenize, batched=True, keep_in_memory=True, remove_columns=dataset['train'].column_names) features_in_memory.set_format(type='torch', columns=['input_ids', 'token_type_ids', 'attention_mask']) in_memory = [features['train'][i] for i in range(len(features['train']))] ``` For using the features without any tweak, I got **1min17s** for copying the entire DataLoader to CUDA: ``` %%time for i, batch in enumerate(DataLoader(features['train'], batch_size=16, num_workers=4)): batch['input_ids'].to(device) ``` For using the features mapped with `keep_in_memory=True`, I also got **1min17s** for copying the entire DataLoader to CUDA: ``` %%time for i, batch in enumerate(DataLoader(features_in_memory['train'], batch_size=16, num_workers=4)): batch['input_ids'].to(device) ``` And for the case using every element in memory, converted from the original dataset, I got **12.5s**: ``` %%time for i, batch in enumerate(DataLoader(in_memory, batch_size=16, num_workers=4)): batch['input_ids'].to(device) ``` Taking a closer look in my SQuAD code, using a profiler, I see a lot of calls to `posix read` api. It seems that it is really reliying on disk, which results in a very high train time.
https://github.com/huggingface/datasets/issues/708
Datasets performance slow? - 6.4x slower than in memory dataset
I am having the same issue here. When loading from memory I can get the GPU up to 70% util but when loading after mapping I can only get 40%. In disk: ``` book_corpus = load_dataset('bookcorpus', 'plain_text', cache_dir='/home/ad/Desktop/bookcorpus', split='train[:20%]') book_corpus = book_corpus.map(encode, batched=True, num_proc=20, load_from_cache_file=True, batch_size=2500) book_corpus.set_format(type='torch', columns=['text', "input_ids", "attention_mask", "token_type_ids"]) training_args = TrainingArguments( output_dir="./mobile_bert_big", overwrite_output_dir=True, num_train_epochs=1, per_device_train_batch_size=32, per_device_eval_batch_size=16, save_steps=50, save_total_limit=2, logging_first_step=True, warmup_steps=100, logging_steps=50, eval_steps=100, no_cuda=False, gradient_accumulation_steps=16, fp16=True) trainer = Trainer( model=model, args=training_args, data_collator=data_collator, train_dataset=book_corpus, tokenizer=tokenizer) ``` In disk I can only get 0,17 it/s: `[ 13/28907 01:03 < 46:03:27, 0.17 it/s, Epoch 0.00/1] ` If I load it with torch.utils.data.Dataset() ``` class BCorpusDataset(torch.utils.data.Dataset): def __init__(self, encodings): self.encodings = encodings def __getitem__(self, idx): item = [torch.tensor(val[idx]) for key, val in self.encodings.items()][0] return item def __len__(self): length = [len(val) for key, val in self.encodings.items()][0] return length **book_corpus = book_corpus.select([i for i in range(16*2000)])** # filtering to not have 20% of BC in memory... book_corpus = book_corpus(book_corpus) ``` I can get: ` [ 5/62 00:09 < 03:03, 0.31 it/s, Epoch 0.06/1]` But obviously I can not get BookCorpus in memory xD EDIT: it is something weird. If i load in disk 1% of bookcorpus: ``` book_corpus = load_dataset('bookcorpus', 'plain_text', cache_dir='/home/ad/Desktop/bookcorpus', split='train[:1%]') ``` I can get 0.28 it/s, (the same that in memory) but if I load 20% of bookcorpus: ``` book_corpus = load_dataset('bookcorpus', 'plain_text', cache_dir='/home/ad/Desktop/bookcorpus', split='train[:20%]') ``` I get again 0.17 it/s. I am missing something? I think it is something related to size, and not disk or in-memory.
I've been very excited about this amazing datasets project. However, I've noticed that the performance can be substantially slower than using an in-memory dataset. Now, this is expected I guess, due to memory mapping data using arrow files, and you don't get anything for free. But I was surprised at how much slower. For example, in the `yelp_polarity` dataset (560000 datapoints, or 17500 batches of 32), it was taking me 3:31 to just get process the data and get it on the GPU (no model involved). Whereas, the equivalent in-memory dataset would finish in just 0:33. Is this expected? Given that one of the goals of this project is also accelerate dataset processing, this seems a bit slower than I would expect. I understand the advantages of being able to work on datasets that exceed memory, and that's very exciting to me, but thought I'd open this issue to discuss. For reference I'm running a AMD Ryzen Threadripper 1900X 8-Core Processor CPU, with 128 GB of RAM and an NVME SSD Samsung 960 EVO. I'm running with an RTX Titan 24GB GPU. I can see with `iotop` that the dataset gets quickly loaded into the system read buffers, and thus doesn't incur any additional IO reads. Thus in theory, all the data *should* be in RAM, but in my benchmark code below it's still 6.4 times slower. What am I doing wrong? And is there a way to force the datasets to completely load into memory instead of being memory mapped in cases where you want maximum performance? At 3:31 for 17500 batches, that's 12ms per batch. Does this 12ms just become insignificant as a proportion of forward and backward passes in practice, and thus it's not worth worrying about this in practice? In any case, here's my code `benchmark.py`. If you run it with an argument of `memory` it will copy the data into memory before executing the same test. ``` py import sys from datasets import load_dataset from transformers import DataCollatorWithPadding, BertTokenizerFast from torch.utils.data import DataLoader from tqdm import tqdm if __name__ == '__main__': tokenizer = BertTokenizerFast.from_pretrained('bert-base-cased') collate_fn = DataCollatorWithPadding(tokenizer, padding=True) ds = load_dataset('yelp_polarity') def do_tokenize(x): return tokenizer(x['text'], truncation=True) ds = ds.map(do_tokenize, batched=True) ds.set_format('torch', ['input_ids', 'token_type_ids', 'attention_mask']) if len(sys.argv) == 2 and sys.argv[1] == 'memory': # copy to memory - probably a faster way to do this - but demonstrates the point # approximately 530 batches per second - 17500 batches in 0:33 print('using memory') _ds = [data for data in tqdm(ds['train'])] else: # approximately 83 batches per second - 17500 batches in 3:31 print('using datasets') _ds = ds['train'] dl = DataLoader(_ds, shuffle=True, collate_fn=collate_fn, batch_size=32, num_workers=4) for data in tqdm(dl): for k, v in data.items(): data[k] = v.to('cuda') ``` For reference, my conda environment is [here](https://gist.github.com/05b6101518ff70ed42a858b302a0405d) Once again, I'm very excited about this library, and how easy it is to load datasets, and to do so without worrying about system memory constraints. Thanks for all your great work.
247
Datasets performance slow? - 6.4x slower than in memory dataset I've been very excited about this amazing datasets project. However, I've noticed that the performance can be substantially slower than using an in-memory dataset. Now, this is expected I guess, due to memory mapping data using arrow files, and you don't get anything for free. But I was surprised at how much slower. For example, in the `yelp_polarity` dataset (560000 datapoints, or 17500 batches of 32), it was taking me 3:31 to just get process the data and get it on the GPU (no model involved). Whereas, the equivalent in-memory dataset would finish in just 0:33. Is this expected? Given that one of the goals of this project is also accelerate dataset processing, this seems a bit slower than I would expect. I understand the advantages of being able to work on datasets that exceed memory, and that's very exciting to me, but thought I'd open this issue to discuss. For reference I'm running a AMD Ryzen Threadripper 1900X 8-Core Processor CPU, with 128 GB of RAM and an NVME SSD Samsung 960 EVO. I'm running with an RTX Titan 24GB GPU. I can see with `iotop` that the dataset gets quickly loaded into the system read buffers, and thus doesn't incur any additional IO reads. Thus in theory, all the data *should* be in RAM, but in my benchmark code below it's still 6.4 times slower. What am I doing wrong? And is there a way to force the datasets to completely load into memory instead of being memory mapped in cases where you want maximum performance? At 3:31 for 17500 batches, that's 12ms per batch. Does this 12ms just become insignificant as a proportion of forward and backward passes in practice, and thus it's not worth worrying about this in practice? In any case, here's my code `benchmark.py`. If you run it with an argument of `memory` it will copy the data into memory before executing the same test. ``` py import sys from datasets import load_dataset from transformers import DataCollatorWithPadding, BertTokenizerFast from torch.utils.data import DataLoader from tqdm import tqdm if __name__ == '__main__': tokenizer = BertTokenizerFast.from_pretrained('bert-base-cased') collate_fn = DataCollatorWithPadding(tokenizer, padding=True) ds = load_dataset('yelp_polarity') def do_tokenize(x): return tokenizer(x['text'], truncation=True) ds = ds.map(do_tokenize, batched=True) ds.set_format('torch', ['input_ids', 'token_type_ids', 'attention_mask']) if len(sys.argv) == 2 and sys.argv[1] == 'memory': # copy to memory - probably a faster way to do this - but demonstrates the point # approximately 530 batches per second - 17500 batches in 0:33 print('using memory') _ds = [data for data in tqdm(ds['train'])] else: # approximately 83 batches per second - 17500 batches in 3:31 print('using datasets') _ds = ds['train'] dl = DataLoader(_ds, shuffle=True, collate_fn=collate_fn, batch_size=32, num_workers=4) for data in tqdm(dl): for k, v in data.items(): data[k] = v.to('cuda') ``` For reference, my conda environment is [here](https://gist.github.com/05b6101518ff70ed42a858b302a0405d) Once again, I'm very excited about this library, and how easy it is to load datasets, and to do so without worrying about system memory constraints. Thanks for all your great work. I am having the same issue here. When loading from memory I can get the GPU up to 70% util but when loading after mapping I can only get 40%. In disk: ``` book_corpus = load_dataset('bookcorpus', 'plain_text', cache_dir='/home/ad/Desktop/bookcorpus', split='train[:20%]') book_corpus = book_corpus.map(encode, batched=True, num_proc=20, load_from_cache_file=True, batch_size=2500) book_corpus.set_format(type='torch', columns=['text', "input_ids", "attention_mask", "token_type_ids"]) training_args = TrainingArguments( output_dir="./mobile_bert_big", overwrite_output_dir=True, num_train_epochs=1, per_device_train_batch_size=32, per_device_eval_batch_size=16, save_steps=50, save_total_limit=2, logging_first_step=True, warmup_steps=100, logging_steps=50, eval_steps=100, no_cuda=False, gradient_accumulation_steps=16, fp16=True) trainer = Trainer( model=model, args=training_args, data_collator=data_collator, train_dataset=book_corpus, tokenizer=tokenizer) ``` In disk I can only get 0,17 it/s: `[ 13/28907 01:03 < 46:03:27, 0.17 it/s, Epoch 0.00/1] ` If I load it with torch.utils.data.Dataset() ``` class BCorpusDataset(torch.utils.data.Dataset): def __init__(self, encodings): self.encodings = encodings def __getitem__(self, idx): item = [torch.tensor(val[idx]) for key, val in self.encodings.items()][0] return item def __len__(self): length = [len(val) for key, val in self.encodings.items()][0] return length **book_corpus = book_corpus.select([i for i in range(16*2000)])** # filtering to not have 20% of BC in memory... book_corpus = book_corpus(book_corpus) ``` I can get: ` [ 5/62 00:09 < 03:03, 0.31 it/s, Epoch 0.06/1]` But obviously I can not get BookCorpus in memory xD EDIT: it is something weird. If i load in disk 1% of bookcorpus: ``` book_corpus = load_dataset('bookcorpus', 'plain_text', cache_dir='/home/ad/Desktop/bookcorpus', split='train[:1%]') ``` I can get 0.28 it/s, (the same that in memory) but if I load 20% of bookcorpus: ``` book_corpus = load_dataset('bookcorpus', 'plain_text', cache_dir='/home/ad/Desktop/bookcorpus', split='train[:20%]') ``` I get again 0.17 it/s. I am missing something? I think it is something related to size, and not disk or in-memory.
https://github.com/huggingface/datasets/issues/708
Datasets performance slow? - 6.4x slower than in memory dataset
There is a way to increase the batches read from memory? or multiprocessed it? I think that one of two or it is reading with just 1 core o it is reading very small chunks from disk and left my GPU at 0 between batches
I've been very excited about this amazing datasets project. However, I've noticed that the performance can be substantially slower than using an in-memory dataset. Now, this is expected I guess, due to memory mapping data using arrow files, and you don't get anything for free. But I was surprised at how much slower. For example, in the `yelp_polarity` dataset (560000 datapoints, or 17500 batches of 32), it was taking me 3:31 to just get process the data and get it on the GPU (no model involved). Whereas, the equivalent in-memory dataset would finish in just 0:33. Is this expected? Given that one of the goals of this project is also accelerate dataset processing, this seems a bit slower than I would expect. I understand the advantages of being able to work on datasets that exceed memory, and that's very exciting to me, but thought I'd open this issue to discuss. For reference I'm running a AMD Ryzen Threadripper 1900X 8-Core Processor CPU, with 128 GB of RAM and an NVME SSD Samsung 960 EVO. I'm running with an RTX Titan 24GB GPU. I can see with `iotop` that the dataset gets quickly loaded into the system read buffers, and thus doesn't incur any additional IO reads. Thus in theory, all the data *should* be in RAM, but in my benchmark code below it's still 6.4 times slower. What am I doing wrong? And is there a way to force the datasets to completely load into memory instead of being memory mapped in cases where you want maximum performance? At 3:31 for 17500 batches, that's 12ms per batch. Does this 12ms just become insignificant as a proportion of forward and backward passes in practice, and thus it's not worth worrying about this in practice? In any case, here's my code `benchmark.py`. If you run it with an argument of `memory` it will copy the data into memory before executing the same test. ``` py import sys from datasets import load_dataset from transformers import DataCollatorWithPadding, BertTokenizerFast from torch.utils.data import DataLoader from tqdm import tqdm if __name__ == '__main__': tokenizer = BertTokenizerFast.from_pretrained('bert-base-cased') collate_fn = DataCollatorWithPadding(tokenizer, padding=True) ds = load_dataset('yelp_polarity') def do_tokenize(x): return tokenizer(x['text'], truncation=True) ds = ds.map(do_tokenize, batched=True) ds.set_format('torch', ['input_ids', 'token_type_ids', 'attention_mask']) if len(sys.argv) == 2 and sys.argv[1] == 'memory': # copy to memory - probably a faster way to do this - but demonstrates the point # approximately 530 batches per second - 17500 batches in 0:33 print('using memory') _ds = [data for data in tqdm(ds['train'])] else: # approximately 83 batches per second - 17500 batches in 3:31 print('using datasets') _ds = ds['train'] dl = DataLoader(_ds, shuffle=True, collate_fn=collate_fn, batch_size=32, num_workers=4) for data in tqdm(dl): for k, v in data.items(): data[k] = v.to('cuda') ``` For reference, my conda environment is [here](https://gist.github.com/05b6101518ff70ed42a858b302a0405d) Once again, I'm very excited about this library, and how easy it is to load datasets, and to do so without worrying about system memory constraints. Thanks for all your great work.
45
Datasets performance slow? - 6.4x slower than in memory dataset I've been very excited about this amazing datasets project. However, I've noticed that the performance can be substantially slower than using an in-memory dataset. Now, this is expected I guess, due to memory mapping data using arrow files, and you don't get anything for free. But I was surprised at how much slower. For example, in the `yelp_polarity` dataset (560000 datapoints, or 17500 batches of 32), it was taking me 3:31 to just get process the data and get it on the GPU (no model involved). Whereas, the equivalent in-memory dataset would finish in just 0:33. Is this expected? Given that one of the goals of this project is also accelerate dataset processing, this seems a bit slower than I would expect. I understand the advantages of being able to work on datasets that exceed memory, and that's very exciting to me, but thought I'd open this issue to discuss. For reference I'm running a AMD Ryzen Threadripper 1900X 8-Core Processor CPU, with 128 GB of RAM and an NVME SSD Samsung 960 EVO. I'm running with an RTX Titan 24GB GPU. I can see with `iotop` that the dataset gets quickly loaded into the system read buffers, and thus doesn't incur any additional IO reads. Thus in theory, all the data *should* be in RAM, but in my benchmark code below it's still 6.4 times slower. What am I doing wrong? And is there a way to force the datasets to completely load into memory instead of being memory mapped in cases where you want maximum performance? At 3:31 for 17500 batches, that's 12ms per batch. Does this 12ms just become insignificant as a proportion of forward and backward passes in practice, and thus it's not worth worrying about this in practice? In any case, here's my code `benchmark.py`. If you run it with an argument of `memory` it will copy the data into memory before executing the same test. ``` py import sys from datasets import load_dataset from transformers import DataCollatorWithPadding, BertTokenizerFast from torch.utils.data import DataLoader from tqdm import tqdm if __name__ == '__main__': tokenizer = BertTokenizerFast.from_pretrained('bert-base-cased') collate_fn = DataCollatorWithPadding(tokenizer, padding=True) ds = load_dataset('yelp_polarity') def do_tokenize(x): return tokenizer(x['text'], truncation=True) ds = ds.map(do_tokenize, batched=True) ds.set_format('torch', ['input_ids', 'token_type_ids', 'attention_mask']) if len(sys.argv) == 2 and sys.argv[1] == 'memory': # copy to memory - probably a faster way to do this - but demonstrates the point # approximately 530 batches per second - 17500 batches in 0:33 print('using memory') _ds = [data for data in tqdm(ds['train'])] else: # approximately 83 batches per second - 17500 batches in 3:31 print('using datasets') _ds = ds['train'] dl = DataLoader(_ds, shuffle=True, collate_fn=collate_fn, batch_size=32, num_workers=4) for data in tqdm(dl): for k, v in data.items(): data[k] = v.to('cuda') ``` For reference, my conda environment is [here](https://gist.github.com/05b6101518ff70ed42a858b302a0405d) Once again, I'm very excited about this library, and how easy it is to load datasets, and to do so without worrying about system memory constraints. Thanks for all your great work. There is a way to increase the batches read from memory? or multiprocessed it? I think that one of two or it is reading with just 1 core o it is reading very small chunks from disk and left my GPU at 0 between batches
https://github.com/huggingface/datasets/issues/708
Datasets performance slow? - 6.4x slower than in memory dataset
My fault! I had not seen the `dataloader_num_workers` in `TrainingArguments` ! Now I can parallelize and go fast! Sorry, and thanks.
I've been very excited about this amazing datasets project. However, I've noticed that the performance can be substantially slower than using an in-memory dataset. Now, this is expected I guess, due to memory mapping data using arrow files, and you don't get anything for free. But I was surprised at how much slower. For example, in the `yelp_polarity` dataset (560000 datapoints, or 17500 batches of 32), it was taking me 3:31 to just get process the data and get it on the GPU (no model involved). Whereas, the equivalent in-memory dataset would finish in just 0:33. Is this expected? Given that one of the goals of this project is also accelerate dataset processing, this seems a bit slower than I would expect. I understand the advantages of being able to work on datasets that exceed memory, and that's very exciting to me, but thought I'd open this issue to discuss. For reference I'm running a AMD Ryzen Threadripper 1900X 8-Core Processor CPU, with 128 GB of RAM and an NVME SSD Samsung 960 EVO. I'm running with an RTX Titan 24GB GPU. I can see with `iotop` that the dataset gets quickly loaded into the system read buffers, and thus doesn't incur any additional IO reads. Thus in theory, all the data *should* be in RAM, but in my benchmark code below it's still 6.4 times slower. What am I doing wrong? And is there a way to force the datasets to completely load into memory instead of being memory mapped in cases where you want maximum performance? At 3:31 for 17500 batches, that's 12ms per batch. Does this 12ms just become insignificant as a proportion of forward and backward passes in practice, and thus it's not worth worrying about this in practice? In any case, here's my code `benchmark.py`. If you run it with an argument of `memory` it will copy the data into memory before executing the same test. ``` py import sys from datasets import load_dataset from transformers import DataCollatorWithPadding, BertTokenizerFast from torch.utils.data import DataLoader from tqdm import tqdm if __name__ == '__main__': tokenizer = BertTokenizerFast.from_pretrained('bert-base-cased') collate_fn = DataCollatorWithPadding(tokenizer, padding=True) ds = load_dataset('yelp_polarity') def do_tokenize(x): return tokenizer(x['text'], truncation=True) ds = ds.map(do_tokenize, batched=True) ds.set_format('torch', ['input_ids', 'token_type_ids', 'attention_mask']) if len(sys.argv) == 2 and sys.argv[1] == 'memory': # copy to memory - probably a faster way to do this - but demonstrates the point # approximately 530 batches per second - 17500 batches in 0:33 print('using memory') _ds = [data for data in tqdm(ds['train'])] else: # approximately 83 batches per second - 17500 batches in 3:31 print('using datasets') _ds = ds['train'] dl = DataLoader(_ds, shuffle=True, collate_fn=collate_fn, batch_size=32, num_workers=4) for data in tqdm(dl): for k, v in data.items(): data[k] = v.to('cuda') ``` For reference, my conda environment is [here](https://gist.github.com/05b6101518ff70ed42a858b302a0405d) Once again, I'm very excited about this library, and how easy it is to load datasets, and to do so without worrying about system memory constraints. Thanks for all your great work.
21
Datasets performance slow? - 6.4x slower than in memory dataset I've been very excited about this amazing datasets project. However, I've noticed that the performance can be substantially slower than using an in-memory dataset. Now, this is expected I guess, due to memory mapping data using arrow files, and you don't get anything for free. But I was surprised at how much slower. For example, in the `yelp_polarity` dataset (560000 datapoints, or 17500 batches of 32), it was taking me 3:31 to just get process the data and get it on the GPU (no model involved). Whereas, the equivalent in-memory dataset would finish in just 0:33. Is this expected? Given that one of the goals of this project is also accelerate dataset processing, this seems a bit slower than I would expect. I understand the advantages of being able to work on datasets that exceed memory, and that's very exciting to me, but thought I'd open this issue to discuss. For reference I'm running a AMD Ryzen Threadripper 1900X 8-Core Processor CPU, with 128 GB of RAM and an NVME SSD Samsung 960 EVO. I'm running with an RTX Titan 24GB GPU. I can see with `iotop` that the dataset gets quickly loaded into the system read buffers, and thus doesn't incur any additional IO reads. Thus in theory, all the data *should* be in RAM, but in my benchmark code below it's still 6.4 times slower. What am I doing wrong? And is there a way to force the datasets to completely load into memory instead of being memory mapped in cases where you want maximum performance? At 3:31 for 17500 batches, that's 12ms per batch. Does this 12ms just become insignificant as a proportion of forward and backward passes in practice, and thus it's not worth worrying about this in practice? In any case, here's my code `benchmark.py`. If you run it with an argument of `memory` it will copy the data into memory before executing the same test. ``` py import sys from datasets import load_dataset from transformers import DataCollatorWithPadding, BertTokenizerFast from torch.utils.data import DataLoader from tqdm import tqdm if __name__ == '__main__': tokenizer = BertTokenizerFast.from_pretrained('bert-base-cased') collate_fn = DataCollatorWithPadding(tokenizer, padding=True) ds = load_dataset('yelp_polarity') def do_tokenize(x): return tokenizer(x['text'], truncation=True) ds = ds.map(do_tokenize, batched=True) ds.set_format('torch', ['input_ids', 'token_type_ids', 'attention_mask']) if len(sys.argv) == 2 and sys.argv[1] == 'memory': # copy to memory - probably a faster way to do this - but demonstrates the point # approximately 530 batches per second - 17500 batches in 0:33 print('using memory') _ds = [data for data in tqdm(ds['train'])] else: # approximately 83 batches per second - 17500 batches in 3:31 print('using datasets') _ds = ds['train'] dl = DataLoader(_ds, shuffle=True, collate_fn=collate_fn, batch_size=32, num_workers=4) for data in tqdm(dl): for k, v in data.items(): data[k] = v.to('cuda') ``` For reference, my conda environment is [here](https://gist.github.com/05b6101518ff70ed42a858b302a0405d) Once again, I'm very excited about this library, and how easy it is to load datasets, and to do so without worrying about system memory constraints. Thanks for all your great work. My fault! I had not seen the `dataloader_num_workers` in `TrainingArguments` ! Now I can parallelize and go fast! Sorry, and thanks.
https://github.com/huggingface/datasets/issues/707
Requirements should specify pyarrow<1
@punitaojha, certainly. Feel free to work on this. Let me know if you need any help or clarity.
I was looking at the docs on [Perplexity](https://huggingface.co/transformers/perplexity.html) via GPT2. When you load datasets and try to load Wikitext, you get the error, ``` module 'pyarrow' has no attribute 'PyExtensionType' ``` I traced it back to datasets having installed PyArrow 1.0.1 but there's not pinning in the setup file. https://github.com/huggingface/datasets/blob/e86a2a8f869b91654e782c9133d810bb82783200/setup.py#L68 Downgrading by installing `pip install "pyarrow<1"` resolved the issue.
18
Requirements should specify pyarrow<1 I was looking at the docs on [Perplexity](https://huggingface.co/transformers/perplexity.html) via GPT2. When you load datasets and try to load Wikitext, you get the error, ``` module 'pyarrow' has no attribute 'PyExtensionType' ``` I traced it back to datasets having installed PyArrow 1.0.1 but there's not pinning in the setup file. https://github.com/huggingface/datasets/blob/e86a2a8f869b91654e782c9133d810bb82783200/setup.py#L68 Downgrading by installing `pip install "pyarrow<1"` resolved the issue. @punitaojha, certainly. Feel free to work on this. Let me know if you need any help or clarity.
https://github.com/huggingface/datasets/issues/707
Requirements should specify pyarrow<1
Hello @mathcass 1. I did fork the repository and clone the same on my local system. 2. Then learnt about how we can publish our package on pypi.org. Also, found some instructions on same in setup.py documentation. 3. Then I Perplexity document link that you shared above. I created a colab link from there keep both tensorflow and pytorch means a mixed option and tried to run it in colab but I encountered no errors at a point where you mentioned. Can you help me to figure out the issue. 4.Here is the link of the colab file with my saved responses. https://colab.research.google.com/drive/1hfYz8Ira39FnREbxgwa_goZWpOojp2NH?usp=sharing
I was looking at the docs on [Perplexity](https://huggingface.co/transformers/perplexity.html) via GPT2. When you load datasets and try to load Wikitext, you get the error, ``` module 'pyarrow' has no attribute 'PyExtensionType' ``` I traced it back to datasets having installed PyArrow 1.0.1 but there's not pinning in the setup file. https://github.com/huggingface/datasets/blob/e86a2a8f869b91654e782c9133d810bb82783200/setup.py#L68 Downgrading by installing `pip install "pyarrow<1"` resolved the issue.
103
Requirements should specify pyarrow<1 I was looking at the docs on [Perplexity](https://huggingface.co/transformers/perplexity.html) via GPT2. When you load datasets and try to load Wikitext, you get the error, ``` module 'pyarrow' has no attribute 'PyExtensionType' ``` I traced it back to datasets having installed PyArrow 1.0.1 but there's not pinning in the setup file. https://github.com/huggingface/datasets/blob/e86a2a8f869b91654e782c9133d810bb82783200/setup.py#L68 Downgrading by installing `pip install "pyarrow<1"` resolved the issue. Hello @mathcass 1. I did fork the repository and clone the same on my local system. 2. Then learnt about how we can publish our package on pypi.org. Also, found some instructions on same in setup.py documentation. 3. Then I Perplexity document link that you shared above. I created a colab link from there keep both tensorflow and pytorch means a mixed option and tried to run it in colab but I encountered no errors at a point where you mentioned. Can you help me to figure out the issue. 4.Here is the link of the colab file with my saved responses. https://colab.research.google.com/drive/1hfYz8Ira39FnREbxgwa_goZWpOojp2NH?usp=sharing
https://github.com/huggingface/datasets/issues/707
Requirements should specify pyarrow<1
Thanks for looking at this @punitaojha and thanks for sharing the notebook. I just tried to reproduce this on my own (based on the environment where I had this issue) and I can't reproduce it somehow. If I run into this again, I'll include some steps to reproduce it. I'll close this as invalid. Thanks again.
I was looking at the docs on [Perplexity](https://huggingface.co/transformers/perplexity.html) via GPT2. When you load datasets and try to load Wikitext, you get the error, ``` module 'pyarrow' has no attribute 'PyExtensionType' ``` I traced it back to datasets having installed PyArrow 1.0.1 but there's not pinning in the setup file. https://github.com/huggingface/datasets/blob/e86a2a8f869b91654e782c9133d810bb82783200/setup.py#L68 Downgrading by installing `pip install "pyarrow<1"` resolved the issue.
56
Requirements should specify pyarrow<1 I was looking at the docs on [Perplexity](https://huggingface.co/transformers/perplexity.html) via GPT2. When you load datasets and try to load Wikitext, you get the error, ``` module 'pyarrow' has no attribute 'PyExtensionType' ``` I traced it back to datasets having installed PyArrow 1.0.1 but there's not pinning in the setup file. https://github.com/huggingface/datasets/blob/e86a2a8f869b91654e782c9133d810bb82783200/setup.py#L68 Downgrading by installing `pip install "pyarrow<1"` resolved the issue. Thanks for looking at this @punitaojha and thanks for sharing the notebook. I just tried to reproduce this on my own (based on the environment where I had this issue) and I can't reproduce it somehow. If I run into this again, I'll include some steps to reproduce it. I'll close this as invalid. Thanks again.
https://github.com/huggingface/datasets/issues/707
Requirements should specify pyarrow<1
I am sorry for hijacking this closed issue, but I believe I was able to reproduce this very issue. Strangely enough, it also turned out that running `pip install "pyarrow<1" --upgrade` did indeed fix the issue (PyArrow was installed in version `0.14.1` in my case). Please see the Colab below: https://colab.research.google.com/drive/15QQS3xWjlKW2aK0J74eEcRFuhXUddUST Thanks!
I was looking at the docs on [Perplexity](https://huggingface.co/transformers/perplexity.html) via GPT2. When you load datasets and try to load Wikitext, you get the error, ``` module 'pyarrow' has no attribute 'PyExtensionType' ``` I traced it back to datasets having installed PyArrow 1.0.1 but there's not pinning in the setup file. https://github.com/huggingface/datasets/blob/e86a2a8f869b91654e782c9133d810bb82783200/setup.py#L68 Downgrading by installing `pip install "pyarrow<1"` resolved the issue.
52
Requirements should specify pyarrow<1 I was looking at the docs on [Perplexity](https://huggingface.co/transformers/perplexity.html) via GPT2. When you load datasets and try to load Wikitext, you get the error, ``` module 'pyarrow' has no attribute 'PyExtensionType' ``` I traced it back to datasets having installed PyArrow 1.0.1 but there's not pinning in the setup file. https://github.com/huggingface/datasets/blob/e86a2a8f869b91654e782c9133d810bb82783200/setup.py#L68 Downgrading by installing `pip install "pyarrow<1"` resolved the issue. I am sorry for hijacking this closed issue, but I believe I was able to reproduce this very issue. Strangely enough, it also turned out that running `pip install "pyarrow<1" --upgrade` did indeed fix the issue (PyArrow was installed in version `0.14.1` in my case). Please see the Colab below: https://colab.research.google.com/drive/15QQS3xWjlKW2aK0J74eEcRFuhXUddUST Thanks!
https://github.com/huggingface/datasets/issues/705
TypeError: '<' not supported between instances of 'NamedSplit' and 'NamedSplit'
Hi ! Thanks for reporting :) Indeed this is an issue on the `datasets` side. I'm creating a PR
## Environment info <!-- You can run the command `transformers-cli env` and copy-and-paste its output below. Don't forget to fill out the missing fields in that output! --> - `transformers` version: 3.3.1 (installed from master) - `datasets` version: 1.0.2 (installed as a dependency from transformers) - Platform: Linux-4.15.0-118-generic-x86_64-with-debian-stretch-sid - Python version: 3.7.9 I'm testing my own text classification dataset using [this example](https://github.com/huggingface/transformers/tree/master/examples/text-classification#run-generic-text-classification-script-in-tensorflow) from transformers. The dataset is split into train / dev / test, and in csv format, containing just a text and a label columns, using comma as sep. Here's a sample: ``` text,label "Registra-se a presenรงa do acadรชmico <name> . <REL_SEP> Ao me deparar com a descriรงรฃo de dois autores no polo ativo da aรงรฃo junto ao PJe , margem esquerda foi informado pela procuradora do reclamante que se trata de uma reclamaรงรฃo trabalhista individual . <REL_SEP> Diante disso , face a ausรชncia injustificada do autor <name> , determina-se o ARQUIVAMENTO do presente processo , com relaรงรฃo a este , nos termos do [[ art . 844 da CLT ]] . <REL_SEP> CUSTAS AUTOR - DISPENSADO <REL_SEP> Custas pelo autor no importe de R $326,82 , calculadas sobre R $16.341,03 , dispensadas na forma da lei , em virtude da concessรฃo dos benefรญcios da Justiรงa Gratuita , ora deferida . <REL_SEP> Cientes os presentes . <REL_SEP> Audiรชncia encerrada ร s 8h42min . <REL_SEP> <name> <REL_SEP> Juรญza do Trabalho <REL_SEP> Ata redigida por << <name> >> , Secretรกrio de Audiรชncia .",NO_RELATION ``` However, @Santosh-Gupta reported in #7351 that he had the exact same problem using the ChemProt dataset. His colab notebook is referenced in the following section. ## To reproduce Steps to reproduce the behavior: 1. Created a new conda environment using conda env -n transformers python=3.7 2. Cloned transformers master, `cd` into it and installed using pip install --editable . -r examples/requirements.txt 3. Installed tensorflow with `pip install tensorflow` 3. Ran `run_tf_text_classification.py` with the following parameters: ``` --train_file <DATASET_PATH>/train.csv \ --dev_file <DATASET_PATH>/dev.csv \ --test_file <DATASET_PATH>/test.csv \ --label_column_id 1 \ --model_name_or_path neuralmind/bert-base-portuguese-cased \ --output_dir <OUTPUT_PATH> \ --num_train_epochs 4 \ --per_device_train_batch_size 4 \ --per_device_eval_batch_size 4 \ --do_train \ --do_eval \ --do_predict \ --logging_steps 1000 \ --evaluate_during_training \ --save_steps 1000 \ --overwrite_output_dir \ --overwrite_cache ``` I have also copied [@Santosh-Gupta 's colab notebook](https://colab.research.google.com/drive/11APei6GjphCZbH5wD9yVlfGvpIkh8pwr?usp=sharing) as a reference. <!-- If you have code snippets, error messages, stack traces please provide them here as well. Important! Use code tags to correctly format your code. See https://help.github.com/en/github/writing-on-github/creating-and-highlighting-code-blocks#syntax-highlighting Do not use screenshots, as they are hard to read and (more importantly) don't allow others to copy-and-paste your code.--> Here is the stack trace: ``` 2020-10-02 07:33:41.622011: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcudart.so.10.1 /media/discoD/repositorios/transformers_pedro/src/transformers/training_args.py:333: FutureWarning: The `evaluate_during_training` argument is deprecated in favor of `evaluation_strategy` (which has more options) FutureWarning, 2020-10-02 07:33:43.471648: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcuda.so.1 2020-10-02 07:33:43.471791: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:982] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2020-10-02 07:33:43.472664: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1716] Found device 0 with properties: pciBusID: 0000:01:00.0 name: GeForce GTX 1070 computeCapability: 6.1 coreClock: 1.7085GHz coreCount: 15 deviceMemorySize: 7.92GiB deviceMemoryBandwidth: 238.66GiB/s 2020-10-02 07:33:43.472684: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcudart.so.10.1 2020-10-02 07:33:43.472765: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcublas.so.10 2020-10-02 07:33:43.472809: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcufft.so.10 2020-10-02 07:33:43.472848: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcurand.so.10 2020-10-02 07:33:43.474209: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcusolver.so.10 2020-10-02 07:33:43.474276: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcusparse.so.10 2020-10-02 07:33:43.561219: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcudnn.so.7 2020-10-02 07:33:43.561397: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:982] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2020-10-02 07:33:43.562345: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:982] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2020-10-02 07:33:43.563219: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1858] Adding visible gpu devices: 0 2020-10-02 07:33:43.563595: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN)to use the following CPU instructions in performance-critical operations: AVX2 FMA To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags. 2020-10-02 07:33:43.570091: I tensorflow/core/platform/profile_utils/cpu_utils.cc:104] CPU Frequency: 3591830000 Hz 2020-10-02 07:33:43.570494: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x560842432400 initialized for platform Host (this does not guarantee that XLA will be used). Devices: 2020-10-02 07:33:43.570511: I tensorflow/compiler/xla/service/service.cc:176] StreamExecutor device (0): Host, Default Version 2020-10-02 07:33:43.570702: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:982] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2020-10-02 07:33:43.571599: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1716] Found device 0 with properties: pciBusID: 0000:01:00.0 name: GeForce GTX 1070 computeCapability: 6.1 coreClock: 1.7085GHz coreCount: 15 deviceMemorySize: 7.92GiB deviceMemoryBandwidth: 238.66GiB/s 2020-10-02 07:33:43.571633: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcudart.so.10.1 2020-10-02 07:33:43.571645: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcublas.so.10 2020-10-02 07:33:43.571654: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcufft.so.10 2020-10-02 07:33:43.571664: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcurand.so.10 2020-10-02 07:33:43.571691: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcusolver.so.10 2020-10-02 07:33:43.571704: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcusparse.so.10 2020-10-02 07:33:43.571718: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcudnn.so.7 2020-10-02 07:33:43.571770: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:982] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2020-10-02 07:33:43.572641: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:982] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2020-10-02 07:33:43.573475: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1858] Adding visible gpu devices: 0 2020-10-02 07:33:47.139227: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1257] Device interconnect StreamExecutor with strength 1 edge matrix: 2020-10-02 07:33:47.139265: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1263] 0 2020-10-02 07:33:47.139272: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1276] 0: N 2020-10-02 07:33:47.140323: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:982] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2020-10-02 07:33:47.141248: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:982] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2020-10-02 07:33:47.142085: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:982] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2020-10-02 07:33:47.142854: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1402] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 5371 MB memory) -> physical GPU (device: 0, name: GeForce GTX 1070, pci bus id: 0000:01:00.0, compute capability: 6.1) 2020-10-02 07:33:47.146317: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x5608b95dc5c0 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices: 2020-10-02 07:33:47.146336: I tensorflow/compiler/xla/service/service.cc:176] StreamExecutor device (0): GeForce GTX 1070, Compute Capability 6.1 10/02/2020 07:33:47 - INFO - __main__ - n_replicas: 1, distributed training: False, 16-bits training: False 10/02/2020 07:33:47 - INFO - __main__ - Training/evaluation parameters TFTrainingArguments(output_dir='/media/discoD/models/datalawyer/pedidos/transformers_tf', overwrite_output_dir=True, do_train=True, do_eval=True, do_predict=True, evaluate_during_training=True, evaluation_strategy=<EvaluationStrategy.STEPS: 'steps'>, prediction_loss_only=False, per_device_train_batch_size=4, per_device_eval_batch_size=4, per_gpu_train_batch_size=None, per_gpu_eval_batch_size=None, gradient_accumulation_steps=1, learning_rate=5e-05, weight_decay=0.0, adam_beta1=0.9, adam_beta2=0.999, adam_epsilon=1e-08, max_grad_norm=1.0, num_train_epochs=4.0, max_steps=-1, warmup_steps=0, logging_dir='runs/Oct02_07-33-43_user-XPS-8700', logging_first_step=False, logging_steps=1000, save_steps=1000, save_total_limit=None, no_cuda=False, seed=42, fp16=False, fp16_opt_level='O1', local_rank=-1, tpu_num_cores=None, tpu_metrics_debug=False, debug=False, dataloader_drop_last=False, eval_steps=1000, dataloader_num_workers=0, past_index=-1, run_name='/media/discoD/models/datalawyer/pedidos/transformers_tf', disable_tqdm=False, remove_unused_columns=True, label_names=None, load_best_model_at_end=False, metric_for_best_model=None, greater_is_better=False, tpu_name=None, xla=False) 10/02/2020 07:33:53 - INFO - filelock - Lock 140407857405776 acquired on /home/user/.cache/huggingface/datasets/e0f1e9ed46db1e2429189f06b479cbd4075c0976104c1aacf8f77d9a53d2ad87.03756fef6da334f50a7ff73608e21b5018229944ca250416ce7352e25d84a552.py.lock 10/02/2020 07:33:53 - INFO - filelock - Lock 140407857405776 released on /home/user/.cache/huggingface/datasets/e0f1e9ed46db1e2429189f06b479cbd4075c0976104c1aacf8f77d9a53d2ad87.03756fef6da334f50a7ff73608e21b5018229944ca250416ce7352e25d84a552.py.lock Using custom data configuration default Traceback (most recent call last): File "run_tf_text_classification.py", line 283, in <module> main() File "run_tf_text_classification.py", line 222, in main max_seq_length=data_args.max_seq_length, File "run_tf_text_classification.py", line 43, in get_tfds ds = datasets.load_dataset("csv", data_files=files) File "/media/discoD/anaconda3/envs/transformers/lib/python3.7/site-packages/datasets/load.py", line 604, in load_dataset **config_kwargs, File "/media/discoD/anaconda3/envs/transformers/lib/python3.7/site-packages/datasets/builder.py", line 158, in __init__ **config_kwargs, File "/media/discoD/anaconda3/envs/transformers/lib/python3.7/site-packages/datasets/builder.py", line 269, in _create_builder_config for key in sorted(data_files.keys()): TypeError: '<' not supported between instances of 'NamedSplit' and 'NamedSplit' ``` ## Expected behavior Should be able to run the text-classification example as described in [https://github.com/huggingface/transformers/tree/master/examples/text-classification#run-generic-text-classification-script-in-tensorflow](https://github.com/huggingface/transformers/tree/master/examples/text-classification#run-generic-text-classification-script-in-tensorflow) Originally opened this issue at transformers' repository: [https://github.com/huggingface/transformers/issues/7535](https://github.com/huggingface/transformers/issues/7535). @jplu instructed me to open here, since according to [this](https://github.com/huggingface/transformers/issues/7535#issuecomment-702778885) evidence, the problem is from datasets. Thanks!
19
TypeError: '<' not supported between instances of 'NamedSplit' and 'NamedSplit' ## Environment info <!-- You can run the command `transformers-cli env` and copy-and-paste its output below. Don't forget to fill out the missing fields in that output! --> - `transformers` version: 3.3.1 (installed from master) - `datasets` version: 1.0.2 (installed as a dependency from transformers) - Platform: Linux-4.15.0-118-generic-x86_64-with-debian-stretch-sid - Python version: 3.7.9 I'm testing my own text classification dataset using [this example](https://github.com/huggingface/transformers/tree/master/examples/text-classification#run-generic-text-classification-script-in-tensorflow) from transformers. The dataset is split into train / dev / test, and in csv format, containing just a text and a label columns, using comma as sep. Here's a sample: ``` text,label "Registra-se a presenรงa do acadรชmico <name> . <REL_SEP> Ao me deparar com a descriรงรฃo de dois autores no polo ativo da aรงรฃo junto ao PJe , margem esquerda foi informado pela procuradora do reclamante que se trata de uma reclamaรงรฃo trabalhista individual . <REL_SEP> Diante disso , face a ausรชncia injustificada do autor <name> , determina-se o ARQUIVAMENTO do presente processo , com relaรงรฃo a este , nos termos do [[ art . 844 da CLT ]] . <REL_SEP> CUSTAS AUTOR - DISPENSADO <REL_SEP> Custas pelo autor no importe de R $326,82 , calculadas sobre R $16.341,03 , dispensadas na forma da lei , em virtude da concessรฃo dos benefรญcios da Justiรงa Gratuita , ora deferida . <REL_SEP> Cientes os presentes . <REL_SEP> Audiรชncia encerrada ร s 8h42min . <REL_SEP> <name> <REL_SEP> Juรญza do Trabalho <REL_SEP> Ata redigida por << <name> >> , Secretรกrio de Audiรชncia .",NO_RELATION ``` However, @Santosh-Gupta reported in #7351 that he had the exact same problem using the ChemProt dataset. His colab notebook is referenced in the following section. ## To reproduce Steps to reproduce the behavior: 1. Created a new conda environment using conda env -n transformers python=3.7 2. Cloned transformers master, `cd` into it and installed using pip install --editable . -r examples/requirements.txt 3. Installed tensorflow with `pip install tensorflow` 3. Ran `run_tf_text_classification.py` with the following parameters: ``` --train_file <DATASET_PATH>/train.csv \ --dev_file <DATASET_PATH>/dev.csv \ --test_file <DATASET_PATH>/test.csv \ --label_column_id 1 \ --model_name_or_path neuralmind/bert-base-portuguese-cased \ --output_dir <OUTPUT_PATH> \ --num_train_epochs 4 \ --per_device_train_batch_size 4 \ --per_device_eval_batch_size 4 \ --do_train \ --do_eval \ --do_predict \ --logging_steps 1000 \ --evaluate_during_training \ --save_steps 1000 \ --overwrite_output_dir \ --overwrite_cache ``` I have also copied [@Santosh-Gupta 's colab notebook](https://colab.research.google.com/drive/11APei6GjphCZbH5wD9yVlfGvpIkh8pwr?usp=sharing) as a reference. <!-- If you have code snippets, error messages, stack traces please provide them here as well. Important! Use code tags to correctly format your code. See https://help.github.com/en/github/writing-on-github/creating-and-highlighting-code-blocks#syntax-highlighting Do not use screenshots, as they are hard to read and (more importantly) don't allow others to copy-and-paste your code.--> Here is the stack trace: ``` 2020-10-02 07:33:41.622011: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcudart.so.10.1 /media/discoD/repositorios/transformers_pedro/src/transformers/training_args.py:333: FutureWarning: The `evaluate_during_training` argument is deprecated in favor of `evaluation_strategy` (which has more options) FutureWarning, 2020-10-02 07:33:43.471648: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcuda.so.1 2020-10-02 07:33:43.471791: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:982] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2020-10-02 07:33:43.472664: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1716] Found device 0 with properties: pciBusID: 0000:01:00.0 name: GeForce GTX 1070 computeCapability: 6.1 coreClock: 1.7085GHz coreCount: 15 deviceMemorySize: 7.92GiB deviceMemoryBandwidth: 238.66GiB/s 2020-10-02 07:33:43.472684: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcudart.so.10.1 2020-10-02 07:33:43.472765: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcublas.so.10 2020-10-02 07:33:43.472809: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcufft.so.10 2020-10-02 07:33:43.472848: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcurand.so.10 2020-10-02 07:33:43.474209: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcusolver.so.10 2020-10-02 07:33:43.474276: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcusparse.so.10 2020-10-02 07:33:43.561219: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcudnn.so.7 2020-10-02 07:33:43.561397: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:982] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2020-10-02 07:33:43.562345: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:982] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2020-10-02 07:33:43.563219: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1858] Adding visible gpu devices: 0 2020-10-02 07:33:43.563595: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN)to use the following CPU instructions in performance-critical operations: AVX2 FMA To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags. 2020-10-02 07:33:43.570091: I tensorflow/core/platform/profile_utils/cpu_utils.cc:104] CPU Frequency: 3591830000 Hz 2020-10-02 07:33:43.570494: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x560842432400 initialized for platform Host (this does not guarantee that XLA will be used). Devices: 2020-10-02 07:33:43.570511: I tensorflow/compiler/xla/service/service.cc:176] StreamExecutor device (0): Host, Default Version 2020-10-02 07:33:43.570702: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:982] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2020-10-02 07:33:43.571599: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1716] Found device 0 with properties: pciBusID: 0000:01:00.0 name: GeForce GTX 1070 computeCapability: 6.1 coreClock: 1.7085GHz coreCount: 15 deviceMemorySize: 7.92GiB deviceMemoryBandwidth: 238.66GiB/s 2020-10-02 07:33:43.571633: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcudart.so.10.1 2020-10-02 07:33:43.571645: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcublas.so.10 2020-10-02 07:33:43.571654: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcufft.so.10 2020-10-02 07:33:43.571664: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcurand.so.10 2020-10-02 07:33:43.571691: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcusolver.so.10 2020-10-02 07:33:43.571704: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcusparse.so.10 2020-10-02 07:33:43.571718: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcudnn.so.7 2020-10-02 07:33:43.571770: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:982] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2020-10-02 07:33:43.572641: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:982] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2020-10-02 07:33:43.573475: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1858] Adding visible gpu devices: 0 2020-10-02 07:33:47.139227: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1257] Device interconnect StreamExecutor with strength 1 edge matrix: 2020-10-02 07:33:47.139265: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1263] 0 2020-10-02 07:33:47.139272: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1276] 0: N 2020-10-02 07:33:47.140323: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:982] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2020-10-02 07:33:47.141248: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:982] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2020-10-02 07:33:47.142085: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:982] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2020-10-02 07:33:47.142854: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1402] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 5371 MB memory) -> physical GPU (device: 0, name: GeForce GTX 1070, pci bus id: 0000:01:00.0, compute capability: 6.1) 2020-10-02 07:33:47.146317: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x5608b95dc5c0 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices: 2020-10-02 07:33:47.146336: I tensorflow/compiler/xla/service/service.cc:176] StreamExecutor device (0): GeForce GTX 1070, Compute Capability 6.1 10/02/2020 07:33:47 - INFO - __main__ - n_replicas: 1, distributed training: False, 16-bits training: False 10/02/2020 07:33:47 - INFO - __main__ - Training/evaluation parameters TFTrainingArguments(output_dir='/media/discoD/models/datalawyer/pedidos/transformers_tf', overwrite_output_dir=True, do_train=True, do_eval=True, do_predict=True, evaluate_during_training=True, evaluation_strategy=<EvaluationStrategy.STEPS: 'steps'>, prediction_loss_only=False, per_device_train_batch_size=4, per_device_eval_batch_size=4, per_gpu_train_batch_size=None, per_gpu_eval_batch_size=None, gradient_accumulation_steps=1, learning_rate=5e-05, weight_decay=0.0, adam_beta1=0.9, adam_beta2=0.999, adam_epsilon=1e-08, max_grad_norm=1.0, num_train_epochs=4.0, max_steps=-1, warmup_steps=0, logging_dir='runs/Oct02_07-33-43_user-XPS-8700', logging_first_step=False, logging_steps=1000, save_steps=1000, save_total_limit=None, no_cuda=False, seed=42, fp16=False, fp16_opt_level='O1', local_rank=-1, tpu_num_cores=None, tpu_metrics_debug=False, debug=False, dataloader_drop_last=False, eval_steps=1000, dataloader_num_workers=0, past_index=-1, run_name='/media/discoD/models/datalawyer/pedidos/transformers_tf', disable_tqdm=False, remove_unused_columns=True, label_names=None, load_best_model_at_end=False, metric_for_best_model=None, greater_is_better=False, tpu_name=None, xla=False) 10/02/2020 07:33:53 - INFO - filelock - Lock 140407857405776 acquired on /home/user/.cache/huggingface/datasets/e0f1e9ed46db1e2429189f06b479cbd4075c0976104c1aacf8f77d9a53d2ad87.03756fef6da334f50a7ff73608e21b5018229944ca250416ce7352e25d84a552.py.lock 10/02/2020 07:33:53 - INFO - filelock - Lock 140407857405776 released on /home/user/.cache/huggingface/datasets/e0f1e9ed46db1e2429189f06b479cbd4075c0976104c1aacf8f77d9a53d2ad87.03756fef6da334f50a7ff73608e21b5018229944ca250416ce7352e25d84a552.py.lock Using custom data configuration default Traceback (most recent call last): File "run_tf_text_classification.py", line 283, in <module> main() File "run_tf_text_classification.py", line 222, in main max_seq_length=data_args.max_seq_length, File "run_tf_text_classification.py", line 43, in get_tfds ds = datasets.load_dataset("csv", data_files=files) File "/media/discoD/anaconda3/envs/transformers/lib/python3.7/site-packages/datasets/load.py", line 604, in load_dataset **config_kwargs, File "/media/discoD/anaconda3/envs/transformers/lib/python3.7/site-packages/datasets/builder.py", line 158, in __init__ **config_kwargs, File "/media/discoD/anaconda3/envs/transformers/lib/python3.7/site-packages/datasets/builder.py", line 269, in _create_builder_config for key in sorted(data_files.keys()): TypeError: '<' not supported between instances of 'NamedSplit' and 'NamedSplit' ``` ## Expected behavior Should be able to run the text-classification example as described in [https://github.com/huggingface/transformers/tree/master/examples/text-classification#run-generic-text-classification-script-in-tensorflow](https://github.com/huggingface/transformers/tree/master/examples/text-classification#run-generic-text-classification-script-in-tensorflow) Originally opened this issue at transformers' repository: [https://github.com/huggingface/transformers/issues/7535](https://github.com/huggingface/transformers/issues/7535). @jplu instructed me to open here, since according to [this](https://github.com/huggingface/transformers/issues/7535#issuecomment-702778885) evidence, the problem is from datasets. Thanks! Hi ! Thanks for reporting :) Indeed this is an issue on the `datasets` side. I'm creating a PR
https://github.com/huggingface/datasets/issues/699
XNLI dataset is not loading
also i tried below code to solve checksum error `datasets-cli test ./datasets/xnli --save_infos --all_configs` and it shows ``` 2020-10-02 07:06:16.588760: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1 Traceback (most recent call last): File "/opt/conda/lib/python3.7/site-packages/datasets/load.py", line 268, in prepare_module local_path = cached_path(file_path, download_config=download_config) File "/opt/conda/lib/python3.7/site-packages/datasets/utils/file_utils.py", line 308, in cached_path use_etag=download_config.use_etag, File "/opt/conda/lib/python3.7/site-packages/datasets/utils/file_utils.py", line 474, in get_from_cache raise FileNotFoundError("Couldn't find file at {}".format(url)) FileNotFoundError: Couldn't find file at https://raw.githubusercontent.com/huggingface/datasets/1.0.2/datasets/./datasets/xnli/xnli.py During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/conda/lib/python3.7/site-packages/datasets/load.py", line 279, in prepare_module local_path = cached_path(file_path, download_config=download_config) File "/opt/conda/lib/python3.7/site-packages/datasets/utils/file_utils.py", line 308, in cached_path use_etag=download_config.use_etag, File "/opt/conda/lib/python3.7/site-packages/datasets/utils/file_utils.py", line 474, in get_from_cache raise FileNotFoundError("Couldn't find file at {}".format(url)) FileNotFoundError: Couldn't find file at https://s3.amazonaws.com/datasets.huggingface.co/datasets/datasets/./datasets/xnli/xnli.py During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/conda/bin/datasets-cli", line 36, in <module> service.run() File "/opt/conda/lib/python3.7/site-packages/datasets/commands/test.py", line 76, in run module_path, hash = prepare_module(path) File "/opt/conda/lib/python3.7/site-packages/datasets/load.py", line 283, in prepare_module combined_path, github_file_path, file_path FileNotFoundError: Couldn't find file locally at ./datasets/xnli/xnli.py, or remotely at https://raw.githubusercontent.com/huggingface/datasets/1.0.2/datasets/./datasets/xnli/xnli.py or https://s3.amazonaws.com/datasets.huggingface.co/datasets/datasets/./datasets/xnli/xnli.py ```
`dataset = datasets.load_dataset(path='xnli')` showing below error ``` /opt/conda/lib/python3.7/site-packages/nlp/utils/info_utils.py in verify_checksums(expected_checksums, recorded_checksums, verification_name) 36 if len(bad_urls) > 0: 37 error_msg = "Checksums didn't match" + for_verification_name + ":\n" ---> 38 raise NonMatchingChecksumError(error_msg + str(bad_urls)) 39 logger.info("All the checksums matched successfully" + for_verification_name) 40 NonMatchingChecksumError: Checksums didn't match for dataset source files: ['https://www.nyu.edu/projects/bowman/xnli/XNLI-1.0.zip'] ``` I think URL is now changed to "https://cims.nyu.edu/~sbowman/xnli/XNLI-MT-1.0.zip"
170
XNLI dataset is not loading `dataset = datasets.load_dataset(path='xnli')` showing below error ``` /opt/conda/lib/python3.7/site-packages/nlp/utils/info_utils.py in verify_checksums(expected_checksums, recorded_checksums, verification_name) 36 if len(bad_urls) > 0: 37 error_msg = "Checksums didn't match" + for_verification_name + ":\n" ---> 38 raise NonMatchingChecksumError(error_msg + str(bad_urls)) 39 logger.info("All the checksums matched successfully" + for_verification_name) 40 NonMatchingChecksumError: Checksums didn't match for dataset source files: ['https://www.nyu.edu/projects/bowman/xnli/XNLI-1.0.zip'] ``` I think URL is now changed to "https://cims.nyu.edu/~sbowman/xnli/XNLI-MT-1.0.zip" also i tried below code to solve checksum error `datasets-cli test ./datasets/xnli --save_infos --all_configs` and it shows ``` 2020-10-02 07:06:16.588760: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1 Traceback (most recent call last): File "/opt/conda/lib/python3.7/site-packages/datasets/load.py", line 268, in prepare_module local_path = cached_path(file_path, download_config=download_config) File "/opt/conda/lib/python3.7/site-packages/datasets/utils/file_utils.py", line 308, in cached_path use_etag=download_config.use_etag, File "/opt/conda/lib/python3.7/site-packages/datasets/utils/file_utils.py", line 474, in get_from_cache raise FileNotFoundError("Couldn't find file at {}".format(url)) FileNotFoundError: Couldn't find file at https://raw.githubusercontent.com/huggingface/datasets/1.0.2/datasets/./datasets/xnli/xnli.py During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/conda/lib/python3.7/site-packages/datasets/load.py", line 279, in prepare_module local_path = cached_path(file_path, download_config=download_config) File "/opt/conda/lib/python3.7/site-packages/datasets/utils/file_utils.py", line 308, in cached_path use_etag=download_config.use_etag, File "/opt/conda/lib/python3.7/site-packages/datasets/utils/file_utils.py", line 474, in get_from_cache raise FileNotFoundError("Couldn't find file at {}".format(url)) FileNotFoundError: Couldn't find file at https://s3.amazonaws.com/datasets.huggingface.co/datasets/datasets/./datasets/xnli/xnli.py During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/conda/bin/datasets-cli", line 36, in <module> service.run() File "/opt/conda/lib/python3.7/site-packages/datasets/commands/test.py", line 76, in run module_path, hash = prepare_module(path) File "/opt/conda/lib/python3.7/site-packages/datasets/load.py", line 283, in prepare_module combined_path, github_file_path, file_path FileNotFoundError: Couldn't find file locally at ./datasets/xnli/xnli.py, or remotely at https://raw.githubusercontent.com/huggingface/datasets/1.0.2/datasets/./datasets/xnli/xnli.py or https://s3.amazonaws.com/datasets.huggingface.co/datasets/datasets/./datasets/xnli/xnli.py ```
https://github.com/huggingface/datasets/issues/699
XNLI dataset is not loading
Hi ! Yes the download url changed. It's updated on the master branch. I'm doing a release today to fix that :)
`dataset = datasets.load_dataset(path='xnli')` showing below error ``` /opt/conda/lib/python3.7/site-packages/nlp/utils/info_utils.py in verify_checksums(expected_checksums, recorded_checksums, verification_name) 36 if len(bad_urls) > 0: 37 error_msg = "Checksums didn't match" + for_verification_name + ":\n" ---> 38 raise NonMatchingChecksumError(error_msg + str(bad_urls)) 39 logger.info("All the checksums matched successfully" + for_verification_name) 40 NonMatchingChecksumError: Checksums didn't match for dataset source files: ['https://www.nyu.edu/projects/bowman/xnli/XNLI-1.0.zip'] ``` I think URL is now changed to "https://cims.nyu.edu/~sbowman/xnli/XNLI-MT-1.0.zip"
22
XNLI dataset is not loading `dataset = datasets.load_dataset(path='xnli')` showing below error ``` /opt/conda/lib/python3.7/site-packages/nlp/utils/info_utils.py in verify_checksums(expected_checksums, recorded_checksums, verification_name) 36 if len(bad_urls) > 0: 37 error_msg = "Checksums didn't match" + for_verification_name + ":\n" ---> 38 raise NonMatchingChecksumError(error_msg + str(bad_urls)) 39 logger.info("All the checksums matched successfully" + for_verification_name) 40 NonMatchingChecksumError: Checksums didn't match for dataset source files: ['https://www.nyu.edu/projects/bowman/xnli/XNLI-1.0.zip'] ``` I think URL is now changed to "https://cims.nyu.edu/~sbowman/xnli/XNLI-MT-1.0.zip" Hi ! Yes the download url changed. It's updated on the master branch. I'm doing a release today to fix that :)
https://github.com/huggingface/datasets/issues/690
XNLI dataset: NonMatchingChecksumError
Thanks for reporting. The data file must have been updated by the host. I'll update the checksum with the new one.
Hi, I tried to download "xnli" dataset in colab using `xnli = load_dataset(path='xnli')` but got 'NonMatchingChecksumError' error `NonMatchingChecksumError Traceback (most recent call last) <ipython-input-27-a87bedc82eeb> in <module>() ----> 1 xnli = load_dataset(path='xnli') 3 frames /usr/local/lib/python3.6/dist-packages/datasets/utils/info_utils.py in verify_checksums(expected_checksums, recorded_checksums, verification_name) 37 if len(bad_urls) > 0: 38 error_msg = "Checksums didn't match" + for_verification_name + ":\n" ---> 39 raise NonMatchingChecksumError(error_msg + str(bad_urls)) 40 logger.info("All the checksums matched successfully" + for_verification_name) 41 NonMatchingChecksumError: Checksums didn't match for dataset source files: ['https://www.nyu.edu/projects/bowman/xnli/XNLI-1.0.zip']` The same code worked well several days ago in colab but stopped working now. Thanks!
21
XNLI dataset: NonMatchingChecksumError Hi, I tried to download "xnli" dataset in colab using `xnli = load_dataset(path='xnli')` but got 'NonMatchingChecksumError' error `NonMatchingChecksumError Traceback (most recent call last) <ipython-input-27-a87bedc82eeb> in <module>() ----> 1 xnli = load_dataset(path='xnli') 3 frames /usr/local/lib/python3.6/dist-packages/datasets/utils/info_utils.py in verify_checksums(expected_checksums, recorded_checksums, verification_name) 37 if len(bad_urls) > 0: 38 error_msg = "Checksums didn't match" + for_verification_name + ":\n" ---> 39 raise NonMatchingChecksumError(error_msg + str(bad_urls)) 40 logger.info("All the checksums matched successfully" + for_verification_name) 41 NonMatchingChecksumError: Checksums didn't match for dataset source files: ['https://www.nyu.edu/projects/bowman/xnli/XNLI-1.0.zip']` The same code worked well several days ago in colab but stopped working now. Thanks! Thanks for reporting. The data file must have been updated by the host. I'll update the checksum with the new one.
https://github.com/huggingface/datasets/issues/690
XNLI dataset: NonMatchingChecksumError
I'll do a release in the next few days to make the fix available for everyone. In the meantime you can load `xnli` with ``` xnli = load_dataset('xnli', script_version="master") ``` This will use the latest version of the xnli script (available on master branch), instead of the old one.
Hi, I tried to download "xnli" dataset in colab using `xnli = load_dataset(path='xnli')` but got 'NonMatchingChecksumError' error `NonMatchingChecksumError Traceback (most recent call last) <ipython-input-27-a87bedc82eeb> in <module>() ----> 1 xnli = load_dataset(path='xnli') 3 frames /usr/local/lib/python3.6/dist-packages/datasets/utils/info_utils.py in verify_checksums(expected_checksums, recorded_checksums, verification_name) 37 if len(bad_urls) > 0: 38 error_msg = "Checksums didn't match" + for_verification_name + ":\n" ---> 39 raise NonMatchingChecksumError(error_msg + str(bad_urls)) 40 logger.info("All the checksums matched successfully" + for_verification_name) 41 NonMatchingChecksumError: Checksums didn't match for dataset source files: ['https://www.nyu.edu/projects/bowman/xnli/XNLI-1.0.zip']` The same code worked well several days ago in colab but stopped working now. Thanks!
49
XNLI dataset: NonMatchingChecksumError Hi, I tried to download "xnli" dataset in colab using `xnli = load_dataset(path='xnli')` but got 'NonMatchingChecksumError' error `NonMatchingChecksumError Traceback (most recent call last) <ipython-input-27-a87bedc82eeb> in <module>() ----> 1 xnli = load_dataset(path='xnli') 3 frames /usr/local/lib/python3.6/dist-packages/datasets/utils/info_utils.py in verify_checksums(expected_checksums, recorded_checksums, verification_name) 37 if len(bad_urls) > 0: 38 error_msg = "Checksums didn't match" + for_verification_name + ":\n" ---> 39 raise NonMatchingChecksumError(error_msg + str(bad_urls)) 40 logger.info("All the checksums matched successfully" + for_verification_name) 41 NonMatchingChecksumError: Checksums didn't match for dataset source files: ['https://www.nyu.edu/projects/bowman/xnli/XNLI-1.0.zip']` The same code worked well several days ago in colab but stopped working now. Thanks! I'll do a release in the next few days to make the fix available for everyone. In the meantime you can load `xnli` with ``` xnli = load_dataset('xnli', script_version="master") ``` This will use the latest version of the xnli script (available on master branch), instead of the old one.
https://github.com/huggingface/datasets/issues/687
`ArrowInvalid` occurs while running `Dataset.map()` function
Hi ! This is because `encode` expects one single text as input (str), or one tokenized text (List[str]). I believe that you actually wanted to use `encode_batch` which expects a batch of texts. However this method is only available for our "fast" tokenizers (ex: BertTokenizerFast). BertJapanese is not one of them unfortunately and I don't think it will be added for now (see https://github.com/huggingface/transformers/pull/7141)... cc @thomwolf for confirmation. Therefore what I'd suggest for now is disable batching and process one text at a time using `encode`. Note that you can make it faster by using multiprocessing: ```python num_proc = None # Specify here the number of processes if you want to use multiprocessing. ex: num_proc = 4 encoded = train_ds.map( lambda example: {'tokens': t.encode(example['title'], max_length=1000)}, num_proc=num_proc ) ```
It seems to fail to process the final batch. This [colab](https://colab.research.google.com/drive/1_byLZRHwGP13PHMkJWo62Wp50S_Z2HMD?usp=sharing) can reproduce the error. Code: ```python # train_ds = Dataset(features: { # 'title': Value(dtype='string', id=None), # 'score': Value(dtype='float64', id=None) # }, num_rows: 99999) # suggested in #665 class PicklableTokenizer(BertJapaneseTokenizer): def __getstate__(self): state = dict(self.__dict__) state['do_lower_case'] = self.word_tokenizer.do_lower_case state['never_split'] = self.word_tokenizer.never_split del state['word_tokenizer'] return state def __setstate(self): do_lower_case = state.pop('do_lower_case') never_split = state.pop('never_split') self.__dict__ = state self.word_tokenizer = MecabTokenizer( do_lower_case=do_lower_case, never_split=never_split ) t = PicklableTokenizer.from_pretrained('bert-base-japanese-whole-word-masking') encoded = train_ds.map( lambda examples: {'tokens': t.encode(examples['title'], max_length=1000)}, batched=True, batch_size=1000 ) ``` Error Message: ``` 99% 99/100 [00:22<00:00, 39.07ba/s] --------------------------------------------------------------------------- ArrowInvalid Traceback (most recent call last) <timed exec> in <module> /usr/local/lib/python3.6/site-packages/datasets/arrow_dataset.py in map(self, function, with_indices, input_columns, batched, batch_size, drop_last_batch, remove_columns, keep_in_memory, load_from_cache_file, cache_file_name, writer_batch_size, features, disable_nullable, fn_kwargs, num_proc, suffix_template, new_fingerprint) 1242 fn_kwargs=fn_kwargs, 1243 new_fingerprint=new_fingerprint, -> 1244 update_data=update_data, 1245 ) 1246 else: /usr/local/lib/python3.6/site-packages/datasets/arrow_dataset.py in wrapper(*args, **kwargs) 151 "output_all_columns": self._output_all_columns, 152 } --> 153 out: Union["Dataset", "DatasetDict"] = func(self, *args, **kwargs) 154 if new_format["columns"] is not None: 155 new_format["columns"] = list(set(new_format["columns"]) & set(out.column_names)) /usr/local/lib/python3.6/site-packages/datasets/fingerprint.py in wrapper(*args, **kwargs) 161 # Call actual function 162 --> 163 out = func(self, *args, **kwargs) 164 165 # Update fingerprint of in-place transforms + update in-place history of transforms /usr/local/lib/python3.6/site-packages/datasets/arrow_dataset.py in _map_single(self, function, with_indices, input_columns, batched, batch_size, drop_last_batch, remove_columns, keep_in_memory, load_from_cache_file, cache_file_name, writer_batch_size, features, disable_nullable, fn_kwargs, new_fingerprint, rank, offset, update_data) 1496 if update_data: 1497 batch = cast_to_python_objects(batch) -> 1498 writer.write_batch(batch) 1499 if update_data: 1500 writer.finalize() # close_stream=bool(buf_writer is None)) # We only close if we are writing in a file /usr/local/lib/python3.6/site-packages/datasets/arrow_writer.py in write_batch(self, batch_examples, writer_batch_size) 271 typed_sequence = TypedSequence(batch_examples[col], type=col_type, try_type=col_try_type) 272 typed_sequence_examples[col] = typed_sequence --> 273 pa_table = pa.Table.from_pydict(typed_sequence_examples) 274 self.write_table(pa_table) 275 /usr/local/lib/python3.6/site-packages/pyarrow/table.pxi in pyarrow.lib.Table.from_pydict() /usr/local/lib/python3.6/site-packages/pyarrow/table.pxi in pyarrow.lib.Table.from_arrays() /usr/local/lib/python3.6/site-packages/pyarrow/table.pxi in pyarrow.lib.Table.validate() /usr/local/lib/python3.6/site-packages/pyarrow/error.pxi in pyarrow.lib.check_status() ArrowInvalid: Column 4 named tokens expected length 999 but got length 1000 ```
128
`ArrowInvalid` occurs while running `Dataset.map()` function It seems to fail to process the final batch. This [colab](https://colab.research.google.com/drive/1_byLZRHwGP13PHMkJWo62Wp50S_Z2HMD?usp=sharing) can reproduce the error. Code: ```python # train_ds = Dataset(features: { # 'title': Value(dtype='string', id=None), # 'score': Value(dtype='float64', id=None) # }, num_rows: 99999) # suggested in #665 class PicklableTokenizer(BertJapaneseTokenizer): def __getstate__(self): state = dict(self.__dict__) state['do_lower_case'] = self.word_tokenizer.do_lower_case state['never_split'] = self.word_tokenizer.never_split del state['word_tokenizer'] return state def __setstate(self): do_lower_case = state.pop('do_lower_case') never_split = state.pop('never_split') self.__dict__ = state self.word_tokenizer = MecabTokenizer( do_lower_case=do_lower_case, never_split=never_split ) t = PicklableTokenizer.from_pretrained('bert-base-japanese-whole-word-masking') encoded = train_ds.map( lambda examples: {'tokens': t.encode(examples['title'], max_length=1000)}, batched=True, batch_size=1000 ) ``` Error Message: ``` 99% 99/100 [00:22<00:00, 39.07ba/s] --------------------------------------------------------------------------- ArrowInvalid Traceback (most recent call last) <timed exec> in <module> /usr/local/lib/python3.6/site-packages/datasets/arrow_dataset.py in map(self, function, with_indices, input_columns, batched, batch_size, drop_last_batch, remove_columns, keep_in_memory, load_from_cache_file, cache_file_name, writer_batch_size, features, disable_nullable, fn_kwargs, num_proc, suffix_template, new_fingerprint) 1242 fn_kwargs=fn_kwargs, 1243 new_fingerprint=new_fingerprint, -> 1244 update_data=update_data, 1245 ) 1246 else: /usr/local/lib/python3.6/site-packages/datasets/arrow_dataset.py in wrapper(*args, **kwargs) 151 "output_all_columns": self._output_all_columns, 152 } --> 153 out: Union["Dataset", "DatasetDict"] = func(self, *args, **kwargs) 154 if new_format["columns"] is not None: 155 new_format["columns"] = list(set(new_format["columns"]) & set(out.column_names)) /usr/local/lib/python3.6/site-packages/datasets/fingerprint.py in wrapper(*args, **kwargs) 161 # Call actual function 162 --> 163 out = func(self, *args, **kwargs) 164 165 # Update fingerprint of in-place transforms + update in-place history of transforms /usr/local/lib/python3.6/site-packages/datasets/arrow_dataset.py in _map_single(self, function, with_indices, input_columns, batched, batch_size, drop_last_batch, remove_columns, keep_in_memory, load_from_cache_file, cache_file_name, writer_batch_size, features, disable_nullable, fn_kwargs, new_fingerprint, rank, offset, update_data) 1496 if update_data: 1497 batch = cast_to_python_objects(batch) -> 1498 writer.write_batch(batch) 1499 if update_data: 1500 writer.finalize() # close_stream=bool(buf_writer is None)) # We only close if we are writing in a file /usr/local/lib/python3.6/site-packages/datasets/arrow_writer.py in write_batch(self, batch_examples, writer_batch_size) 271 typed_sequence = TypedSequence(batch_examples[col], type=col_type, try_type=col_try_type) 272 typed_sequence_examples[col] = typed_sequence --> 273 pa_table = pa.Table.from_pydict(typed_sequence_examples) 274 self.write_table(pa_table) 275 /usr/local/lib/python3.6/site-packages/pyarrow/table.pxi in pyarrow.lib.Table.from_pydict() /usr/local/lib/python3.6/site-packages/pyarrow/table.pxi in pyarrow.lib.Table.from_arrays() /usr/local/lib/python3.6/site-packages/pyarrow/table.pxi in pyarrow.lib.Table.validate() /usr/local/lib/python3.6/site-packages/pyarrow/error.pxi in pyarrow.lib.check_status() ArrowInvalid: Column 4 named tokens expected length 999 but got length 1000 ``` Hi ! This is because `encode` expects one single text as input (str), or one tokenized text (List[str]). I believe that you actually wanted to use `encode_batch` which expects a batch of texts. However this method is only available for our "fast" tokenizers (ex: BertTokenizerFast). BertJapanese is not one of them unfortunately and I don't think it will be added for now (see https://github.com/huggingface/transformers/pull/7141)... cc @thomwolf for confirmation. Therefore what I'd suggest for now is disable batching and process one text at a time using `encode`. Note that you can make it faster by using multiprocessing: ```python num_proc = None # Specify here the number of processes if you want to use multiprocessing. ex: num_proc = 4 encoded = train_ds.map( lambda example: {'tokens': t.encode(example['title'], max_length=1000)}, num_proc=num_proc ) ```
https://github.com/huggingface/datasets/issues/687
`ArrowInvalid` occurs while running `Dataset.map()` function
Thank you very much for the kind and precise suggestion! I'm looking forward to seeing BertJapaneseTokenizer built into the "fast" tokenizers. I tried `map` with multiprocessing as follows, and it worked! ```python # There was a Pickle problem if I use `lambda` for multiprocessing def encode(examples): return {'tokens': t.encode(examples['title'], max_length=1000)} num_proc = 8 encoded = train_ds.map(encode, num_proc=num_proc) ``` Thank you again!
It seems to fail to process the final batch. This [colab](https://colab.research.google.com/drive/1_byLZRHwGP13PHMkJWo62Wp50S_Z2HMD?usp=sharing) can reproduce the error. Code: ```python # train_ds = Dataset(features: { # 'title': Value(dtype='string', id=None), # 'score': Value(dtype='float64', id=None) # }, num_rows: 99999) # suggested in #665 class PicklableTokenizer(BertJapaneseTokenizer): def __getstate__(self): state = dict(self.__dict__) state['do_lower_case'] = self.word_tokenizer.do_lower_case state['never_split'] = self.word_tokenizer.never_split del state['word_tokenizer'] return state def __setstate(self): do_lower_case = state.pop('do_lower_case') never_split = state.pop('never_split') self.__dict__ = state self.word_tokenizer = MecabTokenizer( do_lower_case=do_lower_case, never_split=never_split ) t = PicklableTokenizer.from_pretrained('bert-base-japanese-whole-word-masking') encoded = train_ds.map( lambda examples: {'tokens': t.encode(examples['title'], max_length=1000)}, batched=True, batch_size=1000 ) ``` Error Message: ``` 99% 99/100 [00:22<00:00, 39.07ba/s] --------------------------------------------------------------------------- ArrowInvalid Traceback (most recent call last) <timed exec> in <module> /usr/local/lib/python3.6/site-packages/datasets/arrow_dataset.py in map(self, function, with_indices, input_columns, batched, batch_size, drop_last_batch, remove_columns, keep_in_memory, load_from_cache_file, cache_file_name, writer_batch_size, features, disable_nullable, fn_kwargs, num_proc, suffix_template, new_fingerprint) 1242 fn_kwargs=fn_kwargs, 1243 new_fingerprint=new_fingerprint, -> 1244 update_data=update_data, 1245 ) 1246 else: /usr/local/lib/python3.6/site-packages/datasets/arrow_dataset.py in wrapper(*args, **kwargs) 151 "output_all_columns": self._output_all_columns, 152 } --> 153 out: Union["Dataset", "DatasetDict"] = func(self, *args, **kwargs) 154 if new_format["columns"] is not None: 155 new_format["columns"] = list(set(new_format["columns"]) & set(out.column_names)) /usr/local/lib/python3.6/site-packages/datasets/fingerprint.py in wrapper(*args, **kwargs) 161 # Call actual function 162 --> 163 out = func(self, *args, **kwargs) 164 165 # Update fingerprint of in-place transforms + update in-place history of transforms /usr/local/lib/python3.6/site-packages/datasets/arrow_dataset.py in _map_single(self, function, with_indices, input_columns, batched, batch_size, drop_last_batch, remove_columns, keep_in_memory, load_from_cache_file, cache_file_name, writer_batch_size, features, disable_nullable, fn_kwargs, new_fingerprint, rank, offset, update_data) 1496 if update_data: 1497 batch = cast_to_python_objects(batch) -> 1498 writer.write_batch(batch) 1499 if update_data: 1500 writer.finalize() # close_stream=bool(buf_writer is None)) # We only close if we are writing in a file /usr/local/lib/python3.6/site-packages/datasets/arrow_writer.py in write_batch(self, batch_examples, writer_batch_size) 271 typed_sequence = TypedSequence(batch_examples[col], type=col_type, try_type=col_try_type) 272 typed_sequence_examples[col] = typed_sequence --> 273 pa_table = pa.Table.from_pydict(typed_sequence_examples) 274 self.write_table(pa_table) 275 /usr/local/lib/python3.6/site-packages/pyarrow/table.pxi in pyarrow.lib.Table.from_pydict() /usr/local/lib/python3.6/site-packages/pyarrow/table.pxi in pyarrow.lib.Table.from_arrays() /usr/local/lib/python3.6/site-packages/pyarrow/table.pxi in pyarrow.lib.Table.validate() /usr/local/lib/python3.6/site-packages/pyarrow/error.pxi in pyarrow.lib.check_status() ArrowInvalid: Column 4 named tokens expected length 999 but got length 1000 ```
61
`ArrowInvalid` occurs while running `Dataset.map()` function It seems to fail to process the final batch. This [colab](https://colab.research.google.com/drive/1_byLZRHwGP13PHMkJWo62Wp50S_Z2HMD?usp=sharing) can reproduce the error. Code: ```python # train_ds = Dataset(features: { # 'title': Value(dtype='string', id=None), # 'score': Value(dtype='float64', id=None) # }, num_rows: 99999) # suggested in #665 class PicklableTokenizer(BertJapaneseTokenizer): def __getstate__(self): state = dict(self.__dict__) state['do_lower_case'] = self.word_tokenizer.do_lower_case state['never_split'] = self.word_tokenizer.never_split del state['word_tokenizer'] return state def __setstate(self): do_lower_case = state.pop('do_lower_case') never_split = state.pop('never_split') self.__dict__ = state self.word_tokenizer = MecabTokenizer( do_lower_case=do_lower_case, never_split=never_split ) t = PicklableTokenizer.from_pretrained('bert-base-japanese-whole-word-masking') encoded = train_ds.map( lambda examples: {'tokens': t.encode(examples['title'], max_length=1000)}, batched=True, batch_size=1000 ) ``` Error Message: ``` 99% 99/100 [00:22<00:00, 39.07ba/s] --------------------------------------------------------------------------- ArrowInvalid Traceback (most recent call last) <timed exec> in <module> /usr/local/lib/python3.6/site-packages/datasets/arrow_dataset.py in map(self, function, with_indices, input_columns, batched, batch_size, drop_last_batch, remove_columns, keep_in_memory, load_from_cache_file, cache_file_name, writer_batch_size, features, disable_nullable, fn_kwargs, num_proc, suffix_template, new_fingerprint) 1242 fn_kwargs=fn_kwargs, 1243 new_fingerprint=new_fingerprint, -> 1244 update_data=update_data, 1245 ) 1246 else: /usr/local/lib/python3.6/site-packages/datasets/arrow_dataset.py in wrapper(*args, **kwargs) 151 "output_all_columns": self._output_all_columns, 152 } --> 153 out: Union["Dataset", "DatasetDict"] = func(self, *args, **kwargs) 154 if new_format["columns"] is not None: 155 new_format["columns"] = list(set(new_format["columns"]) & set(out.column_names)) /usr/local/lib/python3.6/site-packages/datasets/fingerprint.py in wrapper(*args, **kwargs) 161 # Call actual function 162 --> 163 out = func(self, *args, **kwargs) 164 165 # Update fingerprint of in-place transforms + update in-place history of transforms /usr/local/lib/python3.6/site-packages/datasets/arrow_dataset.py in _map_single(self, function, with_indices, input_columns, batched, batch_size, drop_last_batch, remove_columns, keep_in_memory, load_from_cache_file, cache_file_name, writer_batch_size, features, disable_nullable, fn_kwargs, new_fingerprint, rank, offset, update_data) 1496 if update_data: 1497 batch = cast_to_python_objects(batch) -> 1498 writer.write_batch(batch) 1499 if update_data: 1500 writer.finalize() # close_stream=bool(buf_writer is None)) # We only close if we are writing in a file /usr/local/lib/python3.6/site-packages/datasets/arrow_writer.py in write_batch(self, batch_examples, writer_batch_size) 271 typed_sequence = TypedSequence(batch_examples[col], type=col_type, try_type=col_try_type) 272 typed_sequence_examples[col] = typed_sequence --> 273 pa_table = pa.Table.from_pydict(typed_sequence_examples) 274 self.write_table(pa_table) 275 /usr/local/lib/python3.6/site-packages/pyarrow/table.pxi in pyarrow.lib.Table.from_pydict() /usr/local/lib/python3.6/site-packages/pyarrow/table.pxi in pyarrow.lib.Table.from_arrays() /usr/local/lib/python3.6/site-packages/pyarrow/table.pxi in pyarrow.lib.Table.validate() /usr/local/lib/python3.6/site-packages/pyarrow/error.pxi in pyarrow.lib.check_status() ArrowInvalid: Column 4 named tokens expected length 999 but got length 1000 ``` Thank you very much for the kind and precise suggestion! I'm looking forward to seeing BertJapaneseTokenizer built into the "fast" tokenizers. I tried `map` with multiprocessing as follows, and it worked! ```python # There was a Pickle problem if I use `lambda` for multiprocessing def encode(examples): return {'tokens': t.encode(examples['title'], max_length=1000)} num_proc = 8 encoded = train_ds.map(encode, num_proc=num_proc) ``` Thank you again!
https://github.com/huggingface/datasets/issues/686
Dataset browser url is still https://huggingface.co/nlp/viewer/
Yes! might do it with @srush one of these days. Hopefully it won't break too many links (we can always redirect from old url to new)
Might be worth updating to https://huggingface.co/datasets/viewer/
26
Dataset browser url is still https://huggingface.co/nlp/viewer/ Might be worth updating to https://huggingface.co/datasets/viewer/ Yes! might do it with @srush one of these days. Hopefully it won't break too many links (we can always redirect from old url to new)
https://github.com/huggingface/datasets/issues/678
The download instructions for c4 datasets are not contained in the error message
Also not that C4 is a dataset that needs an Apache Beam runtime to be generated. For example Dataflow, Spark, Flink etc. Usually we generate the dataset on our side once and for all, but we haven't done it for C4 yet. More info about beam datasets [here](https://huggingface.co/docs/datasets/beam_dataset.html) Let me know if you have any questions
The manual download instructions are not clear ```The dataset c4 with config en requires manual data. Please follow the manual download instructions: <bound method C4.manual_download_instructions of <datasets_modules.datasets.c4.830b0c218bd41fed439812c8dd19dbd4767d2a3faa385eb695cf8666c982b1b3.c4.C4 object at 0x7ff8c5969760>>. Manual data can be loaded with `datasets.load_dataset(c4, data_dir='<path/to/manual/data>') ``` Either `@property` could be added to C4.manual_download_instrcutions (or make it a real property), or the manual_download_instructions function needs to be called I think. Let me know if you want a PR for this, but I'm not sure which possible fix is the correct one.
56
The download instructions for c4 datasets are not contained in the error message The manual download instructions are not clear ```The dataset c4 with config en requires manual data. Please follow the manual download instructions: <bound method C4.manual_download_instructions of <datasets_modules.datasets.c4.830b0c218bd41fed439812c8dd19dbd4767d2a3faa385eb695cf8666c982b1b3.c4.C4 object at 0x7ff8c5969760>>. Manual data can be loaded with `datasets.load_dataset(c4, data_dir='<path/to/manual/data>') ``` Either `@property` could be added to C4.manual_download_instrcutions (or make it a real property), or the manual_download_instructions function needs to be called I think. Let me know if you want a PR for this, but I'm not sure which possible fix is the correct one. Also not that C4 is a dataset that needs an Apache Beam runtime to be generated. For example Dataflow, Spark, Flink etc. Usually we generate the dataset on our side once and for all, but we haven't done it for C4 yet. More info about beam datasets [here](https://huggingface.co/docs/datasets/beam_dataset.html) Let me know if you have any questions
https://github.com/huggingface/datasets/issues/676
train_test_split returns empty dataset item
Can you reproduce this example in a Colab so we can investigate? (or give more information on your software/hardware config)
I try to split my dataset by `train_test_split`, but after that the item in `train` and `test` `Dataset` is empty. The codes: ``` yelp_data = datasets.load_from_disk('/home/ssd4/huanglianzhe/test_yelp') print(yelp_data[0]) yelp_data = yelp_data.train_test_split(test_size=0.1) print(yelp_data) print(yelp_data['test']) print(yelp_data['test'][0]) ``` The outputs: ``` {'stars': 2.0, 'text': 'xxxx'} Loading cached split indices for dataset at /home/ssd4/huanglianzhe/test_yelp/cache-f9b22d8b9d5a7346.arrow and /home/ssd4/huanglianzhe/test_yelp/cache-4aa26fa4005059d1.arrow DatasetDict({'train': Dataset(features: {'stars': Value(dtype='float64', id=None), 'text': Value(dtype='string', id=None)}, num_rows: 7219009), 'test': Dataset(features: {'stars': Value(dtype='float64', id=None), 'text': Value(dtype='string', id=None)}, num_rows: 802113)}) Dataset(features: {'stars': Value(dtype='float64', id=None), 'text': Value(dtype='string', id=None)}, num_rows: 802113) {} # yelp_data['test'][0] is empty ```
20
train_test_split returns empty dataset item I try to split my dataset by `train_test_split`, but after that the item in `train` and `test` `Dataset` is empty. The codes: ``` yelp_data = datasets.load_from_disk('/home/ssd4/huanglianzhe/test_yelp') print(yelp_data[0]) yelp_data = yelp_data.train_test_split(test_size=0.1) print(yelp_data) print(yelp_data['test']) print(yelp_data['test'][0]) ``` The outputs: ``` {'stars': 2.0, 'text': 'xxxx'} Loading cached split indices for dataset at /home/ssd4/huanglianzhe/test_yelp/cache-f9b22d8b9d5a7346.arrow and /home/ssd4/huanglianzhe/test_yelp/cache-4aa26fa4005059d1.arrow DatasetDict({'train': Dataset(features: {'stars': Value(dtype='float64', id=None), 'text': Value(dtype='string', id=None)}, num_rows: 7219009), 'test': Dataset(features: {'stars': Value(dtype='float64', id=None), 'text': Value(dtype='string', id=None)}, num_rows: 802113)}) Dataset(features: {'stars': Value(dtype='float64', id=None), 'text': Value(dtype='string', id=None)}, num_rows: 802113) {} # yelp_data['test'][0] is empty ``` Can you reproduce this example in a Colab so we can investigate? (or give more information on your software/hardware config)
https://github.com/huggingface/datasets/issues/676
train_test_split returns empty dataset item
We'll do a release pretty soon to include the fix :) In the meantime you can install the lib from source if you want to
I try to split my dataset by `train_test_split`, but after that the item in `train` and `test` `Dataset` is empty. The codes: ``` yelp_data = datasets.load_from_disk('/home/ssd4/huanglianzhe/test_yelp') print(yelp_data[0]) yelp_data = yelp_data.train_test_split(test_size=0.1) print(yelp_data) print(yelp_data['test']) print(yelp_data['test'][0]) ``` The outputs: ``` {'stars': 2.0, 'text': 'xxxx'} Loading cached split indices for dataset at /home/ssd4/huanglianzhe/test_yelp/cache-f9b22d8b9d5a7346.arrow and /home/ssd4/huanglianzhe/test_yelp/cache-4aa26fa4005059d1.arrow DatasetDict({'train': Dataset(features: {'stars': Value(dtype='float64', id=None), 'text': Value(dtype='string', id=None)}, num_rows: 7219009), 'test': Dataset(features: {'stars': Value(dtype='float64', id=None), 'text': Value(dtype='string', id=None)}, num_rows: 802113)}) Dataset(features: {'stars': Value(dtype='float64', id=None), 'text': Value(dtype='string', id=None)}, num_rows: 802113) {} # yelp_data['test'][0] is empty ```
25
train_test_split returns empty dataset item I try to split my dataset by `train_test_split`, but after that the item in `train` and `test` `Dataset` is empty. The codes: ``` yelp_data = datasets.load_from_disk('/home/ssd4/huanglianzhe/test_yelp') print(yelp_data[0]) yelp_data = yelp_data.train_test_split(test_size=0.1) print(yelp_data) print(yelp_data['test']) print(yelp_data['test'][0]) ``` The outputs: ``` {'stars': 2.0, 'text': 'xxxx'} Loading cached split indices for dataset at /home/ssd4/huanglianzhe/test_yelp/cache-f9b22d8b9d5a7346.arrow and /home/ssd4/huanglianzhe/test_yelp/cache-4aa26fa4005059d1.arrow DatasetDict({'train': Dataset(features: {'stars': Value(dtype='float64', id=None), 'text': Value(dtype='string', id=None)}, num_rows: 7219009), 'test': Dataset(features: {'stars': Value(dtype='float64', id=None), 'text': Value(dtype='string', id=None)}, num_rows: 802113)}) Dataset(features: {'stars': Value(dtype='float64', id=None), 'text': Value(dtype='string', id=None)}, num_rows: 802113) {} # yelp_data['test'][0] is empty ``` We'll do a release pretty soon to include the fix :) In the meantime you can install the lib from source if you want to
https://github.com/huggingface/datasets/issues/674
load_dataset() won't download in Windows
I have the same issue. Tried to download a few of them and not a single one is downloaded successfully. This is the output: ``` >>> dataset = load_dataset('blended_skill_talk', split='train') Using custom data configuration default <-- This step never ends ```
I don't know if this is just me or Windows. Maybe other Windows users can chime in if they don't have this problem. I've been trying to get some of the tutorials working on Windows, but when I use the load_dataset() function, it just stalls and the script keeps running indefinitely without downloading anything. I've waited upwards of 18 hours to download the 'multi-news' dataset (which isn't very big), and still nothing. I've tried running it through different IDE's and the command line, but it had the same behavior. I've also tried it with all virus and malware protection turned off. I've made sure python and all IDE's are exceptions to the firewall and all the requisite permissions are enabled. Additionally, I checked to see if other packages could download content such as an nltk corpus, and they could. I've also run the same script using Ubuntu and it downloaded fine (and quickly). When I copied the downloaded datasets from my Ubuntu drive to my Windows .cache folder it worked fine by reusing the already-downloaded dataset, but it's cumbersome to do that for every dataset I want to try in my Windows environment. Could this be a bug, or is there something I'm doing wrong or not thinking of? Thanks.
41
load_dataset() won't download in Windows I don't know if this is just me or Windows. Maybe other Windows users can chime in if they don't have this problem. I've been trying to get some of the tutorials working on Windows, but when I use the load_dataset() function, it just stalls and the script keeps running indefinitely without downloading anything. I've waited upwards of 18 hours to download the 'multi-news' dataset (which isn't very big), and still nothing. I've tried running it through different IDE's and the command line, but it had the same behavior. I've also tried it with all virus and malware protection turned off. I've made sure python and all IDE's are exceptions to the firewall and all the requisite permissions are enabled. Additionally, I checked to see if other packages could download content such as an nltk corpus, and they could. I've also run the same script using Ubuntu and it downloaded fine (and quickly). When I copied the downloaded datasets from my Ubuntu drive to my Windows .cache folder it worked fine by reusing the already-downloaded dataset, but it's cumbersome to do that for every dataset I want to try in my Windows environment. Could this be a bug, or is there something I'm doing wrong or not thinking of? Thanks. I have the same issue. Tried to download a few of them and not a single one is downloaded successfully. This is the output: ``` >>> dataset = load_dataset('blended_skill_talk', split='train') Using custom data configuration default <-- This step never ends ```
https://github.com/huggingface/datasets/issues/674
load_dataset() won't download in Windows
This was fixed in #644 I'll do a new release soon :) In the meantime you can run it by installing from source
I don't know if this is just me or Windows. Maybe other Windows users can chime in if they don't have this problem. I've been trying to get some of the tutorials working on Windows, but when I use the load_dataset() function, it just stalls and the script keeps running indefinitely without downloading anything. I've waited upwards of 18 hours to download the 'multi-news' dataset (which isn't very big), and still nothing. I've tried running it through different IDE's and the command line, but it had the same behavior. I've also tried it with all virus and malware protection turned off. I've made sure python and all IDE's are exceptions to the firewall and all the requisite permissions are enabled. Additionally, I checked to see if other packages could download content such as an nltk corpus, and they could. I've also run the same script using Ubuntu and it downloaded fine (and quickly). When I copied the downloaded datasets from my Ubuntu drive to my Windows .cache folder it worked fine by reusing the already-downloaded dataset, but it's cumbersome to do that for every dataset I want to try in my Windows environment. Could this be a bug, or is there something I'm doing wrong or not thinking of? Thanks.
23
load_dataset() won't download in Windows I don't know if this is just me or Windows. Maybe other Windows users can chime in if they don't have this problem. I've been trying to get some of the tutorials working on Windows, but when I use the load_dataset() function, it just stalls and the script keeps running indefinitely without downloading anything. I've waited upwards of 18 hours to download the 'multi-news' dataset (which isn't very big), and still nothing. I've tried running it through different IDE's and the command line, but it had the same behavior. I've also tried it with all virus and malware protection turned off. I've made sure python and all IDE's are exceptions to the firewall and all the requisite permissions are enabled. Additionally, I checked to see if other packages could download content such as an nltk corpus, and they could. I've also run the same script using Ubuntu and it downloaded fine (and quickly). When I copied the downloaded datasets from my Ubuntu drive to my Windows .cache folder it worked fine by reusing the already-downloaded dataset, but it's cumbersome to do that for every dataset I want to try in my Windows environment. Could this be a bug, or is there something I'm doing wrong or not thinking of? Thanks. This was fixed in #644 I'll do a new release soon :) In the meantime you can run it by installing from source
https://github.com/huggingface/datasets/issues/674
load_dataset() won't download in Windows
Closing since version 1.1.0 got released with Windows support :) Let me know if it works for you now
I don't know if this is just me or Windows. Maybe other Windows users can chime in if they don't have this problem. I've been trying to get some of the tutorials working on Windows, but when I use the load_dataset() function, it just stalls and the script keeps running indefinitely without downloading anything. I've waited upwards of 18 hours to download the 'multi-news' dataset (which isn't very big), and still nothing. I've tried running it through different IDE's and the command line, but it had the same behavior. I've also tried it with all virus and malware protection turned off. I've made sure python and all IDE's are exceptions to the firewall and all the requisite permissions are enabled. Additionally, I checked to see if other packages could download content such as an nltk corpus, and they could. I've also run the same script using Ubuntu and it downloaded fine (and quickly). When I copied the downloaded datasets from my Ubuntu drive to my Windows .cache folder it worked fine by reusing the already-downloaded dataset, but it's cumbersome to do that for every dataset I want to try in my Windows environment. Could this be a bug, or is there something I'm doing wrong or not thinking of? Thanks.
19
load_dataset() won't download in Windows I don't know if this is just me or Windows. Maybe other Windows users can chime in if they don't have this problem. I've been trying to get some of the tutorials working on Windows, but when I use the load_dataset() function, it just stalls and the script keeps running indefinitely without downloading anything. I've waited upwards of 18 hours to download the 'multi-news' dataset (which isn't very big), and still nothing. I've tried running it through different IDE's and the command line, but it had the same behavior. I've also tried it with all virus and malware protection turned off. I've made sure python and all IDE's are exceptions to the firewall and all the requisite permissions are enabled. Additionally, I checked to see if other packages could download content such as an nltk corpus, and they could. I've also run the same script using Ubuntu and it downloaded fine (and quickly). When I copied the downloaded datasets from my Ubuntu drive to my Windows .cache folder it worked fine by reusing the already-downloaded dataset, but it's cumbersome to do that for every dataset I want to try in my Windows environment. Could this be a bug, or is there something I'm doing wrong or not thinking of? Thanks. Closing since version 1.1.0 got released with Windows support :) Let me know if it works for you now
https://github.com/huggingface/datasets/issues/672
Questions about XSUM
We should try to regenerate the data using the official script. But iirc that's what we used in the first place, so not sure why it didn't match in the first place. I'll let you know when the dataset is updated
Hi there โœ‹ I'm looking into your `xsum` dataset and I have several questions on that. So here is how I loaded the data: ``` >>> data = datasets.load_dataset('xsum', version='1.0.1') >>> data['train'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 204017) >>> data['test'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 11333) ``` The first issue is, the instance counts donโ€™t match what I see on [the dataset's website](https://github.com/EdinburghNLP/XSum/tree/master/XSum-Dataset#what-builds-the-xsum-dataset) (11,333 vs 11,334 for test set; 204,017 vs 204,045 for training set) ``` โ€ฆ training (90%, 204,045), validation (5%, 11,332), and test (5%, 11,334) set. ``` Any thoughts why? Perhaps @mariamabarham could help here, since she recently had a PR on this dataaset https://github.com/huggingface/datasets/pull/289 (reviewed by @patrickvonplaten) Another issue is that the instances don't seem to have IDs. The original datasets provides IDs for the instances: https://github.com/EdinburghNLP/XSum/blob/master/XSum-Dataset/XSum-TRAINING-DEV-TEST-SPLIT-90-5-5.json but to be able to use them, the dataset sizes need to match. CC @jbragg
41
Questions about XSUM Hi there โœ‹ I'm looking into your `xsum` dataset and I have several questions on that. So here is how I loaded the data: ``` >>> data = datasets.load_dataset('xsum', version='1.0.1') >>> data['train'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 204017) >>> data['test'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 11333) ``` The first issue is, the instance counts donโ€™t match what I see on [the dataset's website](https://github.com/EdinburghNLP/XSum/tree/master/XSum-Dataset#what-builds-the-xsum-dataset) (11,333 vs 11,334 for test set; 204,017 vs 204,045 for training set) ``` โ€ฆ training (90%, 204,045), validation (5%, 11,332), and test (5%, 11,334) set. ``` Any thoughts why? Perhaps @mariamabarham could help here, since she recently had a PR on this dataaset https://github.com/huggingface/datasets/pull/289 (reviewed by @patrickvonplaten) Another issue is that the instances don't seem to have IDs. The original datasets provides IDs for the instances: https://github.com/EdinburghNLP/XSum/blob/master/XSum-Dataset/XSum-TRAINING-DEV-TEST-SPLIT-90-5-5.json but to be able to use them, the dataset sizes need to match. CC @jbragg We should try to regenerate the data using the official script. But iirc that's what we used in the first place, so not sure why it didn't match in the first place. I'll let you know when the dataset is updated
https://github.com/huggingface/datasets/issues/672
Questions about XSUM
Thanks, looking forward to hearing your update on this thread. This is a blocking issue for us; would appreciate any progress on this front. We can also help with the fix, if you deem it appropriately.
Hi there โœ‹ I'm looking into your `xsum` dataset and I have several questions on that. So here is how I loaded the data: ``` >>> data = datasets.load_dataset('xsum', version='1.0.1') >>> data['train'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 204017) >>> data['test'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 11333) ``` The first issue is, the instance counts donโ€™t match what I see on [the dataset's website](https://github.com/EdinburghNLP/XSum/tree/master/XSum-Dataset#what-builds-the-xsum-dataset) (11,333 vs 11,334 for test set; 204,017 vs 204,045 for training set) ``` โ€ฆ training (90%, 204,045), validation (5%, 11,332), and test (5%, 11,334) set. ``` Any thoughts why? Perhaps @mariamabarham could help here, since she recently had a PR on this dataaset https://github.com/huggingface/datasets/pull/289 (reviewed by @patrickvonplaten) Another issue is that the instances don't seem to have IDs. The original datasets provides IDs for the instances: https://github.com/EdinburghNLP/XSum/blob/master/XSum-Dataset/XSum-TRAINING-DEV-TEST-SPLIT-90-5-5.json but to be able to use them, the dataset sizes need to match. CC @jbragg
36
Questions about XSUM Hi there โœ‹ I'm looking into your `xsum` dataset and I have several questions on that. So here is how I loaded the data: ``` >>> data = datasets.load_dataset('xsum', version='1.0.1') >>> data['train'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 204017) >>> data['test'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 11333) ``` The first issue is, the instance counts donโ€™t match what I see on [the dataset's website](https://github.com/EdinburghNLP/XSum/tree/master/XSum-Dataset#what-builds-the-xsum-dataset) (11,333 vs 11,334 for test set; 204,017 vs 204,045 for training set) ``` โ€ฆ training (90%, 204,045), validation (5%, 11,332), and test (5%, 11,334) set. ``` Any thoughts why? Perhaps @mariamabarham could help here, since she recently had a PR on this dataaset https://github.com/huggingface/datasets/pull/289 (reviewed by @patrickvonplaten) Another issue is that the instances don't seem to have IDs. The original datasets provides IDs for the instances: https://github.com/EdinburghNLP/XSum/blob/master/XSum-Dataset/XSum-TRAINING-DEV-TEST-SPLIT-90-5-5.json but to be able to use them, the dataset sizes need to match. CC @jbragg Thanks, looking forward to hearing your update on this thread. This is a blocking issue for us; would appreciate any progress on this front. We can also help with the fix, if you deem it appropriately.
https://github.com/huggingface/datasets/issues/672
Questions about XSUM
I just started the generation on my side, I'll let you know how it goes :)
Hi there โœ‹ I'm looking into your `xsum` dataset and I have several questions on that. So here is how I loaded the data: ``` >>> data = datasets.load_dataset('xsum', version='1.0.1') >>> data['train'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 204017) >>> data['test'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 11333) ``` The first issue is, the instance counts donโ€™t match what I see on [the dataset's website](https://github.com/EdinburghNLP/XSum/tree/master/XSum-Dataset#what-builds-the-xsum-dataset) (11,333 vs 11,334 for test set; 204,017 vs 204,045 for training set) ``` โ€ฆ training (90%, 204,045), validation (5%, 11,332), and test (5%, 11,334) set. ``` Any thoughts why? Perhaps @mariamabarham could help here, since she recently had a PR on this dataaset https://github.com/huggingface/datasets/pull/289 (reviewed by @patrickvonplaten) Another issue is that the instances don't seem to have IDs. The original datasets provides IDs for the instances: https://github.com/EdinburghNLP/XSum/blob/master/XSum-Dataset/XSum-TRAINING-DEV-TEST-SPLIT-90-5-5.json but to be able to use them, the dataset sizes need to match. CC @jbragg
16
Questions about XSUM Hi there โœ‹ I'm looking into your `xsum` dataset and I have several questions on that. So here is how I loaded the data: ``` >>> data = datasets.load_dataset('xsum', version='1.0.1') >>> data['train'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 204017) >>> data['test'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 11333) ``` The first issue is, the instance counts donโ€™t match what I see on [the dataset's website](https://github.com/EdinburghNLP/XSum/tree/master/XSum-Dataset#what-builds-the-xsum-dataset) (11,333 vs 11,334 for test set; 204,017 vs 204,045 for training set) ``` โ€ฆ training (90%, 204,045), validation (5%, 11,332), and test (5%, 11,334) set. ``` Any thoughts why? Perhaps @mariamabarham could help here, since she recently had a PR on this dataaset https://github.com/huggingface/datasets/pull/289 (reviewed by @patrickvonplaten) Another issue is that the instances don't seem to have IDs. The original datasets provides IDs for the instances: https://github.com/EdinburghNLP/XSum/blob/master/XSum-Dataset/XSum-TRAINING-DEV-TEST-SPLIT-90-5-5.json but to be able to use them, the dataset sizes need to match. CC @jbragg I just started the generation on my side, I'll let you know how it goes :)
https://github.com/huggingface/datasets/issues/672
Questions about XSUM
Hmm after a first run I'm still missing 136668/226711 urls. I'll relaunch it tomorrow to try to get the remaining ones.
Hi there โœ‹ I'm looking into your `xsum` dataset and I have several questions on that. So here is how I loaded the data: ``` >>> data = datasets.load_dataset('xsum', version='1.0.1') >>> data['train'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 204017) >>> data['test'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 11333) ``` The first issue is, the instance counts donโ€™t match what I see on [the dataset's website](https://github.com/EdinburghNLP/XSum/tree/master/XSum-Dataset#what-builds-the-xsum-dataset) (11,333 vs 11,334 for test set; 204,017 vs 204,045 for training set) ``` โ€ฆ training (90%, 204,045), validation (5%, 11,332), and test (5%, 11,334) set. ``` Any thoughts why? Perhaps @mariamabarham could help here, since she recently had a PR on this dataaset https://github.com/huggingface/datasets/pull/289 (reviewed by @patrickvonplaten) Another issue is that the instances don't seem to have IDs. The original datasets provides IDs for the instances: https://github.com/EdinburghNLP/XSum/blob/master/XSum-Dataset/XSum-TRAINING-DEV-TEST-SPLIT-90-5-5.json but to be able to use them, the dataset sizes need to match. CC @jbragg
21
Questions about XSUM Hi there โœ‹ I'm looking into your `xsum` dataset and I have several questions on that. So here is how I loaded the data: ``` >>> data = datasets.load_dataset('xsum', version='1.0.1') >>> data['train'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 204017) >>> data['test'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 11333) ``` The first issue is, the instance counts donโ€™t match what I see on [the dataset's website](https://github.com/EdinburghNLP/XSum/tree/master/XSum-Dataset#what-builds-the-xsum-dataset) (11,333 vs 11,334 for test set; 204,017 vs 204,045 for training set) ``` โ€ฆ training (90%, 204,045), validation (5%, 11,332), and test (5%, 11,334) set. ``` Any thoughts why? Perhaps @mariamabarham could help here, since she recently had a PR on this dataaset https://github.com/huggingface/datasets/pull/289 (reviewed by @patrickvonplaten) Another issue is that the instances don't seem to have IDs. The original datasets provides IDs for the instances: https://github.com/EdinburghNLP/XSum/blob/master/XSum-Dataset/XSum-TRAINING-DEV-TEST-SPLIT-90-5-5.json but to be able to use them, the dataset sizes need to match. CC @jbragg Hmm after a first run I'm still missing 136668/226711 urls. I'll relaunch it tomorrow to try to get the remaining ones.
https://github.com/huggingface/datasets/issues/672
Questions about XSUM
So I managed to download them all but when parsing only 226,181/226,711 worked. Not sure if it's worth digging and debugging parsing at this point :/
Hi there โœ‹ I'm looking into your `xsum` dataset and I have several questions on that. So here is how I loaded the data: ``` >>> data = datasets.load_dataset('xsum', version='1.0.1') >>> data['train'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 204017) >>> data['test'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 11333) ``` The first issue is, the instance counts donโ€™t match what I see on [the dataset's website](https://github.com/EdinburghNLP/XSum/tree/master/XSum-Dataset#what-builds-the-xsum-dataset) (11,333 vs 11,334 for test set; 204,017 vs 204,045 for training set) ``` โ€ฆ training (90%, 204,045), validation (5%, 11,332), and test (5%, 11,334) set. ``` Any thoughts why? Perhaps @mariamabarham could help here, since she recently had a PR on this dataaset https://github.com/huggingface/datasets/pull/289 (reviewed by @patrickvonplaten) Another issue is that the instances don't seem to have IDs. The original datasets provides IDs for the instances: https://github.com/EdinburghNLP/XSum/blob/master/XSum-Dataset/XSum-TRAINING-DEV-TEST-SPLIT-90-5-5.json but to be able to use them, the dataset sizes need to match. CC @jbragg
26
Questions about XSUM Hi there โœ‹ I'm looking into your `xsum` dataset and I have several questions on that. So here is how I loaded the data: ``` >>> data = datasets.load_dataset('xsum', version='1.0.1') >>> data['train'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 204017) >>> data['test'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 11333) ``` The first issue is, the instance counts donโ€™t match what I see on [the dataset's website](https://github.com/EdinburghNLP/XSum/tree/master/XSum-Dataset#what-builds-the-xsum-dataset) (11,333 vs 11,334 for test set; 204,017 vs 204,045 for training set) ``` โ€ฆ training (90%, 204,045), validation (5%, 11,332), and test (5%, 11,334) set. ``` Any thoughts why? Perhaps @mariamabarham could help here, since she recently had a PR on this dataaset https://github.com/huggingface/datasets/pull/289 (reviewed by @patrickvonplaten) Another issue is that the instances don't seem to have IDs. The original datasets provides IDs for the instances: https://github.com/EdinburghNLP/XSum/blob/master/XSum-Dataset/XSum-TRAINING-DEV-TEST-SPLIT-90-5-5.json but to be able to use them, the dataset sizes need to match. CC @jbragg So I managed to download them all but when parsing only 226,181/226,711 worked. Not sure if it's worth digging and debugging parsing at this point :/
https://github.com/huggingface/datasets/issues/672
Questions about XSUM
Thanks @lhoestq It would be great to improve coverage, but IDs are the really crucial part for us. We'd really appreciate an update to the dataset with IDs either way!
Hi there โœ‹ I'm looking into your `xsum` dataset and I have several questions on that. So here is how I loaded the data: ``` >>> data = datasets.load_dataset('xsum', version='1.0.1') >>> data['train'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 204017) >>> data['test'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 11333) ``` The first issue is, the instance counts donโ€™t match what I see on [the dataset's website](https://github.com/EdinburghNLP/XSum/tree/master/XSum-Dataset#what-builds-the-xsum-dataset) (11,333 vs 11,334 for test set; 204,017 vs 204,045 for training set) ``` โ€ฆ training (90%, 204,045), validation (5%, 11,332), and test (5%, 11,334) set. ``` Any thoughts why? Perhaps @mariamabarham could help here, since she recently had a PR on this dataaset https://github.com/huggingface/datasets/pull/289 (reviewed by @patrickvonplaten) Another issue is that the instances don't seem to have IDs. The original datasets provides IDs for the instances: https://github.com/EdinburghNLP/XSum/blob/master/XSum-Dataset/XSum-TRAINING-DEV-TEST-SPLIT-90-5-5.json but to be able to use them, the dataset sizes need to match. CC @jbragg
30
Questions about XSUM Hi there โœ‹ I'm looking into your `xsum` dataset and I have several questions on that. So here is how I loaded the data: ``` >>> data = datasets.load_dataset('xsum', version='1.0.1') >>> data['train'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 204017) >>> data['test'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 11333) ``` The first issue is, the instance counts donโ€™t match what I see on [the dataset's website](https://github.com/EdinburghNLP/XSum/tree/master/XSum-Dataset#what-builds-the-xsum-dataset) (11,333 vs 11,334 for test set; 204,017 vs 204,045 for training set) ``` โ€ฆ training (90%, 204,045), validation (5%, 11,332), and test (5%, 11,334) set. ``` Any thoughts why? Perhaps @mariamabarham could help here, since she recently had a PR on this dataaset https://github.com/huggingface/datasets/pull/289 (reviewed by @patrickvonplaten) Another issue is that the instances don't seem to have IDs. The original datasets provides IDs for the instances: https://github.com/EdinburghNLP/XSum/blob/master/XSum-Dataset/XSum-TRAINING-DEV-TEST-SPLIT-90-5-5.json but to be able to use them, the dataset sizes need to match. CC @jbragg Thanks @lhoestq It would be great to improve coverage, but IDs are the really crucial part for us. We'd really appreciate an update to the dataset with IDs either way!
https://github.com/huggingface/datasets/issues/672
Questions about XSUM
I gave up at an even earlier point. The dataset I use has 204,017 train examples.
Hi there โœ‹ I'm looking into your `xsum` dataset and I have several questions on that. So here is how I loaded the data: ``` >>> data = datasets.load_dataset('xsum', version='1.0.1') >>> data['train'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 204017) >>> data['test'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 11333) ``` The first issue is, the instance counts donโ€™t match what I see on [the dataset's website](https://github.com/EdinburghNLP/XSum/tree/master/XSum-Dataset#what-builds-the-xsum-dataset) (11,333 vs 11,334 for test set; 204,017 vs 204,045 for training set) ``` โ€ฆ training (90%, 204,045), validation (5%, 11,332), and test (5%, 11,334) set. ``` Any thoughts why? Perhaps @mariamabarham could help here, since she recently had a PR on this dataaset https://github.com/huggingface/datasets/pull/289 (reviewed by @patrickvonplaten) Another issue is that the instances don't seem to have IDs. The original datasets provides IDs for the instances: https://github.com/EdinburghNLP/XSum/blob/master/XSum-Dataset/XSum-TRAINING-DEV-TEST-SPLIT-90-5-5.json but to be able to use them, the dataset sizes need to match. CC @jbragg
16
Questions about XSUM Hi there โœ‹ I'm looking into your `xsum` dataset and I have several questions on that. So here is how I loaded the data: ``` >>> data = datasets.load_dataset('xsum', version='1.0.1') >>> data['train'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 204017) >>> data['test'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 11333) ``` The first issue is, the instance counts donโ€™t match what I see on [the dataset's website](https://github.com/EdinburghNLP/XSum/tree/master/XSum-Dataset#what-builds-the-xsum-dataset) (11,333 vs 11,334 for test set; 204,017 vs 204,045 for training set) ``` โ€ฆ training (90%, 204,045), validation (5%, 11,332), and test (5%, 11,334) set. ``` Any thoughts why? Perhaps @mariamabarham could help here, since she recently had a PR on this dataaset https://github.com/huggingface/datasets/pull/289 (reviewed by @patrickvonplaten) Another issue is that the instances don't seem to have IDs. The original datasets provides IDs for the instances: https://github.com/EdinburghNLP/XSum/blob/master/XSum-Dataset/XSum-TRAINING-DEV-TEST-SPLIT-90-5-5.json but to be able to use them, the dataset sizes need to match. CC @jbragg I gave up at an even earlier point. The dataset I use has 204,017 train examples.
https://github.com/huggingface/datasets/issues/672
Questions about XSUM
@lhoestq @sshleifer like @jbragg said earlier, the main issue for us is that the current XSUM dataset (in your package) does not have IDs suggested by the original dataset ([here is the file](https://raw.githubusercontent.com/EdinburghNLP/XSum/master/XSum-Dataset/XSum-TRAINING-DEV-TEST-SPLIT-90-5-5.json).) Would appreciate if you update the XSUM dataset to include the instance IDs. The missing instances is also a problem, but likely not worth pursuing given its relatively small scale.
Hi there โœ‹ I'm looking into your `xsum` dataset and I have several questions on that. So here is how I loaded the data: ``` >>> data = datasets.load_dataset('xsum', version='1.0.1') >>> data['train'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 204017) >>> data['test'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 11333) ``` The first issue is, the instance counts donโ€™t match what I see on [the dataset's website](https://github.com/EdinburghNLP/XSum/tree/master/XSum-Dataset#what-builds-the-xsum-dataset) (11,333 vs 11,334 for test set; 204,017 vs 204,045 for training set) ``` โ€ฆ training (90%, 204,045), validation (5%, 11,332), and test (5%, 11,334) set. ``` Any thoughts why? Perhaps @mariamabarham could help here, since she recently had a PR on this dataaset https://github.com/huggingface/datasets/pull/289 (reviewed by @patrickvonplaten) Another issue is that the instances don't seem to have IDs. The original datasets provides IDs for the instances: https://github.com/EdinburghNLP/XSum/blob/master/XSum-Dataset/XSum-TRAINING-DEV-TEST-SPLIT-90-5-5.json but to be able to use them, the dataset sizes need to match. CC @jbragg
63
Questions about XSUM Hi there โœ‹ I'm looking into your `xsum` dataset and I have several questions on that. So here is how I loaded the data: ``` >>> data = datasets.load_dataset('xsum', version='1.0.1') >>> data['train'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 204017) >>> data['test'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 11333) ``` The first issue is, the instance counts donโ€™t match what I see on [the dataset's website](https://github.com/EdinburghNLP/XSum/tree/master/XSum-Dataset#what-builds-the-xsum-dataset) (11,333 vs 11,334 for test set; 204,017 vs 204,045 for training set) ``` โ€ฆ training (90%, 204,045), validation (5%, 11,332), and test (5%, 11,334) set. ``` Any thoughts why? Perhaps @mariamabarham could help here, since she recently had a PR on this dataaset https://github.com/huggingface/datasets/pull/289 (reviewed by @patrickvonplaten) Another issue is that the instances don't seem to have IDs. The original datasets provides IDs for the instances: https://github.com/EdinburghNLP/XSum/blob/master/XSum-Dataset/XSum-TRAINING-DEV-TEST-SPLIT-90-5-5.json but to be able to use them, the dataset sizes need to match. CC @jbragg @lhoestq @sshleifer like @jbragg said earlier, the main issue for us is that the current XSUM dataset (in your package) does not have IDs suggested by the original dataset ([here is the file](https://raw.githubusercontent.com/EdinburghNLP/XSum/master/XSum-Dataset/XSum-TRAINING-DEV-TEST-SPLIT-90-5-5.json).) Would appreciate if you update the XSUM dataset to include the instance IDs. The missing instances is also a problem, but likely not worth pursuing given its relatively small scale.
https://github.com/huggingface/datasets/issues/672
Questions about XSUM
>So I managed to download them all but when parsing only 226,181/226,711 worked. @lhoestq any chance we could update the HF-hosted dataset with the IDs in your new version? Happy to help if there's something I can do.
Hi there โœ‹ I'm looking into your `xsum` dataset and I have several questions on that. So here is how I loaded the data: ``` >>> data = datasets.load_dataset('xsum', version='1.0.1') >>> data['train'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 204017) >>> data['test'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 11333) ``` The first issue is, the instance counts donโ€™t match what I see on [the dataset's website](https://github.com/EdinburghNLP/XSum/tree/master/XSum-Dataset#what-builds-the-xsum-dataset) (11,333 vs 11,334 for test set; 204,017 vs 204,045 for training set) ``` โ€ฆ training (90%, 204,045), validation (5%, 11,332), and test (5%, 11,334) set. ``` Any thoughts why? Perhaps @mariamabarham could help here, since she recently had a PR on this dataaset https://github.com/huggingface/datasets/pull/289 (reviewed by @patrickvonplaten) Another issue is that the instances don't seem to have IDs. The original datasets provides IDs for the instances: https://github.com/EdinburghNLP/XSum/blob/master/XSum-Dataset/XSum-TRAINING-DEV-TEST-SPLIT-90-5-5.json but to be able to use them, the dataset sizes need to match. CC @jbragg
38
Questions about XSUM Hi there โœ‹ I'm looking into your `xsum` dataset and I have several questions on that. So here is how I loaded the data: ``` >>> data = datasets.load_dataset('xsum', version='1.0.1') >>> data['train'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 204017) >>> data['test'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 11333) ``` The first issue is, the instance counts donโ€™t match what I see on [the dataset's website](https://github.com/EdinburghNLP/XSum/tree/master/XSum-Dataset#what-builds-the-xsum-dataset) (11,333 vs 11,334 for test set; 204,017 vs 204,045 for training set) ``` โ€ฆ training (90%, 204,045), validation (5%, 11,332), and test (5%, 11,334) set. ``` Any thoughts why? Perhaps @mariamabarham could help here, since she recently had a PR on this dataaset https://github.com/huggingface/datasets/pull/289 (reviewed by @patrickvonplaten) Another issue is that the instances don't seem to have IDs. The original datasets provides IDs for the instances: https://github.com/EdinburghNLP/XSum/blob/master/XSum-Dataset/XSum-TRAINING-DEV-TEST-SPLIT-90-5-5.json but to be able to use them, the dataset sizes need to match. CC @jbragg >So I managed to download them all but when parsing only 226,181/226,711 worked. @lhoestq any chance we could update the HF-hosted dataset with the IDs in your new version? Happy to help if there's something I can do.
https://github.com/huggingface/datasets/issues/672
Questions about XSUM
Well I couldn't parse what I downloaded. Unfortunately I think I won't be able to take a look at it this week. I can try to send you what I got if you want to give it a shot @jbragg Otherwise feel free to re-run the xsum download script, maybe you'll be luckier than me
Hi there โœ‹ I'm looking into your `xsum` dataset and I have several questions on that. So here is how I loaded the data: ``` >>> data = datasets.load_dataset('xsum', version='1.0.1') >>> data['train'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 204017) >>> data['test'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 11333) ``` The first issue is, the instance counts donโ€™t match what I see on [the dataset's website](https://github.com/EdinburghNLP/XSum/tree/master/XSum-Dataset#what-builds-the-xsum-dataset) (11,333 vs 11,334 for test set; 204,017 vs 204,045 for training set) ``` โ€ฆ training (90%, 204,045), validation (5%, 11,332), and test (5%, 11,334) set. ``` Any thoughts why? Perhaps @mariamabarham could help here, since she recently had a PR on this dataaset https://github.com/huggingface/datasets/pull/289 (reviewed by @patrickvonplaten) Another issue is that the instances don't seem to have IDs. The original datasets provides IDs for the instances: https://github.com/EdinburghNLP/XSum/blob/master/XSum-Dataset/XSum-TRAINING-DEV-TEST-SPLIT-90-5-5.json but to be able to use them, the dataset sizes need to match. CC @jbragg
55
Questions about XSUM Hi there โœ‹ I'm looking into your `xsum` dataset and I have several questions on that. So here is how I loaded the data: ``` >>> data = datasets.load_dataset('xsum', version='1.0.1') >>> data['train'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 204017) >>> data['test'] Dataset(features: {'document': Value(dtype='string', id=None), 'summary': Value(dtype='string', id=None)}, num_rows: 11333) ``` The first issue is, the instance counts donโ€™t match what I see on [the dataset's website](https://github.com/EdinburghNLP/XSum/tree/master/XSum-Dataset#what-builds-the-xsum-dataset) (11,333 vs 11,334 for test set; 204,017 vs 204,045 for training set) ``` โ€ฆ training (90%, 204,045), validation (5%, 11,332), and test (5%, 11,334) set. ``` Any thoughts why? Perhaps @mariamabarham could help here, since she recently had a PR on this dataaset https://github.com/huggingface/datasets/pull/289 (reviewed by @patrickvonplaten) Another issue is that the instances don't seem to have IDs. The original datasets provides IDs for the instances: https://github.com/EdinburghNLP/XSum/blob/master/XSum-Dataset/XSum-TRAINING-DEV-TEST-SPLIT-90-5-5.json but to be able to use them, the dataset sizes need to match. CC @jbragg Well I couldn't parse what I downloaded. Unfortunately I think I won't be able to take a look at it this week. I can try to send you what I got if you want to give it a shot @jbragg Otherwise feel free to re-run the xsum download script, maybe you'll be luckier than me
https://github.com/huggingface/datasets/issues/669
How to skip a example when running dataset.map
Hi @xixiaoyao, Depending on what you want to do you can: - use a first step of `filter` to filter out the invalid examples: https://huggingface.co/docs/datasets/processing.html#filtering-rows-select-and-filter - or directly detect the invalid examples inside the callable used with `map` and return them unchanged or even remove them at the same time if you are using `map` in batched mode. Here is an example where we use `map` in batched mode to add new rows on the fly but you can also use it to remove examples on the fly (that's what `filter` actually do under-the-hood): https://huggingface.co/docs/datasets/processing.html#augmenting-the-dataset
in processing func, I process examples and detect some invalid examples, which I did not want it to be added into train dataset. However I did not find how to skip this recognized invalid example when doing dataset.map.
95
How to skip a example when running dataset.map in processing func, I process examples and detect some invalid examples, which I did not want it to be added into train dataset. However I did not find how to skip this recognized invalid example when doing dataset.map. Hi @xixiaoyao, Depending on what you want to do you can: - use a first step of `filter` to filter out the invalid examples: https://huggingface.co/docs/datasets/processing.html#filtering-rows-select-and-filter - or directly detect the invalid examples inside the callable used with `map` and return them unchanged or even remove them at the same time if you are using `map` in batched mode. Here is an example where we use `map` in batched mode to add new rows on the fly but you can also use it to remove examples on the fly (that's what `filter` actually do under-the-hood): https://huggingface.co/docs/datasets/processing.html#augmenting-the-dataset
https://github.com/huggingface/datasets/issues/667
Loss not decrease with Datasets and Transformers
Hi did you manage to fix your issue ? If so feel free to share your fix and close this thread
HI, The following script is used to fine-tune a BertForSequenceClassification model on SST2. The script is adapted from [this colab](https://colab.research.google.com/github/huggingface/datasets/blob/master/notebooks/Overview.ipynb) that presents an example of fine-tuning BertForQuestionAnswering using squad dataset. In that colab, loss works fine. When I adapt it to SST2, the loss fails to decrease as it should. I attach the adapted script below and appreciate anyone pointing out what I miss? ```python import torch from datasets import load_dataset from transformers import BertForSequenceClassification from transformers import BertTokenizerFast # Load our training dataset and tokenizer dataset = load_dataset("glue", 'sst2') tokenizer = BertTokenizerFast.from_pretrained('bert-base-cased') del dataset["test"] # let's remove it in this demo # Tokenize our training dataset def convert_to_features(example_batch): encodings = tokenizer(example_batch["sentence"]) encodings.update({"labels": example_batch["label"]}) return encodings encoded_dataset = dataset.map(convert_to_features, batched=True) # Format our dataset to outputs torch.Tensor to train a pytorch model columns = ['input_ids', 'token_type_ids', 'attention_mask', 'labels'] encoded_dataset.set_format(type='torch', columns=columns) # Instantiate a PyTorch Dataloader around our dataset # Let's do dynamic batching (pad on the fly with our own collate_fn) def collate_fn(examples): return tokenizer.pad(examples, return_tensors='pt') dataloader = torch.utils.data.DataLoader(encoded_dataset['train'], collate_fn=collate_fn, batch_size=8) # Now let's train our model device = 'cuda' if torch.cuda.is_available() else 'cpu' # Let's load a pretrained Bert model and a simple optimizer model = BertForSequenceClassification.from_pretrained('bert-base-cased', return_dict=True) optimizer = torch.optim.Adam(model.parameters(), lr=1e-5) model.train().to(device) for i, batch in enumerate(dataloader): batch.to(device) outputs = model(**batch) loss = outputs.loss loss.backward() optimizer.step() model.zero_grad() print(f'Step {i} - loss: {loss:.3}') ``` In case needed. - datasets == 1.0.2 - transformers == 3.2.0
21
Loss not decrease with Datasets and Transformers HI, The following script is used to fine-tune a BertForSequenceClassification model on SST2. The script is adapted from [this colab](https://colab.research.google.com/github/huggingface/datasets/blob/master/notebooks/Overview.ipynb) that presents an example of fine-tuning BertForQuestionAnswering using squad dataset. In that colab, loss works fine. When I adapt it to SST2, the loss fails to decrease as it should. I attach the adapted script below and appreciate anyone pointing out what I miss? ```python import torch from datasets import load_dataset from transformers import BertForSequenceClassification from transformers import BertTokenizerFast # Load our training dataset and tokenizer dataset = load_dataset("glue", 'sst2') tokenizer = BertTokenizerFast.from_pretrained('bert-base-cased') del dataset["test"] # let's remove it in this demo # Tokenize our training dataset def convert_to_features(example_batch): encodings = tokenizer(example_batch["sentence"]) encodings.update({"labels": example_batch["label"]}) return encodings encoded_dataset = dataset.map(convert_to_features, batched=True) # Format our dataset to outputs torch.Tensor to train a pytorch model columns = ['input_ids', 'token_type_ids', 'attention_mask', 'labels'] encoded_dataset.set_format(type='torch', columns=columns) # Instantiate a PyTorch Dataloader around our dataset # Let's do dynamic batching (pad on the fly with our own collate_fn) def collate_fn(examples): return tokenizer.pad(examples, return_tensors='pt') dataloader = torch.utils.data.DataLoader(encoded_dataset['train'], collate_fn=collate_fn, batch_size=8) # Now let's train our model device = 'cuda' if torch.cuda.is_available() else 'cpu' # Let's load a pretrained Bert model and a simple optimizer model = BertForSequenceClassification.from_pretrained('bert-base-cased', return_dict=True) optimizer = torch.optim.Adam(model.parameters(), lr=1e-5) model.train().to(device) for i, batch in enumerate(dataloader): batch.to(device) outputs = model(**batch) loss = outputs.loss loss.backward() optimizer.step() model.zero_grad() print(f'Step {i} - loss: {loss:.3}') ``` In case needed. - datasets == 1.0.2 - transformers == 3.2.0 Hi did you manage to fix your issue ? If so feel free to share your fix and close this thread
https://github.com/huggingface/datasets/issues/666
Does both 'bookcorpus' and 'wikipedia' belong to the same datasets which Google used for pretraining BERT?
No they are other similar copies but they are not provided by the official Bert models authors.
17
Does both 'bookcorpus' and 'wikipedia' belong to the same datasets which Google used for pretraining BERT? No they are other similar copies but they are not provided by the official Bert models authors.
https://github.com/huggingface/datasets/issues/665
runing dataset.map, it raises TypeError: can't pickle Tokenizer objects
Hi ! It works on my side with both the LongFormerTokenizer and the LongFormerTokenizerFast. Which version of transformers/datasets are you using ?
I load squad dataset. Then want to process data use following function with `Huggingface Transformers LongformerTokenizer`. ``` def convert_to_features(example): # Tokenize contexts and questions (as pairs of inputs) input_pairs = [example['question'], example['context']] encodings = tokenizer.encode_plus(input_pairs, pad_to_max_length=True, max_length=512) context_encodings = tokenizer.encode_plus(example['context']) # Compute start and end tokens for labels using Transformers's fast tokenizers alignement methodes. # this will give us the position of answer span in the context text start_idx, end_idx = get_correct_alignement(example['context'], example['answers']) start_positions_context = context_encodings.char_to_token(start_idx) end_positions_context = context_encodings.char_to_token(end_idx-1) # here we will compute the start and end position of the answer in the whole example # as the example is encoded like this <s> question</s></s> context</s> # and we know the postion of the answer in the context # we can just find out the index of the sep token and then add that to position + 1 (+1 because there are two sep tokens) # this will give us the position of the answer span in whole example sep_idx = encodings['input_ids'].index(tokenizer.sep_token_id) start_positions = start_positions_context + sep_idx + 1 end_positions = end_positions_context + sep_idx + 1 if end_positions > 512: start_positions, end_positions = 0, 0 encodings.update({'start_positions': start_positions, 'end_positions': end_positions, 'attention_mask': encodings['attention_mask']}) return encodings ``` Then I run `dataset.map(convert_to_features)`, it raise ``` In [59]: a.map(convert_to_features) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-59-c453b508761d> in <module> ----> 1 a.map(convert_to_features) /opt/conda/lib/python3.7/site-packages/datasets/arrow_dataset.py in map(self, function, with_indices, input_columns, batched, batch_size, drop_last_batch, remove_columns, keep_in_memory, load_from_cache_file, cache_file_name, writer_batch_size, features, disable_nullable, fn_kwargs, num_proc, suffix_template, new_fingerprint) 1242 fn_kwargs=fn_kwargs, 1243 new_fingerprint=new_fingerprint, -> 1244 update_data=update_data, 1245 ) 1246 else: /opt/conda/lib/python3.7/site-packages/datasets/arrow_dataset.py in wrapper(*args, **kwargs) 151 "output_all_columns": self._output_all_columns, 152 } --> 153 out: Union["Dataset", "DatasetDict"] = func(self, *args, **kwargs) 154 if new_format["columns"] is not None: 155 new_format["columns"] = list(set(new_format["columns"]) & set(out.column_names)) /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in wrapper(*args, **kwargs) 156 kwargs_for_fingerprint["fingerprint_name"] = fingerprint_name 157 kwargs[fingerprint_name] = update_fingerprint( --> 158 self._fingerprint, transform, kwargs_for_fingerprint 159 ) 160 /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in update_fingerprint(fingerprint, transform, transform_args) 103 for key in sorted(transform_args): 104 hasher.update(key) --> 105 hasher.update(transform_args[key]) 106 return hasher.hexdigest() 107 /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in update(self, value) 55 def update(self, value): 56 self.m.update(f"=={type(value)}==".encode("utf8")) ---> 57 self.m.update(self.hash(value).encode("utf-8")) 58 59 def hexdigest(self): /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in hash(cls, value) 51 return cls.dispatch[type(value)](cls, value) 52 else: ---> 53 return cls.hash_default(value) 54 55 def update(self, value): /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in hash_default(cls, value) 44 @classmethod 45 def hash_default(cls, value): ---> 46 return cls.hash_bytes(dumps(value)) 47 48 @classmethod /opt/conda/lib/python3.7/site-packages/datasets/utils/py_utils.py in dumps(obj) 365 file = StringIO() 366 with _no_cache_fields(obj): --> 367 dump(obj, file) 368 return file.getvalue() 369 /opt/conda/lib/python3.7/site-packages/datasets/utils/py_utils.py in dump(obj, file) 337 def dump(obj, file): 338 """pickle an object to a file""" --> 339 Pickler(file, recurse=True).dump(obj) 340 return 341 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in dump(self, obj) 444 raise PicklingError(msg) 445 else: --> 446 StockPickler.dump(self, obj) 447 stack.clear() # clear record of 'recursion-sensitive' pickled objects 448 return /opt/conda/lib/python3.7/pickle.py in dump(self, obj) 435 if self.proto >= 4: 436 self.framer.start_framing() --> 437 self.save(obj) 438 self.write(STOP) 439 self.framer.end_framing() /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_function(pickler, obj) 1436 globs, obj.__name__, 1437 obj.__defaults__, obj.__closure__, -> 1438 obj.__dict__, fkwdefaults), obj=obj) 1439 else: 1440 _super = ('super' in getattr(obj.func_code,'co_names',())) and (_byref is not None) and getattr(pickler, '_recurse', False) /opt/conda/lib/python3.7/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 636 else: 637 save(func) --> 638 save(args) 639 write(REDUCE) 640 /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/pickle.py in save_tuple(self, obj) 787 write(MARK) 788 for element in obj: --> 789 save(element) 790 791 if id(obj) in memo: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /opt/conda/lib/python3.7/pickle.py in save_dict(self, obj) 857 858 self.memoize(obj) --> 859 self._batch_setitems(obj.items()) 860 861 dispatch[dict] = save_dict /opt/conda/lib/python3.7/pickle.py in _batch_setitems(self, items) 883 for k, v in tmp: 884 save(k) --> 885 save(v) 886 write(SETITEMS) 887 elif n: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 547 548 # Save the reduce() output and finally memoize the object --> 549 self.save_reduce(obj=obj, *rv) 550 551 def persistent_id(self, obj): /opt/conda/lib/python3.7/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 660 661 if state is not None: --> 662 save(state) 663 write(BUILD) 664 /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /opt/conda/lib/python3.7/pickle.py in save_dict(self, obj) 857 858 self.memoize(obj) --> 859 self._batch_setitems(obj.items()) 860 861 dispatch[dict] = save_dict /opt/conda/lib/python3.7/pickle.py in _batch_setitems(self, items) 883 for k, v in tmp: 884 save(k) --> 885 save(v) 886 write(SETITEMS) 887 elif n: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 547 548 # Save the reduce() output and finally memoize the object --> 549 self.save_reduce(obj=obj, *rv) 550 551 def persistent_id(self, obj): /opt/conda/lib/python3.7/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 660 661 if state is not None: --> 662 save(state) 663 write(BUILD) 664 /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /opt/conda/lib/python3.7/pickle.py in save_dict(self, obj) 857 858 self.memoize(obj) --> 859 self._batch_setitems(obj.items()) 860 861 dispatch[dict] = save_dict /opt/conda/lib/python3.7/pickle.py in _batch_setitems(self, items) 883 for k, v in tmp: 884 save(k) --> 885 save(v) 886 write(SETITEMS) 887 elif n: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 522 reduce = getattr(obj, "__reduce_ex__", None) 523 if reduce is not None: --> 524 rv = reduce(self.proto) 525 else: 526 reduce = getattr(obj, "__reduce__", None) TypeError: can't pickle Tokenizer objects ```
22
runing dataset.map, it raises TypeError: can't pickle Tokenizer objects I load squad dataset. Then want to process data use following function with `Huggingface Transformers LongformerTokenizer`. ``` def convert_to_features(example): # Tokenize contexts and questions (as pairs of inputs) input_pairs = [example['question'], example['context']] encodings = tokenizer.encode_plus(input_pairs, pad_to_max_length=True, max_length=512) context_encodings = tokenizer.encode_plus(example['context']) # Compute start and end tokens for labels using Transformers's fast tokenizers alignement methodes. # this will give us the position of answer span in the context text start_idx, end_idx = get_correct_alignement(example['context'], example['answers']) start_positions_context = context_encodings.char_to_token(start_idx) end_positions_context = context_encodings.char_to_token(end_idx-1) # here we will compute the start and end position of the answer in the whole example # as the example is encoded like this <s> question</s></s> context</s> # and we know the postion of the answer in the context # we can just find out the index of the sep token and then add that to position + 1 (+1 because there are two sep tokens) # this will give us the position of the answer span in whole example sep_idx = encodings['input_ids'].index(tokenizer.sep_token_id) start_positions = start_positions_context + sep_idx + 1 end_positions = end_positions_context + sep_idx + 1 if end_positions > 512: start_positions, end_positions = 0, 0 encodings.update({'start_positions': start_positions, 'end_positions': end_positions, 'attention_mask': encodings['attention_mask']}) return encodings ``` Then I run `dataset.map(convert_to_features)`, it raise ``` In [59]: a.map(convert_to_features) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-59-c453b508761d> in <module> ----> 1 a.map(convert_to_features) /opt/conda/lib/python3.7/site-packages/datasets/arrow_dataset.py in map(self, function, with_indices, input_columns, batched, batch_size, drop_last_batch, remove_columns, keep_in_memory, load_from_cache_file, cache_file_name, writer_batch_size, features, disable_nullable, fn_kwargs, num_proc, suffix_template, new_fingerprint) 1242 fn_kwargs=fn_kwargs, 1243 new_fingerprint=new_fingerprint, -> 1244 update_data=update_data, 1245 ) 1246 else: /opt/conda/lib/python3.7/site-packages/datasets/arrow_dataset.py in wrapper(*args, **kwargs) 151 "output_all_columns": self._output_all_columns, 152 } --> 153 out: Union["Dataset", "DatasetDict"] = func(self, *args, **kwargs) 154 if new_format["columns"] is not None: 155 new_format["columns"] = list(set(new_format["columns"]) & set(out.column_names)) /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in wrapper(*args, **kwargs) 156 kwargs_for_fingerprint["fingerprint_name"] = fingerprint_name 157 kwargs[fingerprint_name] = update_fingerprint( --> 158 self._fingerprint, transform, kwargs_for_fingerprint 159 ) 160 /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in update_fingerprint(fingerprint, transform, transform_args) 103 for key in sorted(transform_args): 104 hasher.update(key) --> 105 hasher.update(transform_args[key]) 106 return hasher.hexdigest() 107 /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in update(self, value) 55 def update(self, value): 56 self.m.update(f"=={type(value)}==".encode("utf8")) ---> 57 self.m.update(self.hash(value).encode("utf-8")) 58 59 def hexdigest(self): /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in hash(cls, value) 51 return cls.dispatch[type(value)](cls, value) 52 else: ---> 53 return cls.hash_default(value) 54 55 def update(self, value): /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in hash_default(cls, value) 44 @classmethod 45 def hash_default(cls, value): ---> 46 return cls.hash_bytes(dumps(value)) 47 48 @classmethod /opt/conda/lib/python3.7/site-packages/datasets/utils/py_utils.py in dumps(obj) 365 file = StringIO() 366 with _no_cache_fields(obj): --> 367 dump(obj, file) 368 return file.getvalue() 369 /opt/conda/lib/python3.7/site-packages/datasets/utils/py_utils.py in dump(obj, file) 337 def dump(obj, file): 338 """pickle an object to a file""" --> 339 Pickler(file, recurse=True).dump(obj) 340 return 341 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in dump(self, obj) 444 raise PicklingError(msg) 445 else: --> 446 StockPickler.dump(self, obj) 447 stack.clear() # clear record of 'recursion-sensitive' pickled objects 448 return /opt/conda/lib/python3.7/pickle.py in dump(self, obj) 435 if self.proto >= 4: 436 self.framer.start_framing() --> 437 self.save(obj) 438 self.write(STOP) 439 self.framer.end_framing() /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_function(pickler, obj) 1436 globs, obj.__name__, 1437 obj.__defaults__, obj.__closure__, -> 1438 obj.__dict__, fkwdefaults), obj=obj) 1439 else: 1440 _super = ('super' in getattr(obj.func_code,'co_names',())) and (_byref is not None) and getattr(pickler, '_recurse', False) /opt/conda/lib/python3.7/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 636 else: 637 save(func) --> 638 save(args) 639 write(REDUCE) 640 /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/pickle.py in save_tuple(self, obj) 787 write(MARK) 788 for element in obj: --> 789 save(element) 790 791 if id(obj) in memo: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /opt/conda/lib/python3.7/pickle.py in save_dict(self, obj) 857 858 self.memoize(obj) --> 859 self._batch_setitems(obj.items()) 860 861 dispatch[dict] = save_dict /opt/conda/lib/python3.7/pickle.py in _batch_setitems(self, items) 883 for k, v in tmp: 884 save(k) --> 885 save(v) 886 write(SETITEMS) 887 elif n: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 547 548 # Save the reduce() output and finally memoize the object --> 549 self.save_reduce(obj=obj, *rv) 550 551 def persistent_id(self, obj): /opt/conda/lib/python3.7/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 660 661 if state is not None: --> 662 save(state) 663 write(BUILD) 664 /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /opt/conda/lib/python3.7/pickle.py in save_dict(self, obj) 857 858 self.memoize(obj) --> 859 self._batch_setitems(obj.items()) 860 861 dispatch[dict] = save_dict /opt/conda/lib/python3.7/pickle.py in _batch_setitems(self, items) 883 for k, v in tmp: 884 save(k) --> 885 save(v) 886 write(SETITEMS) 887 elif n: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 547 548 # Save the reduce() output and finally memoize the object --> 549 self.save_reduce(obj=obj, *rv) 550 551 def persistent_id(self, obj): /opt/conda/lib/python3.7/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 660 661 if state is not None: --> 662 save(state) 663 write(BUILD) 664 /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /opt/conda/lib/python3.7/pickle.py in save_dict(self, obj) 857 858 self.memoize(obj) --> 859 self._batch_setitems(obj.items()) 860 861 dispatch[dict] = save_dict /opt/conda/lib/python3.7/pickle.py in _batch_setitems(self, items) 883 for k, v in tmp: 884 save(k) --> 885 save(v) 886 write(SETITEMS) 887 elif n: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 522 reduce = getattr(obj, "__reduce_ex__", None) 523 if reduce is not None: --> 524 rv = reduce(self.proto) 525 else: 526 reduce = getattr(obj, "__reduce__", None) TypeError: can't pickle Tokenizer objects ``` Hi ! It works on my side with both the LongFormerTokenizer and the LongFormerTokenizerFast. Which version of transformers/datasets are you using ?
https://github.com/huggingface/datasets/issues/665
runing dataset.map, it raises TypeError: can't pickle Tokenizer objects
Then I guess you need to give us more informations on your setup (OS, python, GPU, etc) or a Google Colab reproducing the error for us to be able to debug this error.
I load squad dataset. Then want to process data use following function with `Huggingface Transformers LongformerTokenizer`. ``` def convert_to_features(example): # Tokenize contexts and questions (as pairs of inputs) input_pairs = [example['question'], example['context']] encodings = tokenizer.encode_plus(input_pairs, pad_to_max_length=True, max_length=512) context_encodings = tokenizer.encode_plus(example['context']) # Compute start and end tokens for labels using Transformers's fast tokenizers alignement methodes. # this will give us the position of answer span in the context text start_idx, end_idx = get_correct_alignement(example['context'], example['answers']) start_positions_context = context_encodings.char_to_token(start_idx) end_positions_context = context_encodings.char_to_token(end_idx-1) # here we will compute the start and end position of the answer in the whole example # as the example is encoded like this <s> question</s></s> context</s> # and we know the postion of the answer in the context # we can just find out the index of the sep token and then add that to position + 1 (+1 because there are two sep tokens) # this will give us the position of the answer span in whole example sep_idx = encodings['input_ids'].index(tokenizer.sep_token_id) start_positions = start_positions_context + sep_idx + 1 end_positions = end_positions_context + sep_idx + 1 if end_positions > 512: start_positions, end_positions = 0, 0 encodings.update({'start_positions': start_positions, 'end_positions': end_positions, 'attention_mask': encodings['attention_mask']}) return encodings ``` Then I run `dataset.map(convert_to_features)`, it raise ``` In [59]: a.map(convert_to_features) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-59-c453b508761d> in <module> ----> 1 a.map(convert_to_features) /opt/conda/lib/python3.7/site-packages/datasets/arrow_dataset.py in map(self, function, with_indices, input_columns, batched, batch_size, drop_last_batch, remove_columns, keep_in_memory, load_from_cache_file, cache_file_name, writer_batch_size, features, disable_nullable, fn_kwargs, num_proc, suffix_template, new_fingerprint) 1242 fn_kwargs=fn_kwargs, 1243 new_fingerprint=new_fingerprint, -> 1244 update_data=update_data, 1245 ) 1246 else: /opt/conda/lib/python3.7/site-packages/datasets/arrow_dataset.py in wrapper(*args, **kwargs) 151 "output_all_columns": self._output_all_columns, 152 } --> 153 out: Union["Dataset", "DatasetDict"] = func(self, *args, **kwargs) 154 if new_format["columns"] is not None: 155 new_format["columns"] = list(set(new_format["columns"]) & set(out.column_names)) /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in wrapper(*args, **kwargs) 156 kwargs_for_fingerprint["fingerprint_name"] = fingerprint_name 157 kwargs[fingerprint_name] = update_fingerprint( --> 158 self._fingerprint, transform, kwargs_for_fingerprint 159 ) 160 /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in update_fingerprint(fingerprint, transform, transform_args) 103 for key in sorted(transform_args): 104 hasher.update(key) --> 105 hasher.update(transform_args[key]) 106 return hasher.hexdigest() 107 /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in update(self, value) 55 def update(self, value): 56 self.m.update(f"=={type(value)}==".encode("utf8")) ---> 57 self.m.update(self.hash(value).encode("utf-8")) 58 59 def hexdigest(self): /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in hash(cls, value) 51 return cls.dispatch[type(value)](cls, value) 52 else: ---> 53 return cls.hash_default(value) 54 55 def update(self, value): /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in hash_default(cls, value) 44 @classmethod 45 def hash_default(cls, value): ---> 46 return cls.hash_bytes(dumps(value)) 47 48 @classmethod /opt/conda/lib/python3.7/site-packages/datasets/utils/py_utils.py in dumps(obj) 365 file = StringIO() 366 with _no_cache_fields(obj): --> 367 dump(obj, file) 368 return file.getvalue() 369 /opt/conda/lib/python3.7/site-packages/datasets/utils/py_utils.py in dump(obj, file) 337 def dump(obj, file): 338 """pickle an object to a file""" --> 339 Pickler(file, recurse=True).dump(obj) 340 return 341 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in dump(self, obj) 444 raise PicklingError(msg) 445 else: --> 446 StockPickler.dump(self, obj) 447 stack.clear() # clear record of 'recursion-sensitive' pickled objects 448 return /opt/conda/lib/python3.7/pickle.py in dump(self, obj) 435 if self.proto >= 4: 436 self.framer.start_framing() --> 437 self.save(obj) 438 self.write(STOP) 439 self.framer.end_framing() /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_function(pickler, obj) 1436 globs, obj.__name__, 1437 obj.__defaults__, obj.__closure__, -> 1438 obj.__dict__, fkwdefaults), obj=obj) 1439 else: 1440 _super = ('super' in getattr(obj.func_code,'co_names',())) and (_byref is not None) and getattr(pickler, '_recurse', False) /opt/conda/lib/python3.7/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 636 else: 637 save(func) --> 638 save(args) 639 write(REDUCE) 640 /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/pickle.py in save_tuple(self, obj) 787 write(MARK) 788 for element in obj: --> 789 save(element) 790 791 if id(obj) in memo: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /opt/conda/lib/python3.7/pickle.py in save_dict(self, obj) 857 858 self.memoize(obj) --> 859 self._batch_setitems(obj.items()) 860 861 dispatch[dict] = save_dict /opt/conda/lib/python3.7/pickle.py in _batch_setitems(self, items) 883 for k, v in tmp: 884 save(k) --> 885 save(v) 886 write(SETITEMS) 887 elif n: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 547 548 # Save the reduce() output and finally memoize the object --> 549 self.save_reduce(obj=obj, *rv) 550 551 def persistent_id(self, obj): /opt/conda/lib/python3.7/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 660 661 if state is not None: --> 662 save(state) 663 write(BUILD) 664 /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /opt/conda/lib/python3.7/pickle.py in save_dict(self, obj) 857 858 self.memoize(obj) --> 859 self._batch_setitems(obj.items()) 860 861 dispatch[dict] = save_dict /opt/conda/lib/python3.7/pickle.py in _batch_setitems(self, items) 883 for k, v in tmp: 884 save(k) --> 885 save(v) 886 write(SETITEMS) 887 elif n: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 547 548 # Save the reduce() output and finally memoize the object --> 549 self.save_reduce(obj=obj, *rv) 550 551 def persistent_id(self, obj): /opt/conda/lib/python3.7/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 660 661 if state is not None: --> 662 save(state) 663 write(BUILD) 664 /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /opt/conda/lib/python3.7/pickle.py in save_dict(self, obj) 857 858 self.memoize(obj) --> 859 self._batch_setitems(obj.items()) 860 861 dispatch[dict] = save_dict /opt/conda/lib/python3.7/pickle.py in _batch_setitems(self, items) 883 for k, v in tmp: 884 save(k) --> 885 save(v) 886 write(SETITEMS) 887 elif n: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 522 reduce = getattr(obj, "__reduce_ex__", None) 523 if reduce is not None: --> 524 rv = reduce(self.proto) 525 else: 526 reduce = getattr(obj, "__reduce__", None) TypeError: can't pickle Tokenizer objects ```
33
runing dataset.map, it raises TypeError: can't pickle Tokenizer objects I load squad dataset. Then want to process data use following function with `Huggingface Transformers LongformerTokenizer`. ``` def convert_to_features(example): # Tokenize contexts and questions (as pairs of inputs) input_pairs = [example['question'], example['context']] encodings = tokenizer.encode_plus(input_pairs, pad_to_max_length=True, max_length=512) context_encodings = tokenizer.encode_plus(example['context']) # Compute start and end tokens for labels using Transformers's fast tokenizers alignement methodes. # this will give us the position of answer span in the context text start_idx, end_idx = get_correct_alignement(example['context'], example['answers']) start_positions_context = context_encodings.char_to_token(start_idx) end_positions_context = context_encodings.char_to_token(end_idx-1) # here we will compute the start and end position of the answer in the whole example # as the example is encoded like this <s> question</s></s> context</s> # and we know the postion of the answer in the context # we can just find out the index of the sep token and then add that to position + 1 (+1 because there are two sep tokens) # this will give us the position of the answer span in whole example sep_idx = encodings['input_ids'].index(tokenizer.sep_token_id) start_positions = start_positions_context + sep_idx + 1 end_positions = end_positions_context + sep_idx + 1 if end_positions > 512: start_positions, end_positions = 0, 0 encodings.update({'start_positions': start_positions, 'end_positions': end_positions, 'attention_mask': encodings['attention_mask']}) return encodings ``` Then I run `dataset.map(convert_to_features)`, it raise ``` In [59]: a.map(convert_to_features) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-59-c453b508761d> in <module> ----> 1 a.map(convert_to_features) /opt/conda/lib/python3.7/site-packages/datasets/arrow_dataset.py in map(self, function, with_indices, input_columns, batched, batch_size, drop_last_batch, remove_columns, keep_in_memory, load_from_cache_file, cache_file_name, writer_batch_size, features, disable_nullable, fn_kwargs, num_proc, suffix_template, new_fingerprint) 1242 fn_kwargs=fn_kwargs, 1243 new_fingerprint=new_fingerprint, -> 1244 update_data=update_data, 1245 ) 1246 else: /opt/conda/lib/python3.7/site-packages/datasets/arrow_dataset.py in wrapper(*args, **kwargs) 151 "output_all_columns": self._output_all_columns, 152 } --> 153 out: Union["Dataset", "DatasetDict"] = func(self, *args, **kwargs) 154 if new_format["columns"] is not None: 155 new_format["columns"] = list(set(new_format["columns"]) & set(out.column_names)) /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in wrapper(*args, **kwargs) 156 kwargs_for_fingerprint["fingerprint_name"] = fingerprint_name 157 kwargs[fingerprint_name] = update_fingerprint( --> 158 self._fingerprint, transform, kwargs_for_fingerprint 159 ) 160 /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in update_fingerprint(fingerprint, transform, transform_args) 103 for key in sorted(transform_args): 104 hasher.update(key) --> 105 hasher.update(transform_args[key]) 106 return hasher.hexdigest() 107 /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in update(self, value) 55 def update(self, value): 56 self.m.update(f"=={type(value)}==".encode("utf8")) ---> 57 self.m.update(self.hash(value).encode("utf-8")) 58 59 def hexdigest(self): /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in hash(cls, value) 51 return cls.dispatch[type(value)](cls, value) 52 else: ---> 53 return cls.hash_default(value) 54 55 def update(self, value): /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in hash_default(cls, value) 44 @classmethod 45 def hash_default(cls, value): ---> 46 return cls.hash_bytes(dumps(value)) 47 48 @classmethod /opt/conda/lib/python3.7/site-packages/datasets/utils/py_utils.py in dumps(obj) 365 file = StringIO() 366 with _no_cache_fields(obj): --> 367 dump(obj, file) 368 return file.getvalue() 369 /opt/conda/lib/python3.7/site-packages/datasets/utils/py_utils.py in dump(obj, file) 337 def dump(obj, file): 338 """pickle an object to a file""" --> 339 Pickler(file, recurse=True).dump(obj) 340 return 341 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in dump(self, obj) 444 raise PicklingError(msg) 445 else: --> 446 StockPickler.dump(self, obj) 447 stack.clear() # clear record of 'recursion-sensitive' pickled objects 448 return /opt/conda/lib/python3.7/pickle.py in dump(self, obj) 435 if self.proto >= 4: 436 self.framer.start_framing() --> 437 self.save(obj) 438 self.write(STOP) 439 self.framer.end_framing() /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_function(pickler, obj) 1436 globs, obj.__name__, 1437 obj.__defaults__, obj.__closure__, -> 1438 obj.__dict__, fkwdefaults), obj=obj) 1439 else: 1440 _super = ('super' in getattr(obj.func_code,'co_names',())) and (_byref is not None) and getattr(pickler, '_recurse', False) /opt/conda/lib/python3.7/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 636 else: 637 save(func) --> 638 save(args) 639 write(REDUCE) 640 /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/pickle.py in save_tuple(self, obj) 787 write(MARK) 788 for element in obj: --> 789 save(element) 790 791 if id(obj) in memo: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /opt/conda/lib/python3.7/pickle.py in save_dict(self, obj) 857 858 self.memoize(obj) --> 859 self._batch_setitems(obj.items()) 860 861 dispatch[dict] = save_dict /opt/conda/lib/python3.7/pickle.py in _batch_setitems(self, items) 883 for k, v in tmp: 884 save(k) --> 885 save(v) 886 write(SETITEMS) 887 elif n: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 547 548 # Save the reduce() output and finally memoize the object --> 549 self.save_reduce(obj=obj, *rv) 550 551 def persistent_id(self, obj): /opt/conda/lib/python3.7/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 660 661 if state is not None: --> 662 save(state) 663 write(BUILD) 664 /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /opt/conda/lib/python3.7/pickle.py in save_dict(self, obj) 857 858 self.memoize(obj) --> 859 self._batch_setitems(obj.items()) 860 861 dispatch[dict] = save_dict /opt/conda/lib/python3.7/pickle.py in _batch_setitems(self, items) 883 for k, v in tmp: 884 save(k) --> 885 save(v) 886 write(SETITEMS) 887 elif n: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 547 548 # Save the reduce() output and finally memoize the object --> 549 self.save_reduce(obj=obj, *rv) 550 551 def persistent_id(self, obj): /opt/conda/lib/python3.7/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 660 661 if state is not None: --> 662 save(state) 663 write(BUILD) 664 /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /opt/conda/lib/python3.7/pickle.py in save_dict(self, obj) 857 858 self.memoize(obj) --> 859 self._batch_setitems(obj.items()) 860 861 dispatch[dict] = save_dict /opt/conda/lib/python3.7/pickle.py in _batch_setitems(self, items) 883 for k, v in tmp: 884 save(k) --> 885 save(v) 886 write(SETITEMS) 887 elif n: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 522 reduce = getattr(obj, "__reduce_ex__", None) 523 if reduce is not None: --> 524 rv = reduce(self.proto) 525 else: 526 reduce = getattr(obj, "__reduce__", None) TypeError: can't pickle Tokenizer objects ``` Then I guess you need to give us more informations on your setup (OS, python, GPU, etc) or a Google Colab reproducing the error for us to be able to debug this error.
https://github.com/huggingface/datasets/issues/665
runing dataset.map, it raises TypeError: can't pickle Tokenizer objects
I have the same issue with `transformers/BertJapaneseTokenizer`. ```python # train_ds = Dataset(features: { # 'title': Value(dtype='string', id=None), # 'score': Value(dtype='float64', id=None) # }, num_rows: 99999) t = BertJapaneseTokenizer.from_pretrained('bert-base-japanese-whole-word-masking') encoded = train_ds.map(lambda examples: {'tokens': t.encode(examples['title'])}, batched=True) ``` <details><summary>Error Message</summary> ``` --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-35-2b7d66b291c1> in <module> 2 3 encoded = train_ds.map(lambda examples: ----> 4 {'tokens': t.encode(examples['title'])}, batched=True) /usr/local/lib/python3.6/site-packages/datasets/arrow_dataset.py in map(self, function, with_indices, input_columns, batched, batch_size, drop_last_batch, remove_columns, keep_in_memory, load_from_cache_file, cache_file_name, writer_batch_size, features, disable_nullable, fn_kwargs, num_proc, suffix_template, new_fingerprint) 1242 fn_kwargs=fn_kwargs, 1243 new_fingerprint=new_fingerprint, -> 1244 update_data=update_data, 1245 ) 1246 else: /usr/local/lib/python3.6/site-packages/datasets/arrow_dataset.py in wrapper(*args, **kwargs) 151 "output_all_columns": self._output_all_columns, 152 } --> 153 out: Union["Dataset", "DatasetDict"] = func(self, *args, **kwargs) 154 if new_format["columns"] is not None: 155 new_format["columns"] = list(set(new_format["columns"]) & set(out.column_names)) /usr/local/lib/python3.6/site-packages/datasets/fingerprint.py in wrapper(*args, **kwargs) 156 kwargs_for_fingerprint["fingerprint_name"] = fingerprint_name 157 kwargs[fingerprint_name] = update_fingerprint( --> 158 self._fingerprint, transform, kwargs_for_fingerprint 159 ) 160 /usr/local/lib/python3.6/site-packages/datasets/fingerprint.py in update_fingerprint(fingerprint, transform, transform_args) 103 for key in sorted(transform_args): 104 hasher.update(key) --> 105 hasher.update(transform_args[key]) 106 return hasher.hexdigest() 107 /usr/local/lib/python3.6/site-packages/datasets/fingerprint.py in update(self, value) 55 def update(self, value): 56 self.m.update(f"=={type(value)}==".encode("utf8")) ---> 57 self.m.update(self.hash(value).encode("utf-8")) 58 59 def hexdigest(self): /usr/local/lib/python3.6/site-packages/datasets/fingerprint.py in hash(cls, value) 51 return cls.dispatch[type(value)](cls, value) 52 else: ---> 53 return cls.hash_default(value) 54 55 def update(self, value): /usr/local/lib/python3.6/site-packages/datasets/fingerprint.py in hash_default(cls, value) 44 @classmethod 45 def hash_default(cls, value): ---> 46 return cls.hash_bytes(dumps(value)) 47 48 @classmethod /usr/local/lib/python3.6/site-packages/datasets/utils/py_utils.py in dumps(obj) 365 file = StringIO() 366 with _no_cache_fields(obj): --> 367 dump(obj, file) 368 return file.getvalue() 369 /usr/local/lib/python3.6/site-packages/datasets/utils/py_utils.py in dump(obj, file) 337 def dump(obj, file): 338 """pickle an object to a file""" --> 339 Pickler(file, recurse=True).dump(obj) 340 return 341 /usr/local/lib/python3.6/site-packages/dill/_dill.py in dump(self, obj) 444 raise PicklingError(msg) 445 else: --> 446 StockPickler.dump(self, obj) 447 stack.clear() # clear record of 'recursion-sensitive' pickled objects 448 return /usr/local/lib/python3.6/pickle.py in dump(self, obj) 407 if self.proto >= 4: 408 self.framer.start_framing() --> 409 self.save(obj) 410 self.write(STOP) 411 self.framer.end_framing() /usr/local/lib/python3.6/pickle.py in save(self, obj, save_persistent_id) 474 f = self.dispatch.get(t) 475 if f is not None: --> 476 f(self, obj) # Call unbound method with explicit self 477 return 478 /usr/local/lib/python3.6/site-packages/dill/_dill.py in save_function(pickler, obj) 1436 globs, obj.__name__, 1437 obj.__defaults__, obj.__closure__, -> 1438 obj.__dict__, fkwdefaults), obj=obj) 1439 else: 1440 _super = ('super' in getattr(obj.func_code,'co_names',())) and (_byref is not None) and getattr(pickler, '_recurse', False) /usr/local/lib/python3.6/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 608 else: 609 save(func) --> 610 save(args) 611 write(REDUCE) 612 /usr/local/lib/python3.6/pickle.py in save(self, obj, save_persistent_id) 474 f = self.dispatch.get(t) 475 if f is not None: --> 476 f(self, obj) # Call unbound method with explicit self 477 return 478 /usr/local/lib/python3.6/pickle.py in save_tuple(self, obj) 749 write(MARK) 750 for element in obj: --> 751 save(element) 752 753 if id(obj) in memo: /usr/local/lib/python3.6/pickle.py in save(self, obj, save_persistent_id) 474 f = self.dispatch.get(t) 475 if f is not None: --> 476 f(self, obj) # Call unbound method with explicit self 477 return 478 /usr/local/lib/python3.6/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /usr/local/lib/python3.6/pickle.py in save_dict(self, obj) 819 820 self.memoize(obj) --> 821 self._batch_setitems(obj.items()) 822 823 dispatch[dict] = save_dict /usr/local/lib/python3.6/pickle.py in _batch_setitems(self, items) 850 k, v = tmp[0] 851 save(k) --> 852 save(v) 853 write(SETITEM) 854 # else tmp is empty, and we're done /usr/local/lib/python3.6/pickle.py in save(self, obj, save_persistent_id) 519 520 # Save the reduce() output and finally memoize the object --> 521 self.save_reduce(obj=obj, *rv) 522 523 def persistent_id(self, obj): /usr/local/lib/python3.6/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 632 633 if state is not None: --> 634 save(state) 635 write(BUILD) 636 /usr/local/lib/python3.6/pickle.py in save(self, obj, save_persistent_id) 474 f = self.dispatch.get(t) 475 if f is not None: --> 476 f(self, obj) # Call unbound method with explicit self 477 return 478 /usr/local/lib/python3.6/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /usr/local/lib/python3.6/pickle.py in save_dict(self, obj) 819 820 self.memoize(obj) --> 821 self._batch_setitems(obj.items()) 822 823 dispatch[dict] = save_dict /usr/local/lib/python3.6/pickle.py in _batch_setitems(self, items) 845 for k, v in tmp: 846 save(k) --> 847 save(v) 848 write(SETITEMS) 849 elif n: /usr/local/lib/python3.6/pickle.py in save(self, obj, save_persistent_id) 519 520 # Save the reduce() output and finally memoize the object --> 521 self.save_reduce(obj=obj, *rv) 522 523 def persistent_id(self, obj): /usr/local/lib/python3.6/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 632 633 if state is not None: --> 634 save(state) 635 write(BUILD) 636 /usr/local/lib/python3.6/pickle.py in save(self, obj, save_persistent_id) 474 f = self.dispatch.get(t) 475 if f is not None: --> 476 f(self, obj) # Call unbound method with explicit self 477 return 478 /usr/local/lib/python3.6/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /usr/local/lib/python3.6/pickle.py in save_dict(self, obj) 819 820 self.memoize(obj) --> 821 self._batch_setitems(obj.items()) 822 823 dispatch[dict] = save_dict /usr/local/lib/python3.6/pickle.py in _batch_setitems(self, items) 845 for k, v in tmp: 846 save(k) --> 847 save(v) 848 write(SETITEMS) 849 elif n: /usr/local/lib/python3.6/pickle.py in save(self, obj, save_persistent_id) 494 reduce = getattr(obj, "__reduce_ex__", None) 495 if reduce is not None: --> 496 rv = reduce(self.proto) 497 else: 498 reduce = getattr(obj, "__reduce__", None) TypeError: can't pickle Tagger objects ``` </details> trainsformers: 2.10.0 datasets: 1.0.2 dill: 0.3.2 python: 3.6.8 OS: ubuntu 16.04 (Docker Image) on [Deep Learning VM](https://console.cloud.google.com/marketplace/details/click-to-deploy-images/deeplearning) (GCP) GPU: Tesla P100 (CUDA 10)
I load squad dataset. Then want to process data use following function with `Huggingface Transformers LongformerTokenizer`. ``` def convert_to_features(example): # Tokenize contexts and questions (as pairs of inputs) input_pairs = [example['question'], example['context']] encodings = tokenizer.encode_plus(input_pairs, pad_to_max_length=True, max_length=512) context_encodings = tokenizer.encode_plus(example['context']) # Compute start and end tokens for labels using Transformers's fast tokenizers alignement methodes. # this will give us the position of answer span in the context text start_idx, end_idx = get_correct_alignement(example['context'], example['answers']) start_positions_context = context_encodings.char_to_token(start_idx) end_positions_context = context_encodings.char_to_token(end_idx-1) # here we will compute the start and end position of the answer in the whole example # as the example is encoded like this <s> question</s></s> context</s> # and we know the postion of the answer in the context # we can just find out the index of the sep token and then add that to position + 1 (+1 because there are two sep tokens) # this will give us the position of the answer span in whole example sep_idx = encodings['input_ids'].index(tokenizer.sep_token_id) start_positions = start_positions_context + sep_idx + 1 end_positions = end_positions_context + sep_idx + 1 if end_positions > 512: start_positions, end_positions = 0, 0 encodings.update({'start_positions': start_positions, 'end_positions': end_positions, 'attention_mask': encodings['attention_mask']}) return encodings ``` Then I run `dataset.map(convert_to_features)`, it raise ``` In [59]: a.map(convert_to_features) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-59-c453b508761d> in <module> ----> 1 a.map(convert_to_features) /opt/conda/lib/python3.7/site-packages/datasets/arrow_dataset.py in map(self, function, with_indices, input_columns, batched, batch_size, drop_last_batch, remove_columns, keep_in_memory, load_from_cache_file, cache_file_name, writer_batch_size, features, disable_nullable, fn_kwargs, num_proc, suffix_template, new_fingerprint) 1242 fn_kwargs=fn_kwargs, 1243 new_fingerprint=new_fingerprint, -> 1244 update_data=update_data, 1245 ) 1246 else: /opt/conda/lib/python3.7/site-packages/datasets/arrow_dataset.py in wrapper(*args, **kwargs) 151 "output_all_columns": self._output_all_columns, 152 } --> 153 out: Union["Dataset", "DatasetDict"] = func(self, *args, **kwargs) 154 if new_format["columns"] is not None: 155 new_format["columns"] = list(set(new_format["columns"]) & set(out.column_names)) /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in wrapper(*args, **kwargs) 156 kwargs_for_fingerprint["fingerprint_name"] = fingerprint_name 157 kwargs[fingerprint_name] = update_fingerprint( --> 158 self._fingerprint, transform, kwargs_for_fingerprint 159 ) 160 /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in update_fingerprint(fingerprint, transform, transform_args) 103 for key in sorted(transform_args): 104 hasher.update(key) --> 105 hasher.update(transform_args[key]) 106 return hasher.hexdigest() 107 /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in update(self, value) 55 def update(self, value): 56 self.m.update(f"=={type(value)}==".encode("utf8")) ---> 57 self.m.update(self.hash(value).encode("utf-8")) 58 59 def hexdigest(self): /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in hash(cls, value) 51 return cls.dispatch[type(value)](cls, value) 52 else: ---> 53 return cls.hash_default(value) 54 55 def update(self, value): /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in hash_default(cls, value) 44 @classmethod 45 def hash_default(cls, value): ---> 46 return cls.hash_bytes(dumps(value)) 47 48 @classmethod /opt/conda/lib/python3.7/site-packages/datasets/utils/py_utils.py in dumps(obj) 365 file = StringIO() 366 with _no_cache_fields(obj): --> 367 dump(obj, file) 368 return file.getvalue() 369 /opt/conda/lib/python3.7/site-packages/datasets/utils/py_utils.py in dump(obj, file) 337 def dump(obj, file): 338 """pickle an object to a file""" --> 339 Pickler(file, recurse=True).dump(obj) 340 return 341 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in dump(self, obj) 444 raise PicklingError(msg) 445 else: --> 446 StockPickler.dump(self, obj) 447 stack.clear() # clear record of 'recursion-sensitive' pickled objects 448 return /opt/conda/lib/python3.7/pickle.py in dump(self, obj) 435 if self.proto >= 4: 436 self.framer.start_framing() --> 437 self.save(obj) 438 self.write(STOP) 439 self.framer.end_framing() /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_function(pickler, obj) 1436 globs, obj.__name__, 1437 obj.__defaults__, obj.__closure__, -> 1438 obj.__dict__, fkwdefaults), obj=obj) 1439 else: 1440 _super = ('super' in getattr(obj.func_code,'co_names',())) and (_byref is not None) and getattr(pickler, '_recurse', False) /opt/conda/lib/python3.7/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 636 else: 637 save(func) --> 638 save(args) 639 write(REDUCE) 640 /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/pickle.py in save_tuple(self, obj) 787 write(MARK) 788 for element in obj: --> 789 save(element) 790 791 if id(obj) in memo: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /opt/conda/lib/python3.7/pickle.py in save_dict(self, obj) 857 858 self.memoize(obj) --> 859 self._batch_setitems(obj.items()) 860 861 dispatch[dict] = save_dict /opt/conda/lib/python3.7/pickle.py in _batch_setitems(self, items) 883 for k, v in tmp: 884 save(k) --> 885 save(v) 886 write(SETITEMS) 887 elif n: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 547 548 # Save the reduce() output and finally memoize the object --> 549 self.save_reduce(obj=obj, *rv) 550 551 def persistent_id(self, obj): /opt/conda/lib/python3.7/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 660 661 if state is not None: --> 662 save(state) 663 write(BUILD) 664 /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /opt/conda/lib/python3.7/pickle.py in save_dict(self, obj) 857 858 self.memoize(obj) --> 859 self._batch_setitems(obj.items()) 860 861 dispatch[dict] = save_dict /opt/conda/lib/python3.7/pickle.py in _batch_setitems(self, items) 883 for k, v in tmp: 884 save(k) --> 885 save(v) 886 write(SETITEMS) 887 elif n: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 547 548 # Save the reduce() output and finally memoize the object --> 549 self.save_reduce(obj=obj, *rv) 550 551 def persistent_id(self, obj): /opt/conda/lib/python3.7/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 660 661 if state is not None: --> 662 save(state) 663 write(BUILD) 664 /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /opt/conda/lib/python3.7/pickle.py in save_dict(self, obj) 857 858 self.memoize(obj) --> 859 self._batch_setitems(obj.items()) 860 861 dispatch[dict] = save_dict /opt/conda/lib/python3.7/pickle.py in _batch_setitems(self, items) 883 for k, v in tmp: 884 save(k) --> 885 save(v) 886 write(SETITEMS) 887 elif n: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 522 reduce = getattr(obj, "__reduce_ex__", None) 523 if reduce is not None: --> 524 rv = reduce(self.proto) 525 else: 526 reduce = getattr(obj, "__reduce__", None) TypeError: can't pickle Tokenizer objects ```
861
runing dataset.map, it raises TypeError: can't pickle Tokenizer objects I load squad dataset. Then want to process data use following function with `Huggingface Transformers LongformerTokenizer`. ``` def convert_to_features(example): # Tokenize contexts and questions (as pairs of inputs) input_pairs = [example['question'], example['context']] encodings = tokenizer.encode_plus(input_pairs, pad_to_max_length=True, max_length=512) context_encodings = tokenizer.encode_plus(example['context']) # Compute start and end tokens for labels using Transformers's fast tokenizers alignement methodes. # this will give us the position of answer span in the context text start_idx, end_idx = get_correct_alignement(example['context'], example['answers']) start_positions_context = context_encodings.char_to_token(start_idx) end_positions_context = context_encodings.char_to_token(end_idx-1) # here we will compute the start and end position of the answer in the whole example # as the example is encoded like this <s> question</s></s> context</s> # and we know the postion of the answer in the context # we can just find out the index of the sep token and then add that to position + 1 (+1 because there are two sep tokens) # this will give us the position of the answer span in whole example sep_idx = encodings['input_ids'].index(tokenizer.sep_token_id) start_positions = start_positions_context + sep_idx + 1 end_positions = end_positions_context + sep_idx + 1 if end_positions > 512: start_positions, end_positions = 0, 0 encodings.update({'start_positions': start_positions, 'end_positions': end_positions, 'attention_mask': encodings['attention_mask']}) return encodings ``` Then I run `dataset.map(convert_to_features)`, it raise ``` In [59]: a.map(convert_to_features) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-59-c453b508761d> in <module> ----> 1 a.map(convert_to_features) /opt/conda/lib/python3.7/site-packages/datasets/arrow_dataset.py in map(self, function, with_indices, input_columns, batched, batch_size, drop_last_batch, remove_columns, keep_in_memory, load_from_cache_file, cache_file_name, writer_batch_size, features, disable_nullable, fn_kwargs, num_proc, suffix_template, new_fingerprint) 1242 fn_kwargs=fn_kwargs, 1243 new_fingerprint=new_fingerprint, -> 1244 update_data=update_data, 1245 ) 1246 else: /opt/conda/lib/python3.7/site-packages/datasets/arrow_dataset.py in wrapper(*args, **kwargs) 151 "output_all_columns": self._output_all_columns, 152 } --> 153 out: Union["Dataset", "DatasetDict"] = func(self, *args, **kwargs) 154 if new_format["columns"] is not None: 155 new_format["columns"] = list(set(new_format["columns"]) & set(out.column_names)) /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in wrapper(*args, **kwargs) 156 kwargs_for_fingerprint["fingerprint_name"] = fingerprint_name 157 kwargs[fingerprint_name] = update_fingerprint( --> 158 self._fingerprint, transform, kwargs_for_fingerprint 159 ) 160 /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in update_fingerprint(fingerprint, transform, transform_args) 103 for key in sorted(transform_args): 104 hasher.update(key) --> 105 hasher.update(transform_args[key]) 106 return hasher.hexdigest() 107 /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in update(self, value) 55 def update(self, value): 56 self.m.update(f"=={type(value)}==".encode("utf8")) ---> 57 self.m.update(self.hash(value).encode("utf-8")) 58 59 def hexdigest(self): /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in hash(cls, value) 51 return cls.dispatch[type(value)](cls, value) 52 else: ---> 53 return cls.hash_default(value) 54 55 def update(self, value): /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in hash_default(cls, value) 44 @classmethod 45 def hash_default(cls, value): ---> 46 return cls.hash_bytes(dumps(value)) 47 48 @classmethod /opt/conda/lib/python3.7/site-packages/datasets/utils/py_utils.py in dumps(obj) 365 file = StringIO() 366 with _no_cache_fields(obj): --> 367 dump(obj, file) 368 return file.getvalue() 369 /opt/conda/lib/python3.7/site-packages/datasets/utils/py_utils.py in dump(obj, file) 337 def dump(obj, file): 338 """pickle an object to a file""" --> 339 Pickler(file, recurse=True).dump(obj) 340 return 341 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in dump(self, obj) 444 raise PicklingError(msg) 445 else: --> 446 StockPickler.dump(self, obj) 447 stack.clear() # clear record of 'recursion-sensitive' pickled objects 448 return /opt/conda/lib/python3.7/pickle.py in dump(self, obj) 435 if self.proto >= 4: 436 self.framer.start_framing() --> 437 self.save(obj) 438 self.write(STOP) 439 self.framer.end_framing() /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_function(pickler, obj) 1436 globs, obj.__name__, 1437 obj.__defaults__, obj.__closure__, -> 1438 obj.__dict__, fkwdefaults), obj=obj) 1439 else: 1440 _super = ('super' in getattr(obj.func_code,'co_names',())) and (_byref is not None) and getattr(pickler, '_recurse', False) /opt/conda/lib/python3.7/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 636 else: 637 save(func) --> 638 save(args) 639 write(REDUCE) 640 /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/pickle.py in save_tuple(self, obj) 787 write(MARK) 788 for element in obj: --> 789 save(element) 790 791 if id(obj) in memo: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /opt/conda/lib/python3.7/pickle.py in save_dict(self, obj) 857 858 self.memoize(obj) --> 859 self._batch_setitems(obj.items()) 860 861 dispatch[dict] = save_dict /opt/conda/lib/python3.7/pickle.py in _batch_setitems(self, items) 883 for k, v in tmp: 884 save(k) --> 885 save(v) 886 write(SETITEMS) 887 elif n: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 547 548 # Save the reduce() output and finally memoize the object --> 549 self.save_reduce(obj=obj, *rv) 550 551 def persistent_id(self, obj): /opt/conda/lib/python3.7/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 660 661 if state is not None: --> 662 save(state) 663 write(BUILD) 664 /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /opt/conda/lib/python3.7/pickle.py in save_dict(self, obj) 857 858 self.memoize(obj) --> 859 self._batch_setitems(obj.items()) 860 861 dispatch[dict] = save_dict /opt/conda/lib/python3.7/pickle.py in _batch_setitems(self, items) 883 for k, v in tmp: 884 save(k) --> 885 save(v) 886 write(SETITEMS) 887 elif n: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 547 548 # Save the reduce() output and finally memoize the object --> 549 self.save_reduce(obj=obj, *rv) 550 551 def persistent_id(self, obj): /opt/conda/lib/python3.7/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 660 661 if state is not None: --> 662 save(state) 663 write(BUILD) 664 /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /opt/conda/lib/python3.7/pickle.py in save_dict(self, obj) 857 858 self.memoize(obj) --> 859 self._batch_setitems(obj.items()) 860 861 dispatch[dict] = save_dict /opt/conda/lib/python3.7/pickle.py in _batch_setitems(self, items) 883 for k, v in tmp: 884 save(k) --> 885 save(v) 886 write(SETITEMS) 887 elif n: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 522 reduce = getattr(obj, "__reduce_ex__", None) 523 if reduce is not None: --> 524 rv = reduce(self.proto) 525 else: 526 reduce = getattr(obj, "__reduce__", None) TypeError: can't pickle Tokenizer objects ``` I have the same issue with `transformers/BertJapaneseTokenizer`. ```python # train_ds = Dataset(features: { # 'title': Value(dtype='string', id=None), # 'score': Value(dtype='float64', id=None) # }, num_rows: 99999) t = BertJapaneseTokenizer.from_pretrained('bert-base-japanese-whole-word-masking') encoded = train_ds.map(lambda examples: {'tokens': t.encode(examples['title'])}, batched=True) ``` <details><summary>Error Message</summary> ``` --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-35-2b7d66b291c1> in <module> 2 3 encoded = train_ds.map(lambda examples: ----> 4 {'tokens': t.encode(examples['title'])}, batched=True) /usr/local/lib/python3.6/site-packages/datasets/arrow_dataset.py in map(self, function, with_indices, input_columns, batched, batch_size, drop_last_batch, remove_columns, keep_in_memory, load_from_cache_file, cache_file_name, writer_batch_size, features, disable_nullable, fn_kwargs, num_proc, suffix_template, new_fingerprint) 1242 fn_kwargs=fn_kwargs, 1243 new_fingerprint=new_fingerprint, -> 1244 update_data=update_data, 1245 ) 1246 else: /usr/local/lib/python3.6/site-packages/datasets/arrow_dataset.py in wrapper(*args, **kwargs) 151 "output_all_columns": self._output_all_columns, 152 } --> 153 out: Union["Dataset", "DatasetDict"] = func(self, *args, **kwargs) 154 if new_format["columns"] is not None: 155 new_format["columns"] = list(set(new_format["columns"]) & set(out.column_names)) /usr/local/lib/python3.6/site-packages/datasets/fingerprint.py in wrapper(*args, **kwargs) 156 kwargs_for_fingerprint["fingerprint_name"] = fingerprint_name 157 kwargs[fingerprint_name] = update_fingerprint( --> 158 self._fingerprint, transform, kwargs_for_fingerprint 159 ) 160 /usr/local/lib/python3.6/site-packages/datasets/fingerprint.py in update_fingerprint(fingerprint, transform, transform_args) 103 for key in sorted(transform_args): 104 hasher.update(key) --> 105 hasher.update(transform_args[key]) 106 return hasher.hexdigest() 107 /usr/local/lib/python3.6/site-packages/datasets/fingerprint.py in update(self, value) 55 def update(self, value): 56 self.m.update(f"=={type(value)}==".encode("utf8")) ---> 57 self.m.update(self.hash(value).encode("utf-8")) 58 59 def hexdigest(self): /usr/local/lib/python3.6/site-packages/datasets/fingerprint.py in hash(cls, value) 51 return cls.dispatch[type(value)](cls, value) 52 else: ---> 53 return cls.hash_default(value) 54 55 def update(self, value): /usr/local/lib/python3.6/site-packages/datasets/fingerprint.py in hash_default(cls, value) 44 @classmethod 45 def hash_default(cls, value): ---> 46 return cls.hash_bytes(dumps(value)) 47 48 @classmethod /usr/local/lib/python3.6/site-packages/datasets/utils/py_utils.py in dumps(obj) 365 file = StringIO() 366 with _no_cache_fields(obj): --> 367 dump(obj, file) 368 return file.getvalue() 369 /usr/local/lib/python3.6/site-packages/datasets/utils/py_utils.py in dump(obj, file) 337 def dump(obj, file): 338 """pickle an object to a file""" --> 339 Pickler(file, recurse=True).dump(obj) 340 return 341 /usr/local/lib/python3.6/site-packages/dill/_dill.py in dump(self, obj) 444 raise PicklingError(msg) 445 else: --> 446 StockPickler.dump(self, obj) 447 stack.clear() # clear record of 'recursion-sensitive' pickled objects 448 return /usr/local/lib/python3.6/pickle.py in dump(self, obj) 407 if self.proto >= 4: 408 self.framer.start_framing() --> 409 self.save(obj) 410 self.write(STOP) 411 self.framer.end_framing() /usr/local/lib/python3.6/pickle.py in save(self, obj, save_persistent_id) 474 f = self.dispatch.get(t) 475 if f is not None: --> 476 f(self, obj) # Call unbound method with explicit self 477 return 478 /usr/local/lib/python3.6/site-packages/dill/_dill.py in save_function(pickler, obj) 1436 globs, obj.__name__, 1437 obj.__defaults__, obj.__closure__, -> 1438 obj.__dict__, fkwdefaults), obj=obj) 1439 else: 1440 _super = ('super' in getattr(obj.func_code,'co_names',())) and (_byref is not None) and getattr(pickler, '_recurse', False) /usr/local/lib/python3.6/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 608 else: 609 save(func) --> 610 save(args) 611 write(REDUCE) 612 /usr/local/lib/python3.6/pickle.py in save(self, obj, save_persistent_id) 474 f = self.dispatch.get(t) 475 if f is not None: --> 476 f(self, obj) # Call unbound method with explicit self 477 return 478 /usr/local/lib/python3.6/pickle.py in save_tuple(self, obj) 749 write(MARK) 750 for element in obj: --> 751 save(element) 752 753 if id(obj) in memo: /usr/local/lib/python3.6/pickle.py in save(self, obj, save_persistent_id) 474 f = self.dispatch.get(t) 475 if f is not None: --> 476 f(self, obj) # Call unbound method with explicit self 477 return 478 /usr/local/lib/python3.6/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /usr/local/lib/python3.6/pickle.py in save_dict(self, obj) 819 820 self.memoize(obj) --> 821 self._batch_setitems(obj.items()) 822 823 dispatch[dict] = save_dict /usr/local/lib/python3.6/pickle.py in _batch_setitems(self, items) 850 k, v = tmp[0] 851 save(k) --> 852 save(v) 853 write(SETITEM) 854 # else tmp is empty, and we're done /usr/local/lib/python3.6/pickle.py in save(self, obj, save_persistent_id) 519 520 # Save the reduce() output and finally memoize the object --> 521 self.save_reduce(obj=obj, *rv) 522 523 def persistent_id(self, obj): /usr/local/lib/python3.6/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 632 633 if state is not None: --> 634 save(state) 635 write(BUILD) 636 /usr/local/lib/python3.6/pickle.py in save(self, obj, save_persistent_id) 474 f = self.dispatch.get(t) 475 if f is not None: --> 476 f(self, obj) # Call unbound method with explicit self 477 return 478 /usr/local/lib/python3.6/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /usr/local/lib/python3.6/pickle.py in save_dict(self, obj) 819 820 self.memoize(obj) --> 821 self._batch_setitems(obj.items()) 822 823 dispatch[dict] = save_dict /usr/local/lib/python3.6/pickle.py in _batch_setitems(self, items) 845 for k, v in tmp: 846 save(k) --> 847 save(v) 848 write(SETITEMS) 849 elif n: /usr/local/lib/python3.6/pickle.py in save(self, obj, save_persistent_id) 519 520 # Save the reduce() output and finally memoize the object --> 521 self.save_reduce(obj=obj, *rv) 522 523 def persistent_id(self, obj): /usr/local/lib/python3.6/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 632 633 if state is not None: --> 634 save(state) 635 write(BUILD) 636 /usr/local/lib/python3.6/pickle.py in save(self, obj, save_persistent_id) 474 f = self.dispatch.get(t) 475 if f is not None: --> 476 f(self, obj) # Call unbound method with explicit self 477 return 478 /usr/local/lib/python3.6/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /usr/local/lib/python3.6/pickle.py in save_dict(self, obj) 819 820 self.memoize(obj) --> 821 self._batch_setitems(obj.items()) 822 823 dispatch[dict] = save_dict /usr/local/lib/python3.6/pickle.py in _batch_setitems(self, items) 845 for k, v in tmp: 846 save(k) --> 847 save(v) 848 write(SETITEMS) 849 elif n: /usr/local/lib/python3.6/pickle.py in save(self, obj, save_persistent_id) 494 reduce = getattr(obj, "__reduce_ex__", None) 495 if reduce is not None: --> 496 rv = reduce(self.proto) 497 else: 498 reduce = getattr(obj, "__reduce__", None) TypeError: can't pickle Tagger objects ``` </details> trainsformers: 2.10.0 datasets: 1.0.2 dill: 0.3.2 python: 3.6.8 OS: ubuntu 16.04 (Docker Image) on [Deep Learning VM](https://console.cloud.google.com/marketplace/details/click-to-deploy-images/deeplearning) (GCP) GPU: Tesla P100 (CUDA 10)
https://github.com/huggingface/datasets/issues/665
runing dataset.map, it raises TypeError: can't pickle Tokenizer objects
> I have the same issue with `transformers/BertJapaneseTokenizer`. It looks like it this tokenizer is not supported unfortunately. This is because `t.word_tokenizer.mecab` is a `fugashi.fugashi.GenericTagger` which is not compatible with pickle nor dill. We need objects passes to `map` to be picklable for our caching system to work properly. Here it crashes because the caching system is not able to pickle the GenericTagger. \> Maybe you can create an issue on [fugashi](https://github.com/polm/fugashi/issues) 's repo and ask to make `fugashi.fugashi.GenericTagger` compatible with pickle ? What you can do in the meantime is use a picklable wrapper of the tokenizer: ```python from transformers import BertJapaneseTokenizer, MecabTokenizer class PicklableTokenizer(BertJapaneseTokenizer): def __getstate__(self): state = dict(self.__dict__) state["do_lower_case"] = self.word_tokenizer.do_lower_case state["never_split"] = self.word_tokenizer.never_split del state["word_tokenizer"] return state def __setstate__(self, state): do_lower_case = state.pop("do_lower_case") never_split = state.pop("never_split") self.__dict__ = state self.word_tokenizer = MecabTokenizer( do_lower_case=do_lower_case, never_split=never_split) ) t = PicklableTokenizer.from_pretrained("cl-tohoku/bert-base-japanese-whole-word-masking") encoded = train_ds.map(lambda examples: {'tokens': t.encode(examples['title'])}, batched=True) # it works ```
I load squad dataset. Then want to process data use following function with `Huggingface Transformers LongformerTokenizer`. ``` def convert_to_features(example): # Tokenize contexts and questions (as pairs of inputs) input_pairs = [example['question'], example['context']] encodings = tokenizer.encode_plus(input_pairs, pad_to_max_length=True, max_length=512) context_encodings = tokenizer.encode_plus(example['context']) # Compute start and end tokens for labels using Transformers's fast tokenizers alignement methodes. # this will give us the position of answer span in the context text start_idx, end_idx = get_correct_alignement(example['context'], example['answers']) start_positions_context = context_encodings.char_to_token(start_idx) end_positions_context = context_encodings.char_to_token(end_idx-1) # here we will compute the start and end position of the answer in the whole example # as the example is encoded like this <s> question</s></s> context</s> # and we know the postion of the answer in the context # we can just find out the index of the sep token and then add that to position + 1 (+1 because there are two sep tokens) # this will give us the position of the answer span in whole example sep_idx = encodings['input_ids'].index(tokenizer.sep_token_id) start_positions = start_positions_context + sep_idx + 1 end_positions = end_positions_context + sep_idx + 1 if end_positions > 512: start_positions, end_positions = 0, 0 encodings.update({'start_positions': start_positions, 'end_positions': end_positions, 'attention_mask': encodings['attention_mask']}) return encodings ``` Then I run `dataset.map(convert_to_features)`, it raise ``` In [59]: a.map(convert_to_features) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-59-c453b508761d> in <module> ----> 1 a.map(convert_to_features) /opt/conda/lib/python3.7/site-packages/datasets/arrow_dataset.py in map(self, function, with_indices, input_columns, batched, batch_size, drop_last_batch, remove_columns, keep_in_memory, load_from_cache_file, cache_file_name, writer_batch_size, features, disable_nullable, fn_kwargs, num_proc, suffix_template, new_fingerprint) 1242 fn_kwargs=fn_kwargs, 1243 new_fingerprint=new_fingerprint, -> 1244 update_data=update_data, 1245 ) 1246 else: /opt/conda/lib/python3.7/site-packages/datasets/arrow_dataset.py in wrapper(*args, **kwargs) 151 "output_all_columns": self._output_all_columns, 152 } --> 153 out: Union["Dataset", "DatasetDict"] = func(self, *args, **kwargs) 154 if new_format["columns"] is not None: 155 new_format["columns"] = list(set(new_format["columns"]) & set(out.column_names)) /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in wrapper(*args, **kwargs) 156 kwargs_for_fingerprint["fingerprint_name"] = fingerprint_name 157 kwargs[fingerprint_name] = update_fingerprint( --> 158 self._fingerprint, transform, kwargs_for_fingerprint 159 ) 160 /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in update_fingerprint(fingerprint, transform, transform_args) 103 for key in sorted(transform_args): 104 hasher.update(key) --> 105 hasher.update(transform_args[key]) 106 return hasher.hexdigest() 107 /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in update(self, value) 55 def update(self, value): 56 self.m.update(f"=={type(value)}==".encode("utf8")) ---> 57 self.m.update(self.hash(value).encode("utf-8")) 58 59 def hexdigest(self): /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in hash(cls, value) 51 return cls.dispatch[type(value)](cls, value) 52 else: ---> 53 return cls.hash_default(value) 54 55 def update(self, value): /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in hash_default(cls, value) 44 @classmethod 45 def hash_default(cls, value): ---> 46 return cls.hash_bytes(dumps(value)) 47 48 @classmethod /opt/conda/lib/python3.7/site-packages/datasets/utils/py_utils.py in dumps(obj) 365 file = StringIO() 366 with _no_cache_fields(obj): --> 367 dump(obj, file) 368 return file.getvalue() 369 /opt/conda/lib/python3.7/site-packages/datasets/utils/py_utils.py in dump(obj, file) 337 def dump(obj, file): 338 """pickle an object to a file""" --> 339 Pickler(file, recurse=True).dump(obj) 340 return 341 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in dump(self, obj) 444 raise PicklingError(msg) 445 else: --> 446 StockPickler.dump(self, obj) 447 stack.clear() # clear record of 'recursion-sensitive' pickled objects 448 return /opt/conda/lib/python3.7/pickle.py in dump(self, obj) 435 if self.proto >= 4: 436 self.framer.start_framing() --> 437 self.save(obj) 438 self.write(STOP) 439 self.framer.end_framing() /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_function(pickler, obj) 1436 globs, obj.__name__, 1437 obj.__defaults__, obj.__closure__, -> 1438 obj.__dict__, fkwdefaults), obj=obj) 1439 else: 1440 _super = ('super' in getattr(obj.func_code,'co_names',())) and (_byref is not None) and getattr(pickler, '_recurse', False) /opt/conda/lib/python3.7/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 636 else: 637 save(func) --> 638 save(args) 639 write(REDUCE) 640 /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/pickle.py in save_tuple(self, obj) 787 write(MARK) 788 for element in obj: --> 789 save(element) 790 791 if id(obj) in memo: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /opt/conda/lib/python3.7/pickle.py in save_dict(self, obj) 857 858 self.memoize(obj) --> 859 self._batch_setitems(obj.items()) 860 861 dispatch[dict] = save_dict /opt/conda/lib/python3.7/pickle.py in _batch_setitems(self, items) 883 for k, v in tmp: 884 save(k) --> 885 save(v) 886 write(SETITEMS) 887 elif n: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 547 548 # Save the reduce() output and finally memoize the object --> 549 self.save_reduce(obj=obj, *rv) 550 551 def persistent_id(self, obj): /opt/conda/lib/python3.7/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 660 661 if state is not None: --> 662 save(state) 663 write(BUILD) 664 /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /opt/conda/lib/python3.7/pickle.py in save_dict(self, obj) 857 858 self.memoize(obj) --> 859 self._batch_setitems(obj.items()) 860 861 dispatch[dict] = save_dict /opt/conda/lib/python3.7/pickle.py in _batch_setitems(self, items) 883 for k, v in tmp: 884 save(k) --> 885 save(v) 886 write(SETITEMS) 887 elif n: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 547 548 # Save the reduce() output and finally memoize the object --> 549 self.save_reduce(obj=obj, *rv) 550 551 def persistent_id(self, obj): /opt/conda/lib/python3.7/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 660 661 if state is not None: --> 662 save(state) 663 write(BUILD) 664 /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /opt/conda/lib/python3.7/pickle.py in save_dict(self, obj) 857 858 self.memoize(obj) --> 859 self._batch_setitems(obj.items()) 860 861 dispatch[dict] = save_dict /opt/conda/lib/python3.7/pickle.py in _batch_setitems(self, items) 883 for k, v in tmp: 884 save(k) --> 885 save(v) 886 write(SETITEMS) 887 elif n: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 522 reduce = getattr(obj, "__reduce_ex__", None) 523 if reduce is not None: --> 524 rv = reduce(self.proto) 525 else: 526 reduce = getattr(obj, "__reduce__", None) TypeError: can't pickle Tokenizer objects ```
153
runing dataset.map, it raises TypeError: can't pickle Tokenizer objects I load squad dataset. Then want to process data use following function with `Huggingface Transformers LongformerTokenizer`. ``` def convert_to_features(example): # Tokenize contexts and questions (as pairs of inputs) input_pairs = [example['question'], example['context']] encodings = tokenizer.encode_plus(input_pairs, pad_to_max_length=True, max_length=512) context_encodings = tokenizer.encode_plus(example['context']) # Compute start and end tokens for labels using Transformers's fast tokenizers alignement methodes. # this will give us the position of answer span in the context text start_idx, end_idx = get_correct_alignement(example['context'], example['answers']) start_positions_context = context_encodings.char_to_token(start_idx) end_positions_context = context_encodings.char_to_token(end_idx-1) # here we will compute the start and end position of the answer in the whole example # as the example is encoded like this <s> question</s></s> context</s> # and we know the postion of the answer in the context # we can just find out the index of the sep token and then add that to position + 1 (+1 because there are two sep tokens) # this will give us the position of the answer span in whole example sep_idx = encodings['input_ids'].index(tokenizer.sep_token_id) start_positions = start_positions_context + sep_idx + 1 end_positions = end_positions_context + sep_idx + 1 if end_positions > 512: start_positions, end_positions = 0, 0 encodings.update({'start_positions': start_positions, 'end_positions': end_positions, 'attention_mask': encodings['attention_mask']}) return encodings ``` Then I run `dataset.map(convert_to_features)`, it raise ``` In [59]: a.map(convert_to_features) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-59-c453b508761d> in <module> ----> 1 a.map(convert_to_features) /opt/conda/lib/python3.7/site-packages/datasets/arrow_dataset.py in map(self, function, with_indices, input_columns, batched, batch_size, drop_last_batch, remove_columns, keep_in_memory, load_from_cache_file, cache_file_name, writer_batch_size, features, disable_nullable, fn_kwargs, num_proc, suffix_template, new_fingerprint) 1242 fn_kwargs=fn_kwargs, 1243 new_fingerprint=new_fingerprint, -> 1244 update_data=update_data, 1245 ) 1246 else: /opt/conda/lib/python3.7/site-packages/datasets/arrow_dataset.py in wrapper(*args, **kwargs) 151 "output_all_columns": self._output_all_columns, 152 } --> 153 out: Union["Dataset", "DatasetDict"] = func(self, *args, **kwargs) 154 if new_format["columns"] is not None: 155 new_format["columns"] = list(set(new_format["columns"]) & set(out.column_names)) /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in wrapper(*args, **kwargs) 156 kwargs_for_fingerprint["fingerprint_name"] = fingerprint_name 157 kwargs[fingerprint_name] = update_fingerprint( --> 158 self._fingerprint, transform, kwargs_for_fingerprint 159 ) 160 /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in update_fingerprint(fingerprint, transform, transform_args) 103 for key in sorted(transform_args): 104 hasher.update(key) --> 105 hasher.update(transform_args[key]) 106 return hasher.hexdigest() 107 /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in update(self, value) 55 def update(self, value): 56 self.m.update(f"=={type(value)}==".encode("utf8")) ---> 57 self.m.update(self.hash(value).encode("utf-8")) 58 59 def hexdigest(self): /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in hash(cls, value) 51 return cls.dispatch[type(value)](cls, value) 52 else: ---> 53 return cls.hash_default(value) 54 55 def update(self, value): /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in hash_default(cls, value) 44 @classmethod 45 def hash_default(cls, value): ---> 46 return cls.hash_bytes(dumps(value)) 47 48 @classmethod /opt/conda/lib/python3.7/site-packages/datasets/utils/py_utils.py in dumps(obj) 365 file = StringIO() 366 with _no_cache_fields(obj): --> 367 dump(obj, file) 368 return file.getvalue() 369 /opt/conda/lib/python3.7/site-packages/datasets/utils/py_utils.py in dump(obj, file) 337 def dump(obj, file): 338 """pickle an object to a file""" --> 339 Pickler(file, recurse=True).dump(obj) 340 return 341 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in dump(self, obj) 444 raise PicklingError(msg) 445 else: --> 446 StockPickler.dump(self, obj) 447 stack.clear() # clear record of 'recursion-sensitive' pickled objects 448 return /opt/conda/lib/python3.7/pickle.py in dump(self, obj) 435 if self.proto >= 4: 436 self.framer.start_framing() --> 437 self.save(obj) 438 self.write(STOP) 439 self.framer.end_framing() /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_function(pickler, obj) 1436 globs, obj.__name__, 1437 obj.__defaults__, obj.__closure__, -> 1438 obj.__dict__, fkwdefaults), obj=obj) 1439 else: 1440 _super = ('super' in getattr(obj.func_code,'co_names',())) and (_byref is not None) and getattr(pickler, '_recurse', False) /opt/conda/lib/python3.7/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 636 else: 637 save(func) --> 638 save(args) 639 write(REDUCE) 640 /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/pickle.py in save_tuple(self, obj) 787 write(MARK) 788 for element in obj: --> 789 save(element) 790 791 if id(obj) in memo: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /opt/conda/lib/python3.7/pickle.py in save_dict(self, obj) 857 858 self.memoize(obj) --> 859 self._batch_setitems(obj.items()) 860 861 dispatch[dict] = save_dict /opt/conda/lib/python3.7/pickle.py in _batch_setitems(self, items) 883 for k, v in tmp: 884 save(k) --> 885 save(v) 886 write(SETITEMS) 887 elif n: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 547 548 # Save the reduce() output and finally memoize the object --> 549 self.save_reduce(obj=obj, *rv) 550 551 def persistent_id(self, obj): /opt/conda/lib/python3.7/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 660 661 if state is not None: --> 662 save(state) 663 write(BUILD) 664 /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /opt/conda/lib/python3.7/pickle.py in save_dict(self, obj) 857 858 self.memoize(obj) --> 859 self._batch_setitems(obj.items()) 860 861 dispatch[dict] = save_dict /opt/conda/lib/python3.7/pickle.py in _batch_setitems(self, items) 883 for k, v in tmp: 884 save(k) --> 885 save(v) 886 write(SETITEMS) 887 elif n: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 547 548 # Save the reduce() output and finally memoize the object --> 549 self.save_reduce(obj=obj, *rv) 550 551 def persistent_id(self, obj): /opt/conda/lib/python3.7/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 660 661 if state is not None: --> 662 save(state) 663 write(BUILD) 664 /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /opt/conda/lib/python3.7/pickle.py in save_dict(self, obj) 857 858 self.memoize(obj) --> 859 self._batch_setitems(obj.items()) 860 861 dispatch[dict] = save_dict /opt/conda/lib/python3.7/pickle.py in _batch_setitems(self, items) 883 for k, v in tmp: 884 save(k) --> 885 save(v) 886 write(SETITEMS) 887 elif n: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 522 reduce = getattr(obj, "__reduce_ex__", None) 523 if reduce is not None: --> 524 rv = reduce(self.proto) 525 else: 526 reduce = getattr(obj, "__reduce__", None) TypeError: can't pickle Tokenizer objects ``` > I have the same issue with `transformers/BertJapaneseTokenizer`. It looks like it this tokenizer is not supported unfortunately. This is because `t.word_tokenizer.mecab` is a `fugashi.fugashi.GenericTagger` which is not compatible with pickle nor dill. We need objects passes to `map` to be picklable for our caching system to work properly. Here it crashes because the caching system is not able to pickle the GenericTagger. \> Maybe you can create an issue on [fugashi](https://github.com/polm/fugashi/issues) 's repo and ask to make `fugashi.fugashi.GenericTagger` compatible with pickle ? What you can do in the meantime is use a picklable wrapper of the tokenizer: ```python from transformers import BertJapaneseTokenizer, MecabTokenizer class PicklableTokenizer(BertJapaneseTokenizer): def __getstate__(self): state = dict(self.__dict__) state["do_lower_case"] = self.word_tokenizer.do_lower_case state["never_split"] = self.word_tokenizer.never_split del state["word_tokenizer"] return state def __setstate__(self, state): do_lower_case = state.pop("do_lower_case") never_split = state.pop("never_split") self.__dict__ = state self.word_tokenizer = MecabTokenizer( do_lower_case=do_lower_case, never_split=never_split) ) t = PicklableTokenizer.from_pretrained("cl-tohoku/bert-base-japanese-whole-word-masking") encoded = train_ds.map(lambda examples: {'tokens': t.encode(examples['title'])}, batched=True) # it works ```
https://github.com/huggingface/datasets/issues/665
runing dataset.map, it raises TypeError: can't pickle Tokenizer objects
We can also update the `BertJapaneseTokenizer` in `transformers` as you just shown @lhoestq to make it compatible with pickle. It will be faster than asking on fugashi 's repo and good for the other users of `transformers` as well. I'm currently working on `transformers` I'll include it in the https://github.com/huggingface/transformers/pull/7141 PR and the next release of `transformers`.
I load squad dataset. Then want to process data use following function with `Huggingface Transformers LongformerTokenizer`. ``` def convert_to_features(example): # Tokenize contexts and questions (as pairs of inputs) input_pairs = [example['question'], example['context']] encodings = tokenizer.encode_plus(input_pairs, pad_to_max_length=True, max_length=512) context_encodings = tokenizer.encode_plus(example['context']) # Compute start and end tokens for labels using Transformers's fast tokenizers alignement methodes. # this will give us the position of answer span in the context text start_idx, end_idx = get_correct_alignement(example['context'], example['answers']) start_positions_context = context_encodings.char_to_token(start_idx) end_positions_context = context_encodings.char_to_token(end_idx-1) # here we will compute the start and end position of the answer in the whole example # as the example is encoded like this <s> question</s></s> context</s> # and we know the postion of the answer in the context # we can just find out the index of the sep token and then add that to position + 1 (+1 because there are two sep tokens) # this will give us the position of the answer span in whole example sep_idx = encodings['input_ids'].index(tokenizer.sep_token_id) start_positions = start_positions_context + sep_idx + 1 end_positions = end_positions_context + sep_idx + 1 if end_positions > 512: start_positions, end_positions = 0, 0 encodings.update({'start_positions': start_positions, 'end_positions': end_positions, 'attention_mask': encodings['attention_mask']}) return encodings ``` Then I run `dataset.map(convert_to_features)`, it raise ``` In [59]: a.map(convert_to_features) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-59-c453b508761d> in <module> ----> 1 a.map(convert_to_features) /opt/conda/lib/python3.7/site-packages/datasets/arrow_dataset.py in map(self, function, with_indices, input_columns, batched, batch_size, drop_last_batch, remove_columns, keep_in_memory, load_from_cache_file, cache_file_name, writer_batch_size, features, disable_nullable, fn_kwargs, num_proc, suffix_template, new_fingerprint) 1242 fn_kwargs=fn_kwargs, 1243 new_fingerprint=new_fingerprint, -> 1244 update_data=update_data, 1245 ) 1246 else: /opt/conda/lib/python3.7/site-packages/datasets/arrow_dataset.py in wrapper(*args, **kwargs) 151 "output_all_columns": self._output_all_columns, 152 } --> 153 out: Union["Dataset", "DatasetDict"] = func(self, *args, **kwargs) 154 if new_format["columns"] is not None: 155 new_format["columns"] = list(set(new_format["columns"]) & set(out.column_names)) /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in wrapper(*args, **kwargs) 156 kwargs_for_fingerprint["fingerprint_name"] = fingerprint_name 157 kwargs[fingerprint_name] = update_fingerprint( --> 158 self._fingerprint, transform, kwargs_for_fingerprint 159 ) 160 /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in update_fingerprint(fingerprint, transform, transform_args) 103 for key in sorted(transform_args): 104 hasher.update(key) --> 105 hasher.update(transform_args[key]) 106 return hasher.hexdigest() 107 /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in update(self, value) 55 def update(self, value): 56 self.m.update(f"=={type(value)}==".encode("utf8")) ---> 57 self.m.update(self.hash(value).encode("utf-8")) 58 59 def hexdigest(self): /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in hash(cls, value) 51 return cls.dispatch[type(value)](cls, value) 52 else: ---> 53 return cls.hash_default(value) 54 55 def update(self, value): /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in hash_default(cls, value) 44 @classmethod 45 def hash_default(cls, value): ---> 46 return cls.hash_bytes(dumps(value)) 47 48 @classmethod /opt/conda/lib/python3.7/site-packages/datasets/utils/py_utils.py in dumps(obj) 365 file = StringIO() 366 with _no_cache_fields(obj): --> 367 dump(obj, file) 368 return file.getvalue() 369 /opt/conda/lib/python3.7/site-packages/datasets/utils/py_utils.py in dump(obj, file) 337 def dump(obj, file): 338 """pickle an object to a file""" --> 339 Pickler(file, recurse=True).dump(obj) 340 return 341 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in dump(self, obj) 444 raise PicklingError(msg) 445 else: --> 446 StockPickler.dump(self, obj) 447 stack.clear() # clear record of 'recursion-sensitive' pickled objects 448 return /opt/conda/lib/python3.7/pickle.py in dump(self, obj) 435 if self.proto >= 4: 436 self.framer.start_framing() --> 437 self.save(obj) 438 self.write(STOP) 439 self.framer.end_framing() /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_function(pickler, obj) 1436 globs, obj.__name__, 1437 obj.__defaults__, obj.__closure__, -> 1438 obj.__dict__, fkwdefaults), obj=obj) 1439 else: 1440 _super = ('super' in getattr(obj.func_code,'co_names',())) and (_byref is not None) and getattr(pickler, '_recurse', False) /opt/conda/lib/python3.7/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 636 else: 637 save(func) --> 638 save(args) 639 write(REDUCE) 640 /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/pickle.py in save_tuple(self, obj) 787 write(MARK) 788 for element in obj: --> 789 save(element) 790 791 if id(obj) in memo: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /opt/conda/lib/python3.7/pickle.py in save_dict(self, obj) 857 858 self.memoize(obj) --> 859 self._batch_setitems(obj.items()) 860 861 dispatch[dict] = save_dict /opt/conda/lib/python3.7/pickle.py in _batch_setitems(self, items) 883 for k, v in tmp: 884 save(k) --> 885 save(v) 886 write(SETITEMS) 887 elif n: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 547 548 # Save the reduce() output and finally memoize the object --> 549 self.save_reduce(obj=obj, *rv) 550 551 def persistent_id(self, obj): /opt/conda/lib/python3.7/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 660 661 if state is not None: --> 662 save(state) 663 write(BUILD) 664 /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /opt/conda/lib/python3.7/pickle.py in save_dict(self, obj) 857 858 self.memoize(obj) --> 859 self._batch_setitems(obj.items()) 860 861 dispatch[dict] = save_dict /opt/conda/lib/python3.7/pickle.py in _batch_setitems(self, items) 883 for k, v in tmp: 884 save(k) --> 885 save(v) 886 write(SETITEMS) 887 elif n: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 547 548 # Save the reduce() output and finally memoize the object --> 549 self.save_reduce(obj=obj, *rv) 550 551 def persistent_id(self, obj): /opt/conda/lib/python3.7/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 660 661 if state is not None: --> 662 save(state) 663 write(BUILD) 664 /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /opt/conda/lib/python3.7/pickle.py in save_dict(self, obj) 857 858 self.memoize(obj) --> 859 self._batch_setitems(obj.items()) 860 861 dispatch[dict] = save_dict /opt/conda/lib/python3.7/pickle.py in _batch_setitems(self, items) 883 for k, v in tmp: 884 save(k) --> 885 save(v) 886 write(SETITEMS) 887 elif n: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 522 reduce = getattr(obj, "__reduce_ex__", None) 523 if reduce is not None: --> 524 rv = reduce(self.proto) 525 else: 526 reduce = getattr(obj, "__reduce__", None) TypeError: can't pickle Tokenizer objects ```
57
runing dataset.map, it raises TypeError: can't pickle Tokenizer objects I load squad dataset. Then want to process data use following function with `Huggingface Transformers LongformerTokenizer`. ``` def convert_to_features(example): # Tokenize contexts and questions (as pairs of inputs) input_pairs = [example['question'], example['context']] encodings = tokenizer.encode_plus(input_pairs, pad_to_max_length=True, max_length=512) context_encodings = tokenizer.encode_plus(example['context']) # Compute start and end tokens for labels using Transformers's fast tokenizers alignement methodes. # this will give us the position of answer span in the context text start_idx, end_idx = get_correct_alignement(example['context'], example['answers']) start_positions_context = context_encodings.char_to_token(start_idx) end_positions_context = context_encodings.char_to_token(end_idx-1) # here we will compute the start and end position of the answer in the whole example # as the example is encoded like this <s> question</s></s> context</s> # and we know the postion of the answer in the context # we can just find out the index of the sep token and then add that to position + 1 (+1 because there are two sep tokens) # this will give us the position of the answer span in whole example sep_idx = encodings['input_ids'].index(tokenizer.sep_token_id) start_positions = start_positions_context + sep_idx + 1 end_positions = end_positions_context + sep_idx + 1 if end_positions > 512: start_positions, end_positions = 0, 0 encodings.update({'start_positions': start_positions, 'end_positions': end_positions, 'attention_mask': encodings['attention_mask']}) return encodings ``` Then I run `dataset.map(convert_to_features)`, it raise ``` In [59]: a.map(convert_to_features) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-59-c453b508761d> in <module> ----> 1 a.map(convert_to_features) /opt/conda/lib/python3.7/site-packages/datasets/arrow_dataset.py in map(self, function, with_indices, input_columns, batched, batch_size, drop_last_batch, remove_columns, keep_in_memory, load_from_cache_file, cache_file_name, writer_batch_size, features, disable_nullable, fn_kwargs, num_proc, suffix_template, new_fingerprint) 1242 fn_kwargs=fn_kwargs, 1243 new_fingerprint=new_fingerprint, -> 1244 update_data=update_data, 1245 ) 1246 else: /opt/conda/lib/python3.7/site-packages/datasets/arrow_dataset.py in wrapper(*args, **kwargs) 151 "output_all_columns": self._output_all_columns, 152 } --> 153 out: Union["Dataset", "DatasetDict"] = func(self, *args, **kwargs) 154 if new_format["columns"] is not None: 155 new_format["columns"] = list(set(new_format["columns"]) & set(out.column_names)) /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in wrapper(*args, **kwargs) 156 kwargs_for_fingerprint["fingerprint_name"] = fingerprint_name 157 kwargs[fingerprint_name] = update_fingerprint( --> 158 self._fingerprint, transform, kwargs_for_fingerprint 159 ) 160 /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in update_fingerprint(fingerprint, transform, transform_args) 103 for key in sorted(transform_args): 104 hasher.update(key) --> 105 hasher.update(transform_args[key]) 106 return hasher.hexdigest() 107 /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in update(self, value) 55 def update(self, value): 56 self.m.update(f"=={type(value)}==".encode("utf8")) ---> 57 self.m.update(self.hash(value).encode("utf-8")) 58 59 def hexdigest(self): /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in hash(cls, value) 51 return cls.dispatch[type(value)](cls, value) 52 else: ---> 53 return cls.hash_default(value) 54 55 def update(self, value): /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in hash_default(cls, value) 44 @classmethod 45 def hash_default(cls, value): ---> 46 return cls.hash_bytes(dumps(value)) 47 48 @classmethod /opt/conda/lib/python3.7/site-packages/datasets/utils/py_utils.py in dumps(obj) 365 file = StringIO() 366 with _no_cache_fields(obj): --> 367 dump(obj, file) 368 return file.getvalue() 369 /opt/conda/lib/python3.7/site-packages/datasets/utils/py_utils.py in dump(obj, file) 337 def dump(obj, file): 338 """pickle an object to a file""" --> 339 Pickler(file, recurse=True).dump(obj) 340 return 341 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in dump(self, obj) 444 raise PicklingError(msg) 445 else: --> 446 StockPickler.dump(self, obj) 447 stack.clear() # clear record of 'recursion-sensitive' pickled objects 448 return /opt/conda/lib/python3.7/pickle.py in dump(self, obj) 435 if self.proto >= 4: 436 self.framer.start_framing() --> 437 self.save(obj) 438 self.write(STOP) 439 self.framer.end_framing() /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_function(pickler, obj) 1436 globs, obj.__name__, 1437 obj.__defaults__, obj.__closure__, -> 1438 obj.__dict__, fkwdefaults), obj=obj) 1439 else: 1440 _super = ('super' in getattr(obj.func_code,'co_names',())) and (_byref is not None) and getattr(pickler, '_recurse', False) /opt/conda/lib/python3.7/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 636 else: 637 save(func) --> 638 save(args) 639 write(REDUCE) 640 /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/pickle.py in save_tuple(self, obj) 787 write(MARK) 788 for element in obj: --> 789 save(element) 790 791 if id(obj) in memo: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /opt/conda/lib/python3.7/pickle.py in save_dict(self, obj) 857 858 self.memoize(obj) --> 859 self._batch_setitems(obj.items()) 860 861 dispatch[dict] = save_dict /opt/conda/lib/python3.7/pickle.py in _batch_setitems(self, items) 883 for k, v in tmp: 884 save(k) --> 885 save(v) 886 write(SETITEMS) 887 elif n: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 547 548 # Save the reduce() output and finally memoize the object --> 549 self.save_reduce(obj=obj, *rv) 550 551 def persistent_id(self, obj): /opt/conda/lib/python3.7/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 660 661 if state is not None: --> 662 save(state) 663 write(BUILD) 664 /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /opt/conda/lib/python3.7/pickle.py in save_dict(self, obj) 857 858 self.memoize(obj) --> 859 self._batch_setitems(obj.items()) 860 861 dispatch[dict] = save_dict /opt/conda/lib/python3.7/pickle.py in _batch_setitems(self, items) 883 for k, v in tmp: 884 save(k) --> 885 save(v) 886 write(SETITEMS) 887 elif n: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 547 548 # Save the reduce() output and finally memoize the object --> 549 self.save_reduce(obj=obj, *rv) 550 551 def persistent_id(self, obj): /opt/conda/lib/python3.7/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 660 661 if state is not None: --> 662 save(state) 663 write(BUILD) 664 /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /opt/conda/lib/python3.7/pickle.py in save_dict(self, obj) 857 858 self.memoize(obj) --> 859 self._batch_setitems(obj.items()) 860 861 dispatch[dict] = save_dict /opt/conda/lib/python3.7/pickle.py in _batch_setitems(self, items) 883 for k, v in tmp: 884 save(k) --> 885 save(v) 886 write(SETITEMS) 887 elif n: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 522 reduce = getattr(obj, "__reduce_ex__", None) 523 if reduce is not None: --> 524 rv = reduce(self.proto) 525 else: 526 reduce = getattr(obj, "__reduce__", None) TypeError: can't pickle Tokenizer objects ``` We can also update the `BertJapaneseTokenizer` in `transformers` as you just shown @lhoestq to make it compatible with pickle. It will be faster than asking on fugashi 's repo and good for the other users of `transformers` as well. I'm currently working on `transformers` I'll include it in the https://github.com/huggingface/transformers/pull/7141 PR and the next release of `transformers`.
https://github.com/huggingface/datasets/issues/665
runing dataset.map, it raises TypeError: can't pickle Tokenizer objects
Thank you for the rapid and polite response! @lhoestq Thanks for the suggestion! I've passed the pickle phase, but another `ArrowInvalid` problem occored. I created another issue #687 . @thomwolf Wow, really fast work. I'm looking forward to the next release ๐Ÿค—
I load squad dataset. Then want to process data use following function with `Huggingface Transformers LongformerTokenizer`. ``` def convert_to_features(example): # Tokenize contexts and questions (as pairs of inputs) input_pairs = [example['question'], example['context']] encodings = tokenizer.encode_plus(input_pairs, pad_to_max_length=True, max_length=512) context_encodings = tokenizer.encode_plus(example['context']) # Compute start and end tokens for labels using Transformers's fast tokenizers alignement methodes. # this will give us the position of answer span in the context text start_idx, end_idx = get_correct_alignement(example['context'], example['answers']) start_positions_context = context_encodings.char_to_token(start_idx) end_positions_context = context_encodings.char_to_token(end_idx-1) # here we will compute the start and end position of the answer in the whole example # as the example is encoded like this <s> question</s></s> context</s> # and we know the postion of the answer in the context # we can just find out the index of the sep token and then add that to position + 1 (+1 because there are two sep tokens) # this will give us the position of the answer span in whole example sep_idx = encodings['input_ids'].index(tokenizer.sep_token_id) start_positions = start_positions_context + sep_idx + 1 end_positions = end_positions_context + sep_idx + 1 if end_positions > 512: start_positions, end_positions = 0, 0 encodings.update({'start_positions': start_positions, 'end_positions': end_positions, 'attention_mask': encodings['attention_mask']}) return encodings ``` Then I run `dataset.map(convert_to_features)`, it raise ``` In [59]: a.map(convert_to_features) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-59-c453b508761d> in <module> ----> 1 a.map(convert_to_features) /opt/conda/lib/python3.7/site-packages/datasets/arrow_dataset.py in map(self, function, with_indices, input_columns, batched, batch_size, drop_last_batch, remove_columns, keep_in_memory, load_from_cache_file, cache_file_name, writer_batch_size, features, disable_nullable, fn_kwargs, num_proc, suffix_template, new_fingerprint) 1242 fn_kwargs=fn_kwargs, 1243 new_fingerprint=new_fingerprint, -> 1244 update_data=update_data, 1245 ) 1246 else: /opt/conda/lib/python3.7/site-packages/datasets/arrow_dataset.py in wrapper(*args, **kwargs) 151 "output_all_columns": self._output_all_columns, 152 } --> 153 out: Union["Dataset", "DatasetDict"] = func(self, *args, **kwargs) 154 if new_format["columns"] is not None: 155 new_format["columns"] = list(set(new_format["columns"]) & set(out.column_names)) /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in wrapper(*args, **kwargs) 156 kwargs_for_fingerprint["fingerprint_name"] = fingerprint_name 157 kwargs[fingerprint_name] = update_fingerprint( --> 158 self._fingerprint, transform, kwargs_for_fingerprint 159 ) 160 /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in update_fingerprint(fingerprint, transform, transform_args) 103 for key in sorted(transform_args): 104 hasher.update(key) --> 105 hasher.update(transform_args[key]) 106 return hasher.hexdigest() 107 /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in update(self, value) 55 def update(self, value): 56 self.m.update(f"=={type(value)}==".encode("utf8")) ---> 57 self.m.update(self.hash(value).encode("utf-8")) 58 59 def hexdigest(self): /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in hash(cls, value) 51 return cls.dispatch[type(value)](cls, value) 52 else: ---> 53 return cls.hash_default(value) 54 55 def update(self, value): /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in hash_default(cls, value) 44 @classmethod 45 def hash_default(cls, value): ---> 46 return cls.hash_bytes(dumps(value)) 47 48 @classmethod /opt/conda/lib/python3.7/site-packages/datasets/utils/py_utils.py in dumps(obj) 365 file = StringIO() 366 with _no_cache_fields(obj): --> 367 dump(obj, file) 368 return file.getvalue() 369 /opt/conda/lib/python3.7/site-packages/datasets/utils/py_utils.py in dump(obj, file) 337 def dump(obj, file): 338 """pickle an object to a file""" --> 339 Pickler(file, recurse=True).dump(obj) 340 return 341 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in dump(self, obj) 444 raise PicklingError(msg) 445 else: --> 446 StockPickler.dump(self, obj) 447 stack.clear() # clear record of 'recursion-sensitive' pickled objects 448 return /opt/conda/lib/python3.7/pickle.py in dump(self, obj) 435 if self.proto >= 4: 436 self.framer.start_framing() --> 437 self.save(obj) 438 self.write(STOP) 439 self.framer.end_framing() /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_function(pickler, obj) 1436 globs, obj.__name__, 1437 obj.__defaults__, obj.__closure__, -> 1438 obj.__dict__, fkwdefaults), obj=obj) 1439 else: 1440 _super = ('super' in getattr(obj.func_code,'co_names',())) and (_byref is not None) and getattr(pickler, '_recurse', False) /opt/conda/lib/python3.7/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 636 else: 637 save(func) --> 638 save(args) 639 write(REDUCE) 640 /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/pickle.py in save_tuple(self, obj) 787 write(MARK) 788 for element in obj: --> 789 save(element) 790 791 if id(obj) in memo: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /opt/conda/lib/python3.7/pickle.py in save_dict(self, obj) 857 858 self.memoize(obj) --> 859 self._batch_setitems(obj.items()) 860 861 dispatch[dict] = save_dict /opt/conda/lib/python3.7/pickle.py in _batch_setitems(self, items) 883 for k, v in tmp: 884 save(k) --> 885 save(v) 886 write(SETITEMS) 887 elif n: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 547 548 # Save the reduce() output and finally memoize the object --> 549 self.save_reduce(obj=obj, *rv) 550 551 def persistent_id(self, obj): /opt/conda/lib/python3.7/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 660 661 if state is not None: --> 662 save(state) 663 write(BUILD) 664 /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /opt/conda/lib/python3.7/pickle.py in save_dict(self, obj) 857 858 self.memoize(obj) --> 859 self._batch_setitems(obj.items()) 860 861 dispatch[dict] = save_dict /opt/conda/lib/python3.7/pickle.py in _batch_setitems(self, items) 883 for k, v in tmp: 884 save(k) --> 885 save(v) 886 write(SETITEMS) 887 elif n: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 547 548 # Save the reduce() output and finally memoize the object --> 549 self.save_reduce(obj=obj, *rv) 550 551 def persistent_id(self, obj): /opt/conda/lib/python3.7/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 660 661 if state is not None: --> 662 save(state) 663 write(BUILD) 664 /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /opt/conda/lib/python3.7/pickle.py in save_dict(self, obj) 857 858 self.memoize(obj) --> 859 self._batch_setitems(obj.items()) 860 861 dispatch[dict] = save_dict /opt/conda/lib/python3.7/pickle.py in _batch_setitems(self, items) 883 for k, v in tmp: 884 save(k) --> 885 save(v) 886 write(SETITEMS) 887 elif n: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 522 reduce = getattr(obj, "__reduce_ex__", None) 523 if reduce is not None: --> 524 rv = reduce(self.proto) 525 else: 526 reduce = getattr(obj, "__reduce__", None) TypeError: can't pickle Tokenizer objects ```
42
runing dataset.map, it raises TypeError: can't pickle Tokenizer objects I load squad dataset. Then want to process data use following function with `Huggingface Transformers LongformerTokenizer`. ``` def convert_to_features(example): # Tokenize contexts and questions (as pairs of inputs) input_pairs = [example['question'], example['context']] encodings = tokenizer.encode_plus(input_pairs, pad_to_max_length=True, max_length=512) context_encodings = tokenizer.encode_plus(example['context']) # Compute start and end tokens for labels using Transformers's fast tokenizers alignement methodes. # this will give us the position of answer span in the context text start_idx, end_idx = get_correct_alignement(example['context'], example['answers']) start_positions_context = context_encodings.char_to_token(start_idx) end_positions_context = context_encodings.char_to_token(end_idx-1) # here we will compute the start and end position of the answer in the whole example # as the example is encoded like this <s> question</s></s> context</s> # and we know the postion of the answer in the context # we can just find out the index of the sep token and then add that to position + 1 (+1 because there are two sep tokens) # this will give us the position of the answer span in whole example sep_idx = encodings['input_ids'].index(tokenizer.sep_token_id) start_positions = start_positions_context + sep_idx + 1 end_positions = end_positions_context + sep_idx + 1 if end_positions > 512: start_positions, end_positions = 0, 0 encodings.update({'start_positions': start_positions, 'end_positions': end_positions, 'attention_mask': encodings['attention_mask']}) return encodings ``` Then I run `dataset.map(convert_to_features)`, it raise ``` In [59]: a.map(convert_to_features) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-59-c453b508761d> in <module> ----> 1 a.map(convert_to_features) /opt/conda/lib/python3.7/site-packages/datasets/arrow_dataset.py in map(self, function, with_indices, input_columns, batched, batch_size, drop_last_batch, remove_columns, keep_in_memory, load_from_cache_file, cache_file_name, writer_batch_size, features, disable_nullable, fn_kwargs, num_proc, suffix_template, new_fingerprint) 1242 fn_kwargs=fn_kwargs, 1243 new_fingerprint=new_fingerprint, -> 1244 update_data=update_data, 1245 ) 1246 else: /opt/conda/lib/python3.7/site-packages/datasets/arrow_dataset.py in wrapper(*args, **kwargs) 151 "output_all_columns": self._output_all_columns, 152 } --> 153 out: Union["Dataset", "DatasetDict"] = func(self, *args, **kwargs) 154 if new_format["columns"] is not None: 155 new_format["columns"] = list(set(new_format["columns"]) & set(out.column_names)) /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in wrapper(*args, **kwargs) 156 kwargs_for_fingerprint["fingerprint_name"] = fingerprint_name 157 kwargs[fingerprint_name] = update_fingerprint( --> 158 self._fingerprint, transform, kwargs_for_fingerprint 159 ) 160 /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in update_fingerprint(fingerprint, transform, transform_args) 103 for key in sorted(transform_args): 104 hasher.update(key) --> 105 hasher.update(transform_args[key]) 106 return hasher.hexdigest() 107 /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in update(self, value) 55 def update(self, value): 56 self.m.update(f"=={type(value)}==".encode("utf8")) ---> 57 self.m.update(self.hash(value).encode("utf-8")) 58 59 def hexdigest(self): /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in hash(cls, value) 51 return cls.dispatch[type(value)](cls, value) 52 else: ---> 53 return cls.hash_default(value) 54 55 def update(self, value): /opt/conda/lib/python3.7/site-packages/datasets/fingerprint.py in hash_default(cls, value) 44 @classmethod 45 def hash_default(cls, value): ---> 46 return cls.hash_bytes(dumps(value)) 47 48 @classmethod /opt/conda/lib/python3.7/site-packages/datasets/utils/py_utils.py in dumps(obj) 365 file = StringIO() 366 with _no_cache_fields(obj): --> 367 dump(obj, file) 368 return file.getvalue() 369 /opt/conda/lib/python3.7/site-packages/datasets/utils/py_utils.py in dump(obj, file) 337 def dump(obj, file): 338 """pickle an object to a file""" --> 339 Pickler(file, recurse=True).dump(obj) 340 return 341 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in dump(self, obj) 444 raise PicklingError(msg) 445 else: --> 446 StockPickler.dump(self, obj) 447 stack.clear() # clear record of 'recursion-sensitive' pickled objects 448 return /opt/conda/lib/python3.7/pickle.py in dump(self, obj) 435 if self.proto >= 4: 436 self.framer.start_framing() --> 437 self.save(obj) 438 self.write(STOP) 439 self.framer.end_framing() /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_function(pickler, obj) 1436 globs, obj.__name__, 1437 obj.__defaults__, obj.__closure__, -> 1438 obj.__dict__, fkwdefaults), obj=obj) 1439 else: 1440 _super = ('super' in getattr(obj.func_code,'co_names',())) and (_byref is not None) and getattr(pickler, '_recurse', False) /opt/conda/lib/python3.7/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 636 else: 637 save(func) --> 638 save(args) 639 write(REDUCE) 640 /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/pickle.py in save_tuple(self, obj) 787 write(MARK) 788 for element in obj: --> 789 save(element) 790 791 if id(obj) in memo: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /opt/conda/lib/python3.7/pickle.py in save_dict(self, obj) 857 858 self.memoize(obj) --> 859 self._batch_setitems(obj.items()) 860 861 dispatch[dict] = save_dict /opt/conda/lib/python3.7/pickle.py in _batch_setitems(self, items) 883 for k, v in tmp: 884 save(k) --> 885 save(v) 886 write(SETITEMS) 887 elif n: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 547 548 # Save the reduce() output and finally memoize the object --> 549 self.save_reduce(obj=obj, *rv) 550 551 def persistent_id(self, obj): /opt/conda/lib/python3.7/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 660 661 if state is not None: --> 662 save(state) 663 write(BUILD) 664 /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /opt/conda/lib/python3.7/pickle.py in save_dict(self, obj) 857 858 self.memoize(obj) --> 859 self._batch_setitems(obj.items()) 860 861 dispatch[dict] = save_dict /opt/conda/lib/python3.7/pickle.py in _batch_setitems(self, items) 883 for k, v in tmp: 884 save(k) --> 885 save(v) 886 write(SETITEMS) 887 elif n: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 547 548 # Save the reduce() output and finally memoize the object --> 549 self.save_reduce(obj=obj, *rv) 550 551 def persistent_id(self, obj): /opt/conda/lib/python3.7/pickle.py in save_reduce(self, func, args, state, listitems, dictitems, obj) 660 661 if state is not None: --> 662 save(state) 663 write(BUILD) 664 /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 502 f = self.dispatch.get(t) 503 if f is not None: --> 504 f(self, obj) # Call unbound method with explicit self 505 return 506 /opt/conda/lib/python3.7/site-packages/dill/_dill.py in save_module_dict(pickler, obj) 931 # we only care about session the first pass thru 932 pickler._session = False --> 933 StockPickler.save_dict(pickler, obj) 934 log.info("# D2") 935 return /opt/conda/lib/python3.7/pickle.py in save_dict(self, obj) 857 858 self.memoize(obj) --> 859 self._batch_setitems(obj.items()) 860 861 dispatch[dict] = save_dict /opt/conda/lib/python3.7/pickle.py in _batch_setitems(self, items) 883 for k, v in tmp: 884 save(k) --> 885 save(v) 886 write(SETITEMS) 887 elif n: /opt/conda/lib/python3.7/pickle.py in save(self, obj, save_persistent_id) 522 reduce = getattr(obj, "__reduce_ex__", None) 523 if reduce is not None: --> 524 rv = reduce(self.proto) 525 else: 526 reduce = getattr(obj, "__reduce__", None) TypeError: can't pickle Tokenizer objects ``` Thank you for the rapid and polite response! @lhoestq Thanks for the suggestion! I've passed the pickle phase, but another `ArrowInvalid` problem occored. I created another issue #687 . @thomwolf Wow, really fast work. I'm looking forward to the next release ๐Ÿค—
https://github.com/huggingface/datasets/issues/664
load_dataset from local squad.py, raise error: TypeError: 'NoneType' object is not callable
Hi ! Thanks for reporting. It looks like no object inherits from `datasets.GeneratorBasedBuilder` (or more generally from `datasets.DatasetBuilder`) in your script. Could you check that there exist at least one dataset builder class ?
version: 1.0.2 ``` train_dataset = datasets.load_dataset('squad') ``` The above code can works. However, when I download the squad.py from your server, and saved as `my_squad.py` to local. I run followings raise errors. ``` train_dataset = datasets.load_dataset('./my_squad.py') ``` --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-28-25a84b4d1581> in <module> ----> 1 train_dataset = nlp.load_dataset('./my_squad.py') /opt/conda/lib/python3.7/site-packages/datasets/load.py in load_dataset(path, name, data_dir, data_files, split, cache_dir, features, download_config, download_mode, ignore_verifications, save_infos, script_version, **config_kwargs) 602 hash=hash, 603 features=features, --> 604 **config_kwargs, 605 ) 606 TypeError: 'NoneType' object is not callable
34
load_dataset from local squad.py, raise error: TypeError: 'NoneType' object is not callable version: 1.0.2 ``` train_dataset = datasets.load_dataset('squad') ``` The above code can works. However, when I download the squad.py from your server, and saved as `my_squad.py` to local. I run followings raise errors. ``` train_dataset = datasets.load_dataset('./my_squad.py') ``` --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-28-25a84b4d1581> in <module> ----> 1 train_dataset = nlp.load_dataset('./my_squad.py') /opt/conda/lib/python3.7/site-packages/datasets/load.py in load_dataset(path, name, data_dir, data_files, split, cache_dir, features, download_config, download_mode, ignore_verifications, save_infos, script_version, **config_kwargs) 602 hash=hash, 603 features=features, --> 604 **config_kwargs, 605 ) 606 TypeError: 'NoneType' object is not callable Hi ! Thanks for reporting. It looks like no object inherits from `datasets.GeneratorBasedBuilder` (or more generally from `datasets.DatasetBuilder`) in your script. Could you check that there exist at least one dataset builder class ?
https://github.com/huggingface/datasets/issues/664
load_dataset from local squad.py, raise error: TypeError: 'NoneType' object is not callable
It happened when try to change the old project which use 'nlp' to new project which use 'datasets'. You should check you old 'my_squad.py' file, change the inherit class from `nlp.xxx` to `datasets.xxx`. Otherwise datasets - load.py - import_main_class() `if inspect.isclass(obj) and issubclass(obj, main_cls_type):` can not find the main_cls.
version: 1.0.2 ``` train_dataset = datasets.load_dataset('squad') ``` The above code can works. However, when I download the squad.py from your server, and saved as `my_squad.py` to local. I run followings raise errors. ``` train_dataset = datasets.load_dataset('./my_squad.py') ``` --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-28-25a84b4d1581> in <module> ----> 1 train_dataset = nlp.load_dataset('./my_squad.py') /opt/conda/lib/python3.7/site-packages/datasets/load.py in load_dataset(path, name, data_dir, data_files, split, cache_dir, features, download_config, download_mode, ignore_verifications, save_infos, script_version, **config_kwargs) 602 hash=hash, 603 features=features, --> 604 **config_kwargs, 605 ) 606 TypeError: 'NoneType' object is not callable
49
load_dataset from local squad.py, raise error: TypeError: 'NoneType' object is not callable version: 1.0.2 ``` train_dataset = datasets.load_dataset('squad') ``` The above code can works. However, when I download the squad.py from your server, and saved as `my_squad.py` to local. I run followings raise errors. ``` train_dataset = datasets.load_dataset('./my_squad.py') ``` --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-28-25a84b4d1581> in <module> ----> 1 train_dataset = nlp.load_dataset('./my_squad.py') /opt/conda/lib/python3.7/site-packages/datasets/load.py in load_dataset(path, name, data_dir, data_files, split, cache_dir, features, download_config, download_mode, ignore_verifications, save_infos, script_version, **config_kwargs) 602 hash=hash, 603 features=features, --> 604 **config_kwargs, 605 ) 606 TypeError: 'NoneType' object is not callable It happened when try to change the old project which use 'nlp' to new project which use 'datasets'. You should check you old 'my_squad.py' file, change the inherit class from `nlp.xxx` to `datasets.xxx`. Otherwise datasets - load.py - import_main_class() `if inspect.isclass(obj) and issubclass(obj, main_cls_type):` can not find the main_cls.
https://github.com/huggingface/datasets/issues/657
Squad Metric Description & Feature Mismatch
Thanks for reporting ! There indeed a mismatch between the features and the kwargs description I believe `answer_start` was added to match the squad dataset format for consistency, even though it is not used in the metric computation. I think I'd rather keep it this way, so that you can just give `references=squad["answers"]` to `.compute()`. Maybe we can just fix the description then.
The [description](https://github.com/huggingface/datasets/blob/master/metrics/squad/squad.py#L39) doesn't mention `answer_start` in squad. However the `datasets.features` require [it](https://github.com/huggingface/datasets/blob/master/metrics/squad/squad.py#L68). It's also not used in the evaluation.
63
Squad Metric Description & Feature Mismatch The [description](https://github.com/huggingface/datasets/blob/master/metrics/squad/squad.py#L39) doesn't mention `answer_start` in squad. However the `datasets.features` require [it](https://github.com/huggingface/datasets/blob/master/metrics/squad/squad.py#L68). It's also not used in the evaluation. Thanks for reporting ! There indeed a mismatch between the features and the kwargs description I believe `answer_start` was added to match the squad dataset format for consistency, even though it is not used in the metric computation. I think I'd rather keep it this way, so that you can just give `references=squad["answers"]` to `.compute()`. Maybe we can just fix the description then.
https://github.com/huggingface/datasets/issues/657
Squad Metric Description & Feature Mismatch
But then providing the `answer_start` becomes mandatory since the format of the features is checked against the one provided in the squad [file](https://github.com/huggingface/datasets/pull/658/files).
The [description](https://github.com/huggingface/datasets/blob/master/metrics/squad/squad.py#L39) doesn't mention `answer_start` in squad. However the `datasets.features` require [it](https://github.com/huggingface/datasets/blob/master/metrics/squad/squad.py#L68). It's also not used in the evaluation.
23
Squad Metric Description & Feature Mismatch The [description](https://github.com/huggingface/datasets/blob/master/metrics/squad/squad.py#L39) doesn't mention `answer_start` in squad. However the `datasets.features` require [it](https://github.com/huggingface/datasets/blob/master/metrics/squad/squad.py#L68). It's also not used in the evaluation. But then providing the `answer_start` becomes mandatory since the format of the features is checked against the one provided in the squad [file](https://github.com/huggingface/datasets/pull/658/files).
https://github.com/huggingface/datasets/issues/651
Problem with JSON dataset format
Currently the `json` dataset doesn't support this format unfortunately. However you could load it with ```python from datasets import Dataset import pandas as pd df = pd.read_json("path_to_local.json", orient="index") dataset = Dataset.from_pandas(df) ```
I have a local json dataset with the following form. { 'id01234': {'key1': value1, 'key2': value2, 'key3': value3}, 'id01235': {'key1': value1, 'key2': value2, 'key3': value3}, . . . 'id09999': {'key1': value1, 'key2': value2, 'key3': value3} } Note that instead of a list of records it's basically a dictionary of key value pairs with the keys being the record_ids and the values being the corresponding record. Reading this with json: ``` data = datasets.load('json', data_files='path_to_local.json') ``` Throws an error and asks me to chose a field. What's the right way to handle this?
32
Problem with JSON dataset format I have a local json dataset with the following form. { 'id01234': {'key1': value1, 'key2': value2, 'key3': value3}, 'id01235': {'key1': value1, 'key2': value2, 'key3': value3}, . . . 'id09999': {'key1': value1, 'key2': value2, 'key3': value3} } Note that instead of a list of records it's basically a dictionary of key value pairs with the keys being the record_ids and the values being the corresponding record. Reading this with json: ``` data = datasets.load('json', data_files='path_to_local.json') ``` Throws an error and asks me to chose a field. What's the right way to handle this? Currently the `json` dataset doesn't support this format unfortunately. However you could load it with ```python from datasets import Dataset import pandas as pd df = pd.read_json("path_to_local.json", orient="index") dataset = Dataset.from_pandas(df) ```
https://github.com/huggingface/datasets/issues/650
dummy data testing can't test datasets using `dl_manager.extract` in `_split_generators`
Hi :) In your dummy data zip file you can just have `subset000.xz` as directories instead of compressed files. Let me know if it helps
Hi, I recently want to add a dataset whose source data is like this ``` openwebtext.tar.xz |__ openwebtext |__subset000.xz | |__ ....txt | |__ ....txt | ... |__ subset001.xz | .... ``` So I wrote `openwebtext.py` like this ``` def _split_generators(self, dl_manager): dl_dir = dl_manager.download_and_extract(_URL) owt_dir = os.path.join(dl_dir, 'openwebtext') subset_xzs = [ os.path.join(owt_dir, file_name) for file_name in os.listdir(owt_dir) if file_name.endswith('xz') # filter out ...xz.lock ] ex_dirs = dl_manager.extract(subset_xzs, num_proc=round(os.cpu_count()*0.75)) nested_txt_files = [ [ os.path.join(ex_dir,txt_file_name) for txt_file_name in os.listdir(ex_dir) if txt_file_name.endswith('txt') ] for ex_dir in ex_dirs ] txt_files = chain(*nested_txt_files) return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={"txt_files": txt_files} ), ] ``` All went good, I can load and use real openwebtext, except when I try to test with dummy data. The problem is `MockDownloadManager.extract` do nothing, so `ex_dirs = dl_manager.extract(subset_xzs)` won't decompress `subset_xxx.xz`s for me. How should I do ? Or you can modify `MockDownloadManager` to make it like a real `DownloadManager` ?
25
dummy data testing can't test datasets using `dl_manager.extract` in `_split_generators` Hi, I recently want to add a dataset whose source data is like this ``` openwebtext.tar.xz |__ openwebtext |__subset000.xz | |__ ....txt | |__ ....txt | ... |__ subset001.xz | .... ``` So I wrote `openwebtext.py` like this ``` def _split_generators(self, dl_manager): dl_dir = dl_manager.download_and_extract(_URL) owt_dir = os.path.join(dl_dir, 'openwebtext') subset_xzs = [ os.path.join(owt_dir, file_name) for file_name in os.listdir(owt_dir) if file_name.endswith('xz') # filter out ...xz.lock ] ex_dirs = dl_manager.extract(subset_xzs, num_proc=round(os.cpu_count()*0.75)) nested_txt_files = [ [ os.path.join(ex_dir,txt_file_name) for txt_file_name in os.listdir(ex_dir) if txt_file_name.endswith('txt') ] for ex_dir in ex_dirs ] txt_files = chain(*nested_txt_files) return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={"txt_files": txt_files} ), ] ``` All went good, I can load and use real openwebtext, except when I try to test with dummy data. The problem is `MockDownloadManager.extract` do nothing, so `ex_dirs = dl_manager.extract(subset_xzs)` won't decompress `subset_xxx.xz`s for me. How should I do ? Or you can modify `MockDownloadManager` to make it like a real `DownloadManager` ? Hi :) In your dummy data zip file you can just have `subset000.xz` as directories instead of compressed files. Let me know if it helps
https://github.com/huggingface/datasets/issues/650
dummy data testing can't test datasets using `dl_manager.extract` in `_split_generators`
Thanks for your comment @lhoestq , Just for confirmation, changing dummy data like this won't make dummy test test the functionality to extract `subsetxxx.xz` but actually kind of circumvent it. But since we will test the real data so it is ok ?
Hi, I recently want to add a dataset whose source data is like this ``` openwebtext.tar.xz |__ openwebtext |__subset000.xz | |__ ....txt | |__ ....txt | ... |__ subset001.xz | .... ``` So I wrote `openwebtext.py` like this ``` def _split_generators(self, dl_manager): dl_dir = dl_manager.download_and_extract(_URL) owt_dir = os.path.join(dl_dir, 'openwebtext') subset_xzs = [ os.path.join(owt_dir, file_name) for file_name in os.listdir(owt_dir) if file_name.endswith('xz') # filter out ...xz.lock ] ex_dirs = dl_manager.extract(subset_xzs, num_proc=round(os.cpu_count()*0.75)) nested_txt_files = [ [ os.path.join(ex_dir,txt_file_name) for txt_file_name in os.listdir(ex_dir) if txt_file_name.endswith('txt') ] for ex_dir in ex_dirs ] txt_files = chain(*nested_txt_files) return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={"txt_files": txt_files} ), ] ``` All went good, I can load and use real openwebtext, except when I try to test with dummy data. The problem is `MockDownloadManager.extract` do nothing, so `ex_dirs = dl_manager.extract(subset_xzs)` won't decompress `subset_xxx.xz`s for me. How should I do ? Or you can modify `MockDownloadManager` to make it like a real `DownloadManager` ?
43
dummy data testing can't test datasets using `dl_manager.extract` in `_split_generators` Hi, I recently want to add a dataset whose source data is like this ``` openwebtext.tar.xz |__ openwebtext |__subset000.xz | |__ ....txt | |__ ....txt | ... |__ subset001.xz | .... ``` So I wrote `openwebtext.py` like this ``` def _split_generators(self, dl_manager): dl_dir = dl_manager.download_and_extract(_URL) owt_dir = os.path.join(dl_dir, 'openwebtext') subset_xzs = [ os.path.join(owt_dir, file_name) for file_name in os.listdir(owt_dir) if file_name.endswith('xz') # filter out ...xz.lock ] ex_dirs = dl_manager.extract(subset_xzs, num_proc=round(os.cpu_count()*0.75)) nested_txt_files = [ [ os.path.join(ex_dir,txt_file_name) for txt_file_name in os.listdir(ex_dir) if txt_file_name.endswith('txt') ] for ex_dir in ex_dirs ] txt_files = chain(*nested_txt_files) return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={"txt_files": txt_files} ), ] ``` All went good, I can load and use real openwebtext, except when I try to test with dummy data. The problem is `MockDownloadManager.extract` do nothing, so `ex_dirs = dl_manager.extract(subset_xzs)` won't decompress `subset_xxx.xz`s for me. How should I do ? Or you can modify `MockDownloadManager` to make it like a real `DownloadManager` ? Thanks for your comment @lhoestq , Just for confirmation, changing dummy data like this won't make dummy test test the functionality to extract `subsetxxx.xz` but actually kind of circumvent it. But since we will test the real data so it is ok ?
https://github.com/huggingface/datasets/issues/650
dummy data testing can't test datasets using `dl_manager.extract` in `_split_generators`
Yes it's fine for now. We plan to add a job for slow tests. And at one point we'll also do another pass on the dummy data handling and consider extracting files.
Hi, I recently want to add a dataset whose source data is like this ``` openwebtext.tar.xz |__ openwebtext |__subset000.xz | |__ ....txt | |__ ....txt | ... |__ subset001.xz | .... ``` So I wrote `openwebtext.py` like this ``` def _split_generators(self, dl_manager): dl_dir = dl_manager.download_and_extract(_URL) owt_dir = os.path.join(dl_dir, 'openwebtext') subset_xzs = [ os.path.join(owt_dir, file_name) for file_name in os.listdir(owt_dir) if file_name.endswith('xz') # filter out ...xz.lock ] ex_dirs = dl_manager.extract(subset_xzs, num_proc=round(os.cpu_count()*0.75)) nested_txt_files = [ [ os.path.join(ex_dir,txt_file_name) for txt_file_name in os.listdir(ex_dir) if txt_file_name.endswith('txt') ] for ex_dir in ex_dirs ] txt_files = chain(*nested_txt_files) return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={"txt_files": txt_files} ), ] ``` All went good, I can load and use real openwebtext, except when I try to test with dummy data. The problem is `MockDownloadManager.extract` do nothing, so `ex_dirs = dl_manager.extract(subset_xzs)` won't decompress `subset_xxx.xz`s for me. How should I do ? Or you can modify `MockDownloadManager` to make it like a real `DownloadManager` ?
32
dummy data testing can't test datasets using `dl_manager.extract` in `_split_generators` Hi, I recently want to add a dataset whose source data is like this ``` openwebtext.tar.xz |__ openwebtext |__subset000.xz | |__ ....txt | |__ ....txt | ... |__ subset001.xz | .... ``` So I wrote `openwebtext.py` like this ``` def _split_generators(self, dl_manager): dl_dir = dl_manager.download_and_extract(_URL) owt_dir = os.path.join(dl_dir, 'openwebtext') subset_xzs = [ os.path.join(owt_dir, file_name) for file_name in os.listdir(owt_dir) if file_name.endswith('xz') # filter out ...xz.lock ] ex_dirs = dl_manager.extract(subset_xzs, num_proc=round(os.cpu_count()*0.75)) nested_txt_files = [ [ os.path.join(ex_dir,txt_file_name) for txt_file_name in os.listdir(ex_dir) if txt_file_name.endswith('txt') ] for ex_dir in ex_dirs ] txt_files = chain(*nested_txt_files) return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={"txt_files": txt_files} ), ] ``` All went good, I can load and use real openwebtext, except when I try to test with dummy data. The problem is `MockDownloadManager.extract` do nothing, so `ex_dirs = dl_manager.extract(subset_xzs)` won't decompress `subset_xxx.xz`s for me. How should I do ? Or you can modify `MockDownloadManager` to make it like a real `DownloadManager` ? Yes it's fine for now. We plan to add a job for slow tests. And at one point we'll also do another pass on the dummy data handling and consider extracting files.
https://github.com/huggingface/datasets/issues/649
Inconsistent behavior in map
Thanks for reporting ! This issue must have appeared when we refactored type inference in `nlp` By default the library tries to keep the same feature types when applying `map` but apparently it has troubles with nested structures. I'll try to fix that next week
I'm observing inconsistent behavior when applying .map(). This happens specifically when I'm incrementally adding onto a feature that is a nested dictionary. Here's a simple example that reproduces the problem. ```python import datasets # Dataset with a single feature called 'field' consisting of two examples dataset = datasets.Dataset.from_dict({'field': ['a', 'b']}) print(dataset[0]) # outputs {'field': 'a'} # Map this dataset to create another feature called 'otherfield', which is a dictionary containing a key called 'capital' dataset = dataset.map(lambda example: {'otherfield': {'capital': example['field'].capitalize()}}) print(dataset[0]) # output is okay {'field': 'a', 'otherfield': {'capital': 'A'}} # Now I want to map again to modify 'otherfield', by adding another key called 'append_x' to the dictionary under 'otherfield' print(dataset.map(lambda example: {'otherfield': {'append_x': example['field'] + 'x'}})[0]) # printing out the first example after applying the map shows that the new key 'append_x' doesn't get added # it also messes up the value stored at 'capital' {'field': 'a', 'otherfield': {'capital': None}} # Instead, I try to do the same thing by using a different mapped fn print(dataset.map(lambda example: {'otherfield': {'append_x': example['field'] + 'x', 'capital': example['otherfield']['capital']}})[0]) # this preserves the value under capital, but still no 'append_x' {'field': 'a', 'otherfield': {'capital': 'A'}} # Instead, I try to pass 'otherfield' to remove_columns print(dataset.map(lambda example: {'otherfield': {'append_x': example['field'] + 'x', 'capital': example['otherfield']['capital']}}, remove_columns=['otherfield'])[0]) # this still doesn't fix the problem {'field': 'a', 'otherfield': {'capital': 'A'}} # Alternately, here's what happens if I just directly map both 'capital' and 'append_x' on a fresh dataset. # Recreate the dataset dataset = datasets.Dataset.from_dict({'field': ['a', 'b']}) # Now map the entire 'otherfield' dict directly, instead of incrementally as before print(dataset.map(lambda example: {'otherfield': {'append_x': example['field'] + 'x', 'capital': example['field'].capitalize()}})[0]) # This looks good! {'field': 'a', 'otherfield': {'append_x': 'ax', 'capital': 'A'}} ``` This might be a new issue, because I didn't see this behavior in the `nlp` library. Any help is appreciated!
45
Inconsistent behavior in map I'm observing inconsistent behavior when applying .map(). This happens specifically when I'm incrementally adding onto a feature that is a nested dictionary. Here's a simple example that reproduces the problem. ```python import datasets # Dataset with a single feature called 'field' consisting of two examples dataset = datasets.Dataset.from_dict({'field': ['a', 'b']}) print(dataset[0]) # outputs {'field': 'a'} # Map this dataset to create another feature called 'otherfield', which is a dictionary containing a key called 'capital' dataset = dataset.map(lambda example: {'otherfield': {'capital': example['field'].capitalize()}}) print(dataset[0]) # output is okay {'field': 'a', 'otherfield': {'capital': 'A'}} # Now I want to map again to modify 'otherfield', by adding another key called 'append_x' to the dictionary under 'otherfield' print(dataset.map(lambda example: {'otherfield': {'append_x': example['field'] + 'x'}})[0]) # printing out the first example after applying the map shows that the new key 'append_x' doesn't get added # it also messes up the value stored at 'capital' {'field': 'a', 'otherfield': {'capital': None}} # Instead, I try to do the same thing by using a different mapped fn print(dataset.map(lambda example: {'otherfield': {'append_x': example['field'] + 'x', 'capital': example['otherfield']['capital']}})[0]) # this preserves the value under capital, but still no 'append_x' {'field': 'a', 'otherfield': {'capital': 'A'}} # Instead, I try to pass 'otherfield' to remove_columns print(dataset.map(lambda example: {'otherfield': {'append_x': example['field'] + 'x', 'capital': example['otherfield']['capital']}}, remove_columns=['otherfield'])[0]) # this still doesn't fix the problem {'field': 'a', 'otherfield': {'capital': 'A'}} # Alternately, here's what happens if I just directly map both 'capital' and 'append_x' on a fresh dataset. # Recreate the dataset dataset = datasets.Dataset.from_dict({'field': ['a', 'b']}) # Now map the entire 'otherfield' dict directly, instead of incrementally as before print(dataset.map(lambda example: {'otherfield': {'append_x': example['field'] + 'x', 'capital': example['field'].capitalize()}})[0]) # This looks good! {'field': 'a', 'otherfield': {'append_x': 'ax', 'capital': 'A'}} ``` This might be a new issue, because I didn't see this behavior in the `nlp` library. Any help is appreciated! Thanks for reporting ! This issue must have appeared when we refactored type inference in `nlp` By default the library tries to keep the same feature types when applying `map` but apparently it has troubles with nested structures. I'll try to fix that next week
https://github.com/huggingface/datasets/issues/647
Cannot download dataset_info.json
Thanks for reporting ! We should add support for servers without internet connection indeed I'll do that early next week
I am running my job on a cloud server where does not provide for connections from the standard compute nodes to outside resources. Hence, when I use `dataset.load_dataset()` to load data, I got an error like this: ``` ConnectionError: Couldn't reach https://storage.googleapis.com/huggingface-nlp/cache/datasets/text/default-53ee3045f07ba8ca/0.0.0/dataset_info.json ``` I tried to open this link manually, but I cannot access this file. How can I download this file and pass it through `dataset.load_dataset()` manually? Versions: Python version 3.7.3 PyTorch version 1.6.0 TensorFlow version 2.3.0 datasets version: 1.0.1
20
Cannot download dataset_info.json I am running my job on a cloud server where does not provide for connections from the standard compute nodes to outside resources. Hence, when I use `dataset.load_dataset()` to load data, I got an error like this: ``` ConnectionError: Couldn't reach https://storage.googleapis.com/huggingface-nlp/cache/datasets/text/default-53ee3045f07ba8ca/0.0.0/dataset_info.json ``` I tried to open this link manually, but I cannot access this file. How can I download this file and pass it through `dataset.load_dataset()` manually? Versions: Python version 3.7.3 PyTorch version 1.6.0 TensorFlow version 2.3.0 datasets version: 1.0.1 Thanks for reporting ! We should add support for servers without internet connection indeed I'll do that early next week
https://github.com/huggingface/datasets/issues/647
Cannot download dataset_info.json
Right now the recommended way is to create the dataset on a server with internet connection and then to save it and copy the serialized dataset to the server without internet connection.
I am running my job on a cloud server where does not provide for connections from the standard compute nodes to outside resources. Hence, when I use `dataset.load_dataset()` to load data, I got an error like this: ``` ConnectionError: Couldn't reach https://storage.googleapis.com/huggingface-nlp/cache/datasets/text/default-53ee3045f07ba8ca/0.0.0/dataset_info.json ``` I tried to open this link manually, but I cannot access this file. How can I download this file and pass it through `dataset.load_dataset()` manually? Versions: Python version 3.7.3 PyTorch version 1.6.0 TensorFlow version 2.3.0 datasets version: 1.0.1
32
Cannot download dataset_info.json I am running my job on a cloud server where does not provide for connections from the standard compute nodes to outside resources. Hence, when I use `dataset.load_dataset()` to load data, I got an error like this: ``` ConnectionError: Couldn't reach https://storage.googleapis.com/huggingface-nlp/cache/datasets/text/default-53ee3045f07ba8ca/0.0.0/dataset_info.json ``` I tried to open this link manually, but I cannot access this file. How can I download this file and pass it through `dataset.load_dataset()` manually? Versions: Python version 3.7.3 PyTorch version 1.6.0 TensorFlow version 2.3.0 datasets version: 1.0.1 Right now the recommended way is to create the dataset on a server with internet connection and then to save it and copy the serialized dataset to the server without internet connection.
https://github.com/huggingface/datasets/issues/647
Cannot download dataset_info.json
#652 should allow you to load text/json/csv/pandas datasets without an internet connection **IF** you've the dataset script locally. Example: If you have `datasets/text/text.py` locally, then you can do `load_dataset("./datasets/text", data_files=...)`
I am running my job on a cloud server where does not provide for connections from the standard compute nodes to outside resources. Hence, when I use `dataset.load_dataset()` to load data, I got an error like this: ``` ConnectionError: Couldn't reach https://storage.googleapis.com/huggingface-nlp/cache/datasets/text/default-53ee3045f07ba8ca/0.0.0/dataset_info.json ``` I tried to open this link manually, but I cannot access this file. How can I download this file and pass it through `dataset.load_dataset()` manually? Versions: Python version 3.7.3 PyTorch version 1.6.0 TensorFlow version 2.3.0 datasets version: 1.0.1
30
Cannot download dataset_info.json I am running my job on a cloud server where does not provide for connections from the standard compute nodes to outside resources. Hence, when I use `dataset.load_dataset()` to load data, I got an error like this: ``` ConnectionError: Couldn't reach https://storage.googleapis.com/huggingface-nlp/cache/datasets/text/default-53ee3045f07ba8ca/0.0.0/dataset_info.json ``` I tried to open this link manually, but I cannot access this file. How can I download this file and pass it through `dataset.load_dataset()` manually? Versions: Python version 3.7.3 PyTorch version 1.6.0 TensorFlow version 2.3.0 datasets version: 1.0.1 #652 should allow you to load text/json/csv/pandas datasets without an internet connection **IF** you've the dataset script locally. Example: If you have `datasets/text/text.py` locally, then you can do `load_dataset("./datasets/text", data_files=...)`
https://github.com/huggingface/datasets/issues/643
Caching processed dataset at wrong folder
Thanks for reporting ! It uses a temporary file to write the data. However it looks like the temporary file is not placed in the right directory during the processing
Hi guys, I run this on my Colab (PRO): ```python from datasets import load_dataset dataset = load_dataset('text', data_files='/content/corpus.txt', cache_dir='/content/drive/My Drive', split='train') def encode(examples): return tokenizer(examples['text'], truncation=True, padding='max_length') dataset = dataset.map(encode, batched=True) ``` The file is about 4 GB, so I cannot process it on the Colab HD because there is no enough space. So I decided to mount my Google Drive fs and do it on it. The dataset is cached in the right place but by processing it (applying `encode` function) seems to use a different folder because Colab HD starts to grow and it crashes when it should be done in the Drive fs. What gets me crazy, it prints it is processing/encoding the dataset in the right folder: ``` Testing the mapped function outputs Testing finished, running the mapping function on the dataset Caching processed dataset at /content/drive/My Drive/text/default-ad3e69d6242ee916/0.0.0/7e13bc0fa76783d4ef197f079dc8acfe54c3efda980f2c9adfab046ede2f0ff7/cache-b16341780a59747d.arrow ```
30
Caching processed dataset at wrong folder Hi guys, I run this on my Colab (PRO): ```python from datasets import load_dataset dataset = load_dataset('text', data_files='/content/corpus.txt', cache_dir='/content/drive/My Drive', split='train') def encode(examples): return tokenizer(examples['text'], truncation=True, padding='max_length') dataset = dataset.map(encode, batched=True) ``` The file is about 4 GB, so I cannot process it on the Colab HD because there is no enough space. So I decided to mount my Google Drive fs and do it on it. The dataset is cached in the right place but by processing it (applying `encode` function) seems to use a different folder because Colab HD starts to grow and it crashes when it should be done in the Drive fs. What gets me crazy, it prints it is processing/encoding the dataset in the right folder: ``` Testing the mapped function outputs Testing finished, running the mapping function on the dataset Caching processed dataset at /content/drive/My Drive/text/default-ad3e69d6242ee916/0.0.0/7e13bc0fa76783d4ef197f079dc8acfe54c3efda980f2c9adfab046ede2f0ff7/cache-b16341780a59747d.arrow ``` Thanks for reporting ! It uses a temporary file to write the data. However it looks like the temporary file is not placed in the right directory during the processing
https://github.com/huggingface/datasets/issues/643
Caching processed dataset at wrong folder
Well actually I just tested and the temporary file is placed in the same directory, so it should work as expected. Which version of `datasets` are you using ?
Hi guys, I run this on my Colab (PRO): ```python from datasets import load_dataset dataset = load_dataset('text', data_files='/content/corpus.txt', cache_dir='/content/drive/My Drive', split='train') def encode(examples): return tokenizer(examples['text'], truncation=True, padding='max_length') dataset = dataset.map(encode, batched=True) ``` The file is about 4 GB, so I cannot process it on the Colab HD because there is no enough space. So I decided to mount my Google Drive fs and do it on it. The dataset is cached in the right place but by processing it (applying `encode` function) seems to use a different folder because Colab HD starts to grow and it crashes when it should be done in the Drive fs. What gets me crazy, it prints it is processing/encoding the dataset in the right folder: ``` Testing the mapped function outputs Testing finished, running the mapping function on the dataset Caching processed dataset at /content/drive/My Drive/text/default-ad3e69d6242ee916/0.0.0/7e13bc0fa76783d4ef197f079dc8acfe54c3efda980f2c9adfab046ede2f0ff7/cache-b16341780a59747d.arrow ```
29
Caching processed dataset at wrong folder Hi guys, I run this on my Colab (PRO): ```python from datasets import load_dataset dataset = load_dataset('text', data_files='/content/corpus.txt', cache_dir='/content/drive/My Drive', split='train') def encode(examples): return tokenizer(examples['text'], truncation=True, padding='max_length') dataset = dataset.map(encode, batched=True) ``` The file is about 4 GB, so I cannot process it on the Colab HD because there is no enough space. So I decided to mount my Google Drive fs and do it on it. The dataset is cached in the right place but by processing it (applying `encode` function) seems to use a different folder because Colab HD starts to grow and it crashes when it should be done in the Drive fs. What gets me crazy, it prints it is processing/encoding the dataset in the right folder: ``` Testing the mapped function outputs Testing finished, running the mapping function on the dataset Caching processed dataset at /content/drive/My Drive/text/default-ad3e69d6242ee916/0.0.0/7e13bc0fa76783d4ef197f079dc8acfe54c3efda980f2c9adfab046ede2f0ff7/cache-b16341780a59747d.arrow ``` Well actually I just tested and the temporary file is placed in the same directory, so it should work as expected. Which version of `datasets` are you using ?
https://github.com/huggingface/datasets/issues/643
Caching processed dataset at wrong folder
It looks like a pyarrow issue with google colab. For some reason this code increases the disk usage of google colab while it actually writes into google drive: ```python import pyarrow as pa stream = pa.OSFile("/content/drive/My Drive/path/to/file.arrow", "wb") writer = pa.RecordBatchStreamWriter(stream, schema=pa.schema({"text": pa.string()})) writer.write_table(pa.Table.from_pydict({"text": ["a"*511 + "\n"] * ((1 << 30) // 512)})) # 1GiB writer.close() stream.close() ``` Moreover if I `rm` the file on google drive, it frees disk space on google colab.
Hi guys, I run this on my Colab (PRO): ```python from datasets import load_dataset dataset = load_dataset('text', data_files='/content/corpus.txt', cache_dir='/content/drive/My Drive', split='train') def encode(examples): return tokenizer(examples['text'], truncation=True, padding='max_length') dataset = dataset.map(encode, batched=True) ``` The file is about 4 GB, so I cannot process it on the Colab HD because there is no enough space. So I decided to mount my Google Drive fs and do it on it. The dataset is cached in the right place but by processing it (applying `encode` function) seems to use a different folder because Colab HD starts to grow and it crashes when it should be done in the Drive fs. What gets me crazy, it prints it is processing/encoding the dataset in the right folder: ``` Testing the mapped function outputs Testing finished, running the mapping function on the dataset Caching processed dataset at /content/drive/My Drive/text/default-ad3e69d6242ee916/0.0.0/7e13bc0fa76783d4ef197f079dc8acfe54c3efda980f2c9adfab046ede2f0ff7/cache-b16341780a59747d.arrow ```
74
Caching processed dataset at wrong folder Hi guys, I run this on my Colab (PRO): ```python from datasets import load_dataset dataset = load_dataset('text', data_files='/content/corpus.txt', cache_dir='/content/drive/My Drive', split='train') def encode(examples): return tokenizer(examples['text'], truncation=True, padding='max_length') dataset = dataset.map(encode, batched=True) ``` The file is about 4 GB, so I cannot process it on the Colab HD because there is no enough space. So I decided to mount my Google Drive fs and do it on it. The dataset is cached in the right place but by processing it (applying `encode` function) seems to use a different folder because Colab HD starts to grow and it crashes when it should be done in the Drive fs. What gets me crazy, it prints it is processing/encoding the dataset in the right folder: ``` Testing the mapped function outputs Testing finished, running the mapping function on the dataset Caching processed dataset at /content/drive/My Drive/text/default-ad3e69d6242ee916/0.0.0/7e13bc0fa76783d4ef197f079dc8acfe54c3efda980f2c9adfab046ede2f0ff7/cache-b16341780a59747d.arrow ``` It looks like a pyarrow issue with google colab. For some reason this code increases the disk usage of google colab while it actually writes into google drive: ```python import pyarrow as pa stream = pa.OSFile("/content/drive/My Drive/path/to/file.arrow", "wb") writer = pa.RecordBatchStreamWriter(stream, schema=pa.schema({"text": pa.string()})) writer.write_table(pa.Table.from_pydict({"text": ["a"*511 + "\n"] * ((1 << 30) // 512)})) # 1GiB writer.close() stream.close() ``` Moreover if I `rm` the file on google drive, it frees disk space on google colab.
https://github.com/huggingface/datasets/issues/643
Caching processed dataset at wrong folder
Actually I did more tests it doesn't >.< I'll let you know if I find a way to fix that
Hi guys, I run this on my Colab (PRO): ```python from datasets import load_dataset dataset = load_dataset('text', data_files='/content/corpus.txt', cache_dir='/content/drive/My Drive', split='train') def encode(examples): return tokenizer(examples['text'], truncation=True, padding='max_length') dataset = dataset.map(encode, batched=True) ``` The file is about 4 GB, so I cannot process it on the Colab HD because there is no enough space. So I decided to mount my Google Drive fs and do it on it. The dataset is cached in the right place but by processing it (applying `encode` function) seems to use a different folder because Colab HD starts to grow and it crashes when it should be done in the Drive fs. What gets me crazy, it prints it is processing/encoding the dataset in the right folder: ``` Testing the mapped function outputs Testing finished, running the mapping function on the dataset Caching processed dataset at /content/drive/My Drive/text/default-ad3e69d6242ee916/0.0.0/7e13bc0fa76783d4ef197f079dc8acfe54c3efda980f2c9adfab046ede2f0ff7/cache-b16341780a59747d.arrow ```
20
Caching processed dataset at wrong folder Hi guys, I run this on my Colab (PRO): ```python from datasets import load_dataset dataset = load_dataset('text', data_files='/content/corpus.txt', cache_dir='/content/drive/My Drive', split='train') def encode(examples): return tokenizer(examples['text'], truncation=True, padding='max_length') dataset = dataset.map(encode, batched=True) ``` The file is about 4 GB, so I cannot process it on the Colab HD because there is no enough space. So I decided to mount my Google Drive fs and do it on it. The dataset is cached in the right place but by processing it (applying `encode` function) seems to use a different folder because Colab HD starts to grow and it crashes when it should be done in the Drive fs. What gets me crazy, it prints it is processing/encoding the dataset in the right folder: ``` Testing the mapped function outputs Testing finished, running the mapping function on the dataset Caching processed dataset at /content/drive/My Drive/text/default-ad3e69d6242ee916/0.0.0/7e13bc0fa76783d4ef197f079dc8acfe54c3efda980f2c9adfab046ede2f0ff7/cache-b16341780a59747d.arrow ``` Actually I did more tests it doesn't >.< I'll let you know if I find a way to fix that
https://github.com/huggingface/datasets/issues/643
Caching processed dataset at wrong folder
Actually I also have the issue when writing a regular text file ```python f = open("/content/drive/My Drive/path/to/file", "w") f.write(("a"*511 + "\n") * ((1 << 30) // 512)) # 1GiB f.close() ``` Is that supposed to happen ?
Hi guys, I run this on my Colab (PRO): ```python from datasets import load_dataset dataset = load_dataset('text', data_files='/content/corpus.txt', cache_dir='/content/drive/My Drive', split='train') def encode(examples): return tokenizer(examples['text'], truncation=True, padding='max_length') dataset = dataset.map(encode, batched=True) ``` The file is about 4 GB, so I cannot process it on the Colab HD because there is no enough space. So I decided to mount my Google Drive fs and do it on it. The dataset is cached in the right place but by processing it (applying `encode` function) seems to use a different folder because Colab HD starts to grow and it crashes when it should be done in the Drive fs. What gets me crazy, it prints it is processing/encoding the dataset in the right folder: ``` Testing the mapped function outputs Testing finished, running the mapping function on the dataset Caching processed dataset at /content/drive/My Drive/text/default-ad3e69d6242ee916/0.0.0/7e13bc0fa76783d4ef197f079dc8acfe54c3efda980f2c9adfab046ede2f0ff7/cache-b16341780a59747d.arrow ```
37
Caching processed dataset at wrong folder Hi guys, I run this on my Colab (PRO): ```python from datasets import load_dataset dataset = load_dataset('text', data_files='/content/corpus.txt', cache_dir='/content/drive/My Drive', split='train') def encode(examples): return tokenizer(examples['text'], truncation=True, padding='max_length') dataset = dataset.map(encode, batched=True) ``` The file is about 4 GB, so I cannot process it on the Colab HD because there is no enough space. So I decided to mount my Google Drive fs and do it on it. The dataset is cached in the right place but by processing it (applying `encode` function) seems to use a different folder because Colab HD starts to grow and it crashes when it should be done in the Drive fs. What gets me crazy, it prints it is processing/encoding the dataset in the right folder: ``` Testing the mapped function outputs Testing finished, running the mapping function on the dataset Caching processed dataset at /content/drive/My Drive/text/default-ad3e69d6242ee916/0.0.0/7e13bc0fa76783d4ef197f079dc8acfe54c3efda980f2c9adfab046ede2f0ff7/cache-b16341780a59747d.arrow ``` Actually I also have the issue when writing a regular text file ```python f = open("/content/drive/My Drive/path/to/file", "w") f.write(("a"*511 + "\n") * ((1 << 30) // 512)) # 1GiB f.close() ``` Is that supposed to happen ?
https://github.com/huggingface/datasets/issues/643
Caching processed dataset at wrong folder
The code you wrote should write a 1GB file in the Google Drive folder. Doesn't it?
Hi guys, I run this on my Colab (PRO): ```python from datasets import load_dataset dataset = load_dataset('text', data_files='/content/corpus.txt', cache_dir='/content/drive/My Drive', split='train') def encode(examples): return tokenizer(examples['text'], truncation=True, padding='max_length') dataset = dataset.map(encode, batched=True) ``` The file is about 4 GB, so I cannot process it on the Colab HD because there is no enough space. So I decided to mount my Google Drive fs and do it on it. The dataset is cached in the right place but by processing it (applying `encode` function) seems to use a different folder because Colab HD starts to grow and it crashes when it should be done in the Drive fs. What gets me crazy, it prints it is processing/encoding the dataset in the right folder: ``` Testing the mapped function outputs Testing finished, running the mapping function on the dataset Caching processed dataset at /content/drive/My Drive/text/default-ad3e69d6242ee916/0.0.0/7e13bc0fa76783d4ef197f079dc8acfe54c3efda980f2c9adfab046ede2f0ff7/cache-b16341780a59747d.arrow ```
16
Caching processed dataset at wrong folder Hi guys, I run this on my Colab (PRO): ```python from datasets import load_dataset dataset = load_dataset('text', data_files='/content/corpus.txt', cache_dir='/content/drive/My Drive', split='train') def encode(examples): return tokenizer(examples['text'], truncation=True, padding='max_length') dataset = dataset.map(encode, batched=True) ``` The file is about 4 GB, so I cannot process it on the Colab HD because there is no enough space. So I decided to mount my Google Drive fs and do it on it. The dataset is cached in the right place but by processing it (applying `encode` function) seems to use a different folder because Colab HD starts to grow and it crashes when it should be done in the Drive fs. What gets me crazy, it prints it is processing/encoding the dataset in the right folder: ``` Testing the mapped function outputs Testing finished, running the mapping function on the dataset Caching processed dataset at /content/drive/My Drive/text/default-ad3e69d6242ee916/0.0.0/7e13bc0fa76783d4ef197f079dc8acfe54c3efda980f2c9adfab046ede2f0ff7/cache-b16341780a59747d.arrow ``` The code you wrote should write a 1GB file in the Google Drive folder. Doesn't it?
https://github.com/huggingface/datasets/issues/643
Caching processed dataset at wrong folder
I could check it and as you say as I write to te Drive disk the colab disk also increases...
Hi guys, I run this on my Colab (PRO): ```python from datasets import load_dataset dataset = load_dataset('text', data_files='/content/corpus.txt', cache_dir='/content/drive/My Drive', split='train') def encode(examples): return tokenizer(examples['text'], truncation=True, padding='max_length') dataset = dataset.map(encode, batched=True) ``` The file is about 4 GB, so I cannot process it on the Colab HD because there is no enough space. So I decided to mount my Google Drive fs and do it on it. The dataset is cached in the right place but by processing it (applying `encode` function) seems to use a different folder because Colab HD starts to grow and it crashes when it should be done in the Drive fs. What gets me crazy, it prints it is processing/encoding the dataset in the right folder: ``` Testing the mapped function outputs Testing finished, running the mapping function on the dataset Caching processed dataset at /content/drive/My Drive/text/default-ad3e69d6242ee916/0.0.0/7e13bc0fa76783d4ef197f079dc8acfe54c3efda980f2c9adfab046ede2f0ff7/cache-b16341780a59747d.arrow ```
20
Caching processed dataset at wrong folder Hi guys, I run this on my Colab (PRO): ```python from datasets import load_dataset dataset = load_dataset('text', data_files='/content/corpus.txt', cache_dir='/content/drive/My Drive', split='train') def encode(examples): return tokenizer(examples['text'], truncation=True, padding='max_length') dataset = dataset.map(encode, batched=True) ``` The file is about 4 GB, so I cannot process it on the Colab HD because there is no enough space. So I decided to mount my Google Drive fs and do it on it. The dataset is cached in the right place but by processing it (applying `encode` function) seems to use a different folder because Colab HD starts to grow and it crashes when it should be done in the Drive fs. What gets me crazy, it prints it is processing/encoding the dataset in the right folder: ``` Testing the mapped function outputs Testing finished, running the mapping function on the dataset Caching processed dataset at /content/drive/My Drive/text/default-ad3e69d6242ee916/0.0.0/7e13bc0fa76783d4ef197f079dc8acfe54c3efda980f2c9adfab046ede2f0ff7/cache-b16341780a59747d.arrow ``` I could check it and as you say as I write to te Drive disk the colab disk also increases...
https://github.com/huggingface/datasets/issues/643
Caching processed dataset at wrong folder
To reproduce it: ```bash !df -h | grep sda1 ``` ```python f = open("/content/drive/My Drive/test_to_remove.txt", "w") f.write(("a"*511 + "\n") * ((1 << 30) // 512)) # 1GiB f.write(("a"*511 + "\n") * ((1 << 30) // 512)) # 1GiB f.close() ``` ```bash !ls -lh /content/drive/My\ Drive/test_to_remove.txt !df -h | grep sda1 !rm -rf /content/drive/My\ Drive/test_to_remove.txt ``` [Colab](https://colab.research.google.com/drive/1D0UiweCYQwwWZ65EEhuqqbaDDbhJYXfm?usp=sharing)
Hi guys, I run this on my Colab (PRO): ```python from datasets import load_dataset dataset = load_dataset('text', data_files='/content/corpus.txt', cache_dir='/content/drive/My Drive', split='train') def encode(examples): return tokenizer(examples['text'], truncation=True, padding='max_length') dataset = dataset.map(encode, batched=True) ``` The file is about 4 GB, so I cannot process it on the Colab HD because there is no enough space. So I decided to mount my Google Drive fs and do it on it. The dataset is cached in the right place but by processing it (applying `encode` function) seems to use a different folder because Colab HD starts to grow and it crashes when it should be done in the Drive fs. What gets me crazy, it prints it is processing/encoding the dataset in the right folder: ``` Testing the mapped function outputs Testing finished, running the mapping function on the dataset Caching processed dataset at /content/drive/My Drive/text/default-ad3e69d6242ee916/0.0.0/7e13bc0fa76783d4ef197f079dc8acfe54c3efda980f2c9adfab046ede2f0ff7/cache-b16341780a59747d.arrow ```
56
Caching processed dataset at wrong folder Hi guys, I run this on my Colab (PRO): ```python from datasets import load_dataset dataset = load_dataset('text', data_files='/content/corpus.txt', cache_dir='/content/drive/My Drive', split='train') def encode(examples): return tokenizer(examples['text'], truncation=True, padding='max_length') dataset = dataset.map(encode, batched=True) ``` The file is about 4 GB, so I cannot process it on the Colab HD because there is no enough space. So I decided to mount my Google Drive fs and do it on it. The dataset is cached in the right place but by processing it (applying `encode` function) seems to use a different folder because Colab HD starts to grow and it crashes when it should be done in the Drive fs. What gets me crazy, it prints it is processing/encoding the dataset in the right folder: ``` Testing the mapped function outputs Testing finished, running the mapping function on the dataset Caching processed dataset at /content/drive/My Drive/text/default-ad3e69d6242ee916/0.0.0/7e13bc0fa76783d4ef197f079dc8acfe54c3efda980f2c9adfab046ede2f0ff7/cache-b16341780a59747d.arrow ``` To reproduce it: ```bash !df -h | grep sda1 ``` ```python f = open("/content/drive/My Drive/test_to_remove.txt", "w") f.write(("a"*511 + "\n") * ((1 << 30) // 512)) # 1GiB f.write(("a"*511 + "\n") * ((1 << 30) // 512)) # 1GiB f.close() ``` ```bash !ls -lh /content/drive/My\ Drive/test_to_remove.txt !df -h | grep sda1 !rm -rf /content/drive/My\ Drive/test_to_remove.txt ``` [Colab](https://colab.research.google.com/drive/1D0UiweCYQwwWZ65EEhuqqbaDDbhJYXfm?usp=sharing)
https://github.com/huggingface/datasets/issues/643
Caching processed dataset at wrong folder
Apparently, Colab uses a local cache of the data files read/written from Google Drive. See: - https://github.com/googlecolab/colabtools/issues/2087#issuecomment-860818457 - https://github.com/googlecolab/colabtools/issues/1915#issuecomment-804234540 - https://github.com/googlecolab/colabtools/issues/2147#issuecomment-885052636
Hi guys, I run this on my Colab (PRO): ```python from datasets import load_dataset dataset = load_dataset('text', data_files='/content/corpus.txt', cache_dir='/content/drive/My Drive', split='train') def encode(examples): return tokenizer(examples['text'], truncation=True, padding='max_length') dataset = dataset.map(encode, batched=True) ``` The file is about 4 GB, so I cannot process it on the Colab HD because there is no enough space. So I decided to mount my Google Drive fs and do it on it. The dataset is cached in the right place but by processing it (applying `encode` function) seems to use a different folder because Colab HD starts to grow and it crashes when it should be done in the Drive fs. What gets me crazy, it prints it is processing/encoding the dataset in the right folder: ``` Testing the mapped function outputs Testing finished, running the mapping function on the dataset Caching processed dataset at /content/drive/My Drive/text/default-ad3e69d6242ee916/0.0.0/7e13bc0fa76783d4ef197f079dc8acfe54c3efda980f2c9adfab046ede2f0ff7/cache-b16341780a59747d.arrow ```
21
Caching processed dataset at wrong folder Hi guys, I run this on my Colab (PRO): ```python from datasets import load_dataset dataset = load_dataset('text', data_files='/content/corpus.txt', cache_dir='/content/drive/My Drive', split='train') def encode(examples): return tokenizer(examples['text'], truncation=True, padding='max_length') dataset = dataset.map(encode, batched=True) ``` The file is about 4 GB, so I cannot process it on the Colab HD because there is no enough space. So I decided to mount my Google Drive fs and do it on it. The dataset is cached in the right place but by processing it (applying `encode` function) seems to use a different folder because Colab HD starts to grow and it crashes when it should be done in the Drive fs. What gets me crazy, it prints it is processing/encoding the dataset in the right folder: ``` Testing the mapped function outputs Testing finished, running the mapping function on the dataset Caching processed dataset at /content/drive/My Drive/text/default-ad3e69d6242ee916/0.0.0/7e13bc0fa76783d4ef197f079dc8acfe54c3efda980f2c9adfab046ede2f0ff7/cache-b16341780a59747d.arrow ``` Apparently, Colab uses a local cache of the data files read/written from Google Drive. See: - https://github.com/googlecolab/colabtools/issues/2087#issuecomment-860818457 - https://github.com/googlecolab/colabtools/issues/1915#issuecomment-804234540 - https://github.com/googlecolab/colabtools/issues/2147#issuecomment-885052636
https://github.com/huggingface/datasets/issues/633
Load large text file for LM pre-training resulting in OOM
Not sure what could cause that on the `datasets` side. Could this be a `Trainer` issue ? cc @julien-c @sgugger ?
I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks.
21
Load large text file for LM pre-training resulting in OOM I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks. Not sure what could cause that on the `datasets` side. Could this be a `Trainer` issue ? cc @julien-c @sgugger ?
https://github.com/huggingface/datasets/issues/633
Load large text file for LM pre-training resulting in OOM
There was a memory leak issue fixed recently in master. You should install from source and see if it fixes your problem.
I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks.
22
Load large text file for LM pre-training resulting in OOM I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks. There was a memory leak issue fixed recently in master. You should install from source and see if it fixes your problem.
https://github.com/huggingface/datasets/issues/633
Load large text file for LM pre-training resulting in OOM
@lhoestq @sgugger Thanks for your comments. I have install from source code as you told, but the problem is still there. To reproduce the issue, just replace [these lines](https://github.com/huggingface/transformers/blob/master/examples/language-modeling/run_language_modeling.py#L241-L258) with: (load_dataset and DataCollatorForDatasetsLanguageModeling as [above mentioned](https://github.com/huggingface/datasets/issues/633#issue-702440484)) ```python dataset = load_dataset("bookcorpus") dataset = dataset.train_test_split(test_size=0.1) train_dataset = dataset['train'] eval_dataset = dataset['test'] if training_args.do_eval else None data_collator = DataCollatorForDatasetsLanguageModeling( tokenizer=tokenizer, mlm=data_args.mlm, mlm_probability=data_args.mlm_probability, block_size=data_args.block_size ) ``` and run by: ```bash python run_language_modeling.py --output_dir=output \ --model_type=bert \ --model_name_or_path=bert-base-uncased \ --do_train \ --do_eval \ --mlm ```
I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks.
80
Load large text file for LM pre-training resulting in OOM I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks. @lhoestq @sgugger Thanks for your comments. I have install from source code as you told, but the problem is still there. To reproduce the issue, just replace [these lines](https://github.com/huggingface/transformers/blob/master/examples/language-modeling/run_language_modeling.py#L241-L258) with: (load_dataset and DataCollatorForDatasetsLanguageModeling as [above mentioned](https://github.com/huggingface/datasets/issues/633#issue-702440484)) ```python dataset = load_dataset("bookcorpus") dataset = dataset.train_test_split(test_size=0.1) train_dataset = dataset['train'] eval_dataset = dataset['test'] if training_args.do_eval else None data_collator = DataCollatorForDatasetsLanguageModeling( tokenizer=tokenizer, mlm=data_args.mlm, mlm_probability=data_args.mlm_probability, block_size=data_args.block_size ) ``` and run by: ```bash python run_language_modeling.py --output_dir=output \ --model_type=bert \ --model_name_or_path=bert-base-uncased \ --do_train \ --do_eval \ --mlm ```
https://github.com/huggingface/datasets/issues/633
Load large text file for LM pre-training resulting in OOM
Same here. Pre-training on wikitext-103 to do some test. At the end of the training it takes 32GB of RAM + ~30GB of SWAP. I installed dataset==1.1.0, not built from source. I will try uninstalling and building from source when it finish.
I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks.
42
Load large text file for LM pre-training resulting in OOM I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks. Same here. Pre-training on wikitext-103 to do some test. At the end of the training it takes 32GB of RAM + ~30GB of SWAP. I installed dataset==1.1.0, not built from source. I will try uninstalling and building from source when it finish.
https://github.com/huggingface/datasets/issues/633
Load large text file for LM pre-training resulting in OOM
This seems to be on the `transformers` library side. If you have more informations (pip env) or even better, a colab reproducing the error we can investigate.
I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks.
27
Load large text file for LM pre-training resulting in OOM I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks. This seems to be on the `transformers` library side. If you have more informations (pip env) or even better, a colab reproducing the error we can investigate.
https://github.com/huggingface/datasets/issues/633
Load large text file for LM pre-training resulting in OOM
It seems like it's solved with freshed versions of transformers. I have tried to replicate the error doing a fresh pip install transformers & datasets on colab and the error doesn't continue. On colab it keeps stable on 5GB! (Y) Edit: **Thanks for your great work**. Have a good day.
I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks.
50
Load large text file for LM pre-training resulting in OOM I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks. It seems like it's solved with freshed versions of transformers. I have tried to replicate the error doing a fresh pip install transformers & datasets on colab and the error doesn't continue. On colab it keeps stable on 5GB! (Y) Edit: **Thanks for your great work**. Have a good day.
https://github.com/huggingface/datasets/issues/633
Load large text file for LM pre-training resulting in OOM
@gaceladri witch version transformers and datasets are you using now? I want to try again. Thanks.
I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks.
16
Load large text file for LM pre-training resulting in OOM I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks. @gaceladri witch version transformers and datasets are you using now? I want to try again. Thanks.
https://github.com/huggingface/datasets/issues/633
Load large text file for LM pre-training resulting in OOM
It's happening to me again. After 4 hours of pre-training, my ram memory gets full and the kernel dies. I am using the last transformers version as today. 4.4.0 and the last version of datasets 1.2.1, both installed from master. The memory consumption keeps increasing.
I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks.
45
Load large text file for LM pre-training resulting in OOM I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks. It's happening to me again. After 4 hours of pre-training, my ram memory gets full and the kernel dies. I am using the last transformers version as today. 4.4.0 and the last version of datasets 1.2.1, both installed from master. The memory consumption keeps increasing.
https://github.com/huggingface/datasets/issues/633
Load large text file for LM pre-training resulting in OOM
Thanks for the investigation @gaceladri Apparently this happens when `num_workers>0` and has to do with objects being copied-on-write. Did you try setting num_workers to 0 @gaceladri ? If the issue doesn't happen with `num_workers=0` then this would confirm that it's indeed related to this python/pytorch issue. Since a `Dataset` object is a wrapper of a pyarrow Table, we should investigate if the data being copied comes from the Table itself or from metadata in the `Dataset` object. If it comes from the metadata in the `Dataset` object, we should be able to implement a workaround. But if it comes from the Table, we'll need to see with the pyarrow team what we can do...
I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks.
114
Load large text file for LM pre-training resulting in OOM I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks. Thanks for the investigation @gaceladri Apparently this happens when `num_workers>0` and has to do with objects being copied-on-write. Did you try setting num_workers to 0 @gaceladri ? If the issue doesn't happen with `num_workers=0` then this would confirm that it's indeed related to this python/pytorch issue. Since a `Dataset` object is a wrapper of a pyarrow Table, we should investigate if the data being copied comes from the Table itself or from metadata in the `Dataset` object. If it comes from the metadata in the `Dataset` object, we should be able to implement a workaround. But if it comes from the Table, we'll need to see with the pyarrow team what we can do...
https://github.com/huggingface/datasets/issues/633
Load large text file for LM pre-training resulting in OOM
Hmmm so this might come from another issue... Since it doesn't seem to be related to multiprocessing it should be easier to investigate though. Do you have some ideas @gaceladri ?
I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks.
31
Load large text file for LM pre-training resulting in OOM I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks. Hmmm so this might come from another issue... Since it doesn't seem to be related to multiprocessing it should be easier to investigate though. Do you have some ideas @gaceladri ?
https://github.com/huggingface/datasets/issues/633
Load large text file for LM pre-training resulting in OOM
@lhoestq I looked quickly to a previously spoted bug in my env wandb /sdk/interface/interface.py, because sometimes when I load the dataset I got a multiprocessing error at line 510 in wandb...interface.py This bug is reported here https://github.com/huggingface/datasets/issues/847 ``` --------------------------------------------------------------------------- AssertionError Traceback (most recent call last) <timed eval> in <module> ~/anaconda3/envs/tfm/lib/python3.6/site-packages/transformers/trainer.py in train(self, model_path, trial) 877 print(len(epoch_iterator)) 878 --> 879 for step, inputs in enumerate(epoch_iterator): 880 881 start_step = time.time() ~/anaconda3/envs/tfm/lib/python3.6/site-packages/torch/utils/data/dataloader.py in __next__(self) 433 if self._sampler_iter is None: 434 self._reset() --> 435 data = self._next_data() 436 self._num_yielded += 1 437 if self._dataset_kind == _DatasetKind.Iterable and \ ~/anaconda3/envs/tfm/lib/python3.6/site-packages/torch/utils/data/dataloader.py in _next_data(self) 1083 else: 1084 del self._task_info[idx] -> 1085 return self._process_data(data) 1086 1087 def _try_put_index(self): ~/anaconda3/envs/tfm/lib/python3.6/site-packages/torch/utils/data/dataloader.py in _process_data(self, data) 1109 self._try_put_index() 1110 if isinstance(data, ExceptionWrapper): -> 1111 data.reraise() 1112 return data 1113 ~/anaconda3/envs/tfm/lib/python3.6/site-packages/torch/_utils.py in reraise(self) 426 # have message field 427 raise self.exc_type(message=msg) --> 428 raise self.exc_type(msg) 429 430 AssertionError: Caught AssertionError in DataLoader worker process 0. Original Traceback (most recent call last): File "/home/ad/anaconda3/envs/tfm/lib/python3.6/site-packages/torch/utils/data/_utils/worker.py", line 198, in _worker_loop data = fetcher.fetch(index) File "/home/ad/anaconda3/envs/tfm/lib/python3.6/site-packages/torch/utils/data/_utils/fetch.py", line 44, in fetch data = [self.dataset[idx] for idx in possibly_batched_index] File "/home/ad/anaconda3/envs/tfm/lib/python3.6/site-packages/torch/utils/data/_utils/fetch.py", line 44, in <listcomp> data = [self.dataset[idx] for idx in possibly_batched_index] File "/home/ad/anaconda3/envs/tfm/lib/python3.6/site-packages/datasets/arrow_dataset.py", line 1083, in __getitem__ format_kwargs=self._format_kwargs, File "/home/ad/anaconda3/envs/tfm/lib/python3.6/site-packages/datasets/arrow_dataset.py", line 1070, in _getitem format_kwargs=format_kwargs, File "/home/ad/anaconda3/envs/tfm/lib/python3.6/site-packages/datasets/arrow_dataset.py", line 886, in _convert_outputs v = map_nested(command, v, **map_nested_kwargs) File "/home/ad/anaconda3/envs/tfm/lib/python3.6/site-packages/datasets/utils/py_utils.py", line 216, in map_nested return function(data_struct) File "/home/ad/anaconda3/envs/tfm/lib/python3.6/site-packages/datasets/arrow_dataset.py", line 847, in command return torch.tensor(x, **format_kwargs) File "/home/ad/anaconda3/envs/tfm/lib/python3.6/warnings.py", line 101, in _showwarnmsg _showwarnmsg_impl(msg) File "/home/ad/anaconda3/envs/tfm/lib/python3.6/warnings.py", line 30, in _showwarnmsg_impl file.write(text) File "/home/ad/anaconda3/envs/tfm/lib/python3.6/site-packages/wandb/sdk/lib/redirect.py", line 100, in new_write cb(name, data) File "/home/ad/anaconda3/envs/tfm/lib/python3.6/site-packages/wandb/sdk/wandb_run.py", line 729, in _console_callback self._backend.interface.publish_output(name, data) File "/home/ad/anaconda3/envs/tfm/lib/python3.6/site-packages/wandb/sdk/interface/interface.py", line 186, in publish_output self._publish_output(o) File "/home/ad/anaconda3/envs/tfm/lib/python3.6/site-packages/wandb/sdk/interface/interface.py", line 191, in _publish_output self._publish(rec) File "/home/ad/anaconda3/envs/tfm/lib/python3.6/site-packages/wandb/sdk/interface/interface.py", line 510, in _publish if self._process and not self._process.is_alive(): File "/home/ad/anaconda3/envs/tfm/lib/python3.6/multiprocessing/process.py", line 134, in is_alive assert self._parent_pid == os.getpid(), 'can only test a child process' AssertionError: can only test a child process ``` My workaround was to just comment those lines without looking to much into consecuences: ``` def _publish(self, record: pb.Record, local: bool = None) -> None: #if self._process and not self._process.is_alive(): # raise Exception("The wandb backend process has shutdown") ``` It worked so far... I need to try running without wandb and see if it could be causing something wrong with multiprocessing. I am going to try to launch the training setting wandb to false and I will let you know again.
I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks.
396
Load large text file for LM pre-training resulting in OOM I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks. @lhoestq I looked quickly to a previously spoted bug in my env wandb /sdk/interface/interface.py, because sometimes when I load the dataset I got a multiprocessing error at line 510 in wandb...interface.py This bug is reported here https://github.com/huggingface/datasets/issues/847 ``` --------------------------------------------------------------------------- AssertionError Traceback (most recent call last) <timed eval> in <module> ~/anaconda3/envs/tfm/lib/python3.6/site-packages/transformers/trainer.py in train(self, model_path, trial) 877 print(len(epoch_iterator)) 878 --> 879 for step, inputs in enumerate(epoch_iterator): 880 881 start_step = time.time() ~/anaconda3/envs/tfm/lib/python3.6/site-packages/torch/utils/data/dataloader.py in __next__(self) 433 if self._sampler_iter is None: 434 self._reset() --> 435 data = self._next_data() 436 self._num_yielded += 1 437 if self._dataset_kind == _DatasetKind.Iterable and \ ~/anaconda3/envs/tfm/lib/python3.6/site-packages/torch/utils/data/dataloader.py in _next_data(self) 1083 else: 1084 del self._task_info[idx] -> 1085 return self._process_data(data) 1086 1087 def _try_put_index(self): ~/anaconda3/envs/tfm/lib/python3.6/site-packages/torch/utils/data/dataloader.py in _process_data(self, data) 1109 self._try_put_index() 1110 if isinstance(data, ExceptionWrapper): -> 1111 data.reraise() 1112 return data 1113 ~/anaconda3/envs/tfm/lib/python3.6/site-packages/torch/_utils.py in reraise(self) 426 # have message field 427 raise self.exc_type(message=msg) --> 428 raise self.exc_type(msg) 429 430 AssertionError: Caught AssertionError in DataLoader worker process 0. Original Traceback (most recent call last): File "/home/ad/anaconda3/envs/tfm/lib/python3.6/site-packages/torch/utils/data/_utils/worker.py", line 198, in _worker_loop data = fetcher.fetch(index) File "/home/ad/anaconda3/envs/tfm/lib/python3.6/site-packages/torch/utils/data/_utils/fetch.py", line 44, in fetch data = [self.dataset[idx] for idx in possibly_batched_index] File "/home/ad/anaconda3/envs/tfm/lib/python3.6/site-packages/torch/utils/data/_utils/fetch.py", line 44, in <listcomp> data = [self.dataset[idx] for idx in possibly_batched_index] File "/home/ad/anaconda3/envs/tfm/lib/python3.6/site-packages/datasets/arrow_dataset.py", line 1083, in __getitem__ format_kwargs=self._format_kwargs, File "/home/ad/anaconda3/envs/tfm/lib/python3.6/site-packages/datasets/arrow_dataset.py", line 1070, in _getitem format_kwargs=format_kwargs, File "/home/ad/anaconda3/envs/tfm/lib/python3.6/site-packages/datasets/arrow_dataset.py", line 886, in _convert_outputs v = map_nested(command, v, **map_nested_kwargs) File "/home/ad/anaconda3/envs/tfm/lib/python3.6/site-packages/datasets/utils/py_utils.py", line 216, in map_nested return function(data_struct) File "/home/ad/anaconda3/envs/tfm/lib/python3.6/site-packages/datasets/arrow_dataset.py", line 847, in command return torch.tensor(x, **format_kwargs) File "/home/ad/anaconda3/envs/tfm/lib/python3.6/warnings.py", line 101, in _showwarnmsg _showwarnmsg_impl(msg) File "/home/ad/anaconda3/envs/tfm/lib/python3.6/warnings.py", line 30, in _showwarnmsg_impl file.write(text) File "/home/ad/anaconda3/envs/tfm/lib/python3.6/site-packages/wandb/sdk/lib/redirect.py", line 100, in new_write cb(name, data) File "/home/ad/anaconda3/envs/tfm/lib/python3.6/site-packages/wandb/sdk/wandb_run.py", line 729, in _console_callback self._backend.interface.publish_output(name, data) File "/home/ad/anaconda3/envs/tfm/lib/python3.6/site-packages/wandb/sdk/interface/interface.py", line 186, in publish_output self._publish_output(o) File "/home/ad/anaconda3/envs/tfm/lib/python3.6/site-packages/wandb/sdk/interface/interface.py", line 191, in _publish_output self._publish(rec) File "/home/ad/anaconda3/envs/tfm/lib/python3.6/site-packages/wandb/sdk/interface/interface.py", line 510, in _publish if self._process and not self._process.is_alive(): File "/home/ad/anaconda3/envs/tfm/lib/python3.6/multiprocessing/process.py", line 134, in is_alive assert self._parent_pid == os.getpid(), 'can only test a child process' AssertionError: can only test a child process ``` My workaround was to just comment those lines without looking to much into consecuences: ``` def _publish(self, record: pb.Record, local: bool = None) -> None: #if self._process and not self._process.is_alive(): # raise Exception("The wandb backend process has shutdown") ``` It worked so far... I need to try running without wandb and see if it could be causing something wrong with multiprocessing. I am going to try to launch the training setting wandb to false and I will let you know again.
https://github.com/huggingface/datasets/issues/633
Load large text file for LM pre-training resulting in OOM
@lhoestq But despite this, I got lost into the [class Dataset()](https://huggingface.co/docs/datasets/_modules/datasets/arrow_dataset.html#Dataset) reading the pyarrow files. Edit: but you should be rigth, that it does not have to be related to multiprocessing since it keeps happening when `num_workers=0`
I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks.
37
Load large text file for LM pre-training resulting in OOM I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks. @lhoestq But despite this, I got lost into the [class Dataset()](https://huggingface.co/docs/datasets/_modules/datasets/arrow_dataset.html#Dataset) reading the pyarrow files. Edit: but you should be rigth, that it does not have to be related to multiprocessing since it keeps happening when `num_workers=0`
https://github.com/huggingface/datasets/issues/633
Load large text file for LM pre-training resulting in OOM
Or maybe wandb uses multiprocessing ? One process for wandb logging and one for actual training ? If this is the case then even setting `num_workers=0` would cause the process to be forked for wandb and therefore cause the memory issue.
I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks.
41
Load large text file for LM pre-training resulting in OOM I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks. Or maybe wandb uses multiprocessing ? One process for wandb logging and one for actual training ? If this is the case then even setting `num_workers=0` would cause the process to be forked for wandb and therefore cause the memory issue.
https://github.com/huggingface/datasets/issues/633
Load large text file for LM pre-training resulting in OOM
@lhoestq could be, but if we set wandb to false this should not happen. I am going to try.
I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks.
19
Load large text file for LM pre-training resulting in OOM I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks. @lhoestq could be, but if we set wandb to false this should not happen. I am going to try.
https://github.com/huggingface/datasets/issues/633
Load large text file for LM pre-training resulting in OOM
@lhoestq It keeps happening. I have uninstalled wandb from my env, setted `%env WANDB_DISABLED=true` on my notebook, and commented this func: ``` def get_available_reporting_integrations(): integrations = [] if is_azureml_available(): integrations.append("azure_ml") if is_comet_available(): integrations.append("comet_ml") if is_mlflow_available(): integrations.append("mlflow") if is_tensorboard_available(): integrations.append("tensorboard") # if is_wandb_available(): # integrations.append("wandb") return integrations ``` As a fast test and it keeps increasing the ram memory. Wandb could not be the blameworthy here.
I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks.
65
Load large text file for LM pre-training resulting in OOM I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks. @lhoestq It keeps happening. I have uninstalled wandb from my env, setted `%env WANDB_DISABLED=true` on my notebook, and commented this func: ``` def get_available_reporting_integrations(): integrations = [] if is_azureml_available(): integrations.append("azure_ml") if is_comet_available(): integrations.append("comet_ml") if is_mlflow_available(): integrations.append("mlflow") if is_tensorboard_available(): integrations.append("tensorboard") # if is_wandb_available(): # integrations.append("wandb") return integrations ``` As a fast test and it keeps increasing the ram memory. Wandb could not be the blameworthy here.
https://github.com/huggingface/datasets/issues/633
Load large text file for LM pre-training resulting in OOM
Thanks for checking @gaceladri . Let's investigate the single process setting then. If you have some sort of colab notebook with a minimal code example that shows this behavior feel free to share it @gaceladri so that we can play around with it to find what causes this. Otherwise I'll probably try to reproduce on my side at one point
I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks.
60
Load large text file for LM pre-training resulting in OOM I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks. Thanks for checking @gaceladri . Let's investigate the single process setting then. If you have some sort of colab notebook with a minimal code example that shows this behavior feel free to share it @gaceladri so that we can play around with it to find what causes this. Otherwise I'll probably try to reproduce on my side at one point
https://github.com/huggingface/datasets/issues/633
Load large text file for LM pre-training resulting in OOM
@lhoestq sure. Here you have https://colab.research.google.com/drive/1ba09ZOpyHGAOQLcsxiQAHRXl10qnMU5o?usp=sharing let me know if the link works and it reproduces the issue. To me, it reproduces the issue, since if you start the training the ram memory keeps increasing. Let me know. Thanks!
I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks.
39
Load large text file for LM pre-training resulting in OOM I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks. @lhoestq sure. Here you have https://colab.research.google.com/drive/1ba09ZOpyHGAOQLcsxiQAHRXl10qnMU5o?usp=sharing let me know if the link works and it reproduces the issue. To me, it reproduces the issue, since if you start the training the ram memory keeps increasing. Let me know. Thanks!
https://github.com/huggingface/datasets/issues/633
Load large text file for LM pre-training resulting in OOM
Could the bug be comming from tokenizers? I got this warning at the terminal from my jupyter notebook: ``` huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks... To disable this warning, you can either: - Avoid using `tokenizers` before the fork if possible - Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false) ```
I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks.
63
Load large text file for LM pre-training resulting in OOM I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks. Could the bug be comming from tokenizers? I got this warning at the terminal from my jupyter notebook: ``` huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks... To disable this warning, you can either: - Avoid using `tokenizers` before the fork if possible - Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false) ```
https://github.com/huggingface/datasets/issues/633
Load large text file for LM pre-training resulting in OOM
I've never experienced memory issues with tokenizers so I don't know Cc @n1t0 are you aware of any issue that would cause memory to keep increasing when the tokenizer is used in the Data Collator for language modeling ?
I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks.
39
Load large text file for LM pre-training resulting in OOM I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks. I've never experienced memory issues with tokenizers so I don't know Cc @n1t0 are you aware of any issue that would cause memory to keep increasing when the tokenizer is used in the Data Collator for language modeling ?
https://github.com/huggingface/datasets/issues/633
Load large text file for LM pre-training resulting in OOM
@lhoestq Thanks for pointing to n1t0, just to clarify. That warning was doing fine-tuning, without collator: ``` from datasets import load_dataset, load_metric import numpy as np GLUE_TASKS = [ "cola", "mnli", "mnli-mm", "mrpc", "qnli", "qqp", "rte", "sst2", "stsb", "wnli", ] task = "mnli" actual_task = "mnli" if task == "mnli-mm" else task dataset = load_dataset("glue", actual_task) metric = load_metric("glue", actual_task) batch_size = 16 attention_type = "linear" from transformers.models.mobilebert_mod import ( MobileBertForSequenceClassification, MobileBertTokenizerFast, ) from transformers.models.mobilebert_mod.configuration_mobilebert import ( MobileBertConfigMod, ) from transformers import TrainingArguments, Trainer num_labels = 3 if task.startswith("mnli") else 1 if task == "stsb" else 2 tokenizer = MobileBertTokenizerFast.from_pretrained( "/media/ad/00b5422b-9d54-4449-8b5d-08eab5cdac8c/training_trfm/big_linear_layerdrop_shared/checkpoint-23000/", max_len=512, ) model = MobileBertForSequenceClassification.from_pretrained( "/media/ad/00b5422b-9d54-4449-8b5d-08eab5cdac8c/training_trfm/big_linear_layerdrop_shared/checkpoint-23000/", num_labels=num_labels, ) print(model.num_parameters()) task_to_keys = { "cola": ("sentence", None), "mnli": ("premise", "hypothesis"), "mnli-mm": ("premise", "hypothesis"), "mrpc": ("sentence1", "sentence2"), "qnli": ("question", "sentence"), "qqp": ("question1", "question2"), "rte": ("sentence1", "sentence2"), "sst2": ("sentence", None), "stsb": ("sentence1", "sentence2"), "wnli": ("sentence1", "sentence2"), } sentence1_key, sentence2_key = task_to_keys[task] if sentence2_key is None: print(f"Sentence: {dataset['train'][0][sentence1_key]}") else: print(f"Sentence 1: {dataset['train'][0][sentence1_key]}") print(f"Sentence 2: {dataset['train'][0][sentence2_key]}") def preprocess_function(examples): if sentence2_key is None: return tokenizer(examples[sentence1_key], truncation=True) return tokenizer(examples[sentence1_key], examples[sentence2_key], truncation=True) encoded_dataset = dataset.map(preprocess_function, batched=True) metric_name = ( "pearson" if task == "stsb" else "matthews_correlation" if task == "cola" else "accuracy" ) args = TrainingArguments( f"test-glue/{task}_{attention_type}", evaluation_strategy="steps", learning_rate=1e-5, per_device_train_batch_size=batch_size, per_device_eval_batch_size=batch_size, logging_steps=200, num_train_epochs=5, gradient_accumulation_steps=1, warmup_steps=10000, fp16=True, dataloader_num_workers=10, weight_decay=0.1, load_best_model_at_end=True, metric_for_best_model=metric_name, ) def compute_metrics(eval_pred): predictions, labels = eval_pred if task != "stsb": predictions = np.argmax(predictions, axis=1) else: predictions = predictions[:, 0] return metric.compute(predictions=predictions, references=labels) validation_key = ( "validation_mismatched" if task == "mnli-mm" else "validation_matched" if task == "mnli" else "validation" ) trainer = Trainer( model, args, train_dataset=encoded_dataset["train"], eval_dataset=encoded_dataset[validation_key], tokenizer=tokenizer, compute_metrics=compute_metrics, ) trainer.train() ``` Now, I have come back to pre-training. The changes that I think I have done are: not formatting the dataset to torch: ~~`big_dataset.set_format(type='torch', columns=["text", "input_ids", "attention_mask", "token_type_ids"])`~~ so maybe some column is dropped and not freezed in memory and now I have not setted any validation dataset in the trainer. My validation dataset before: ``` book_corpus_eval = load_dataset( "bookcorpus", "plain_text", cache_dir="/home/ad/Desktop/bookcorpus", split="train[98:99%]", ) book_corpus_eval = book_corpus_eval.map(encode, batched=True) book_corpus_eval.set_format( type="torch", columns=["text", "input_ids", "attention_mask", "token_type_ids"] ) **book_corpus_eval = book_corpus_eval.select([i for i in range(1500)])** ``` Maybe _selecting_ or indexing the dataset before feeding it to the trainer, do something strange. My trainer now: ``` big_dataset = load_from_disk("/home/ad/Desktop/35percent_data.arrow/") from transformers import DataCollatorForWholeWordMask data_collator = DataCollatorForWholeWordMask( tokenizer=tokenizer, mlm=True, mlm_probability=0.15) from transformers import Trainer, TrainingArguments training_args = TrainingArguments( output_dir="./big_linear_layerdrop_shared_silu_secondtry", overwrite_output_dir=True, per_device_train_batch_size=60, per_device_eval_batch_size=60, save_steps=500, save_total_limit=10, logging_first_step=True, logging_steps=100, # evaluation_strategy='steps', # eval_steps=250, gradient_accumulation_steps=8, fp16=True, dataloader_num_workers=10, warmup_steps=15000, learning_rate=6e-4, adam_epsilon=1e-6, adam_beta2=0.98, weight_decay=0.01, max_grad_norm=1.0, max_steps=500000, ) trainer = Trainer( model=model, args=training_args, data_collator=data_collator, train_dataset=big_dataset, # eval_dataset=book_corpus_eval, tokenizer=tokenizer) import wandb wandb.login() trainer.train() ``` And surprisingly, the ram now keeps going up and down. The training is up now for 12h without collapse the ram. I don't know what could cause the leakage. :mag: Edit: I didn't see the swap memory, that keeps increasing. So the problem persist.
I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks.
468
Load large text file for LM pre-training resulting in OOM I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks. @lhoestq Thanks for pointing to n1t0, just to clarify. That warning was doing fine-tuning, without collator: ``` from datasets import load_dataset, load_metric import numpy as np GLUE_TASKS = [ "cola", "mnli", "mnli-mm", "mrpc", "qnli", "qqp", "rte", "sst2", "stsb", "wnli", ] task = "mnli" actual_task = "mnli" if task == "mnli-mm" else task dataset = load_dataset("glue", actual_task) metric = load_metric("glue", actual_task) batch_size = 16 attention_type = "linear" from transformers.models.mobilebert_mod import ( MobileBertForSequenceClassification, MobileBertTokenizerFast, ) from transformers.models.mobilebert_mod.configuration_mobilebert import ( MobileBertConfigMod, ) from transformers import TrainingArguments, Trainer num_labels = 3 if task.startswith("mnli") else 1 if task == "stsb" else 2 tokenizer = MobileBertTokenizerFast.from_pretrained( "/media/ad/00b5422b-9d54-4449-8b5d-08eab5cdac8c/training_trfm/big_linear_layerdrop_shared/checkpoint-23000/", max_len=512, ) model = MobileBertForSequenceClassification.from_pretrained( "/media/ad/00b5422b-9d54-4449-8b5d-08eab5cdac8c/training_trfm/big_linear_layerdrop_shared/checkpoint-23000/", num_labels=num_labels, ) print(model.num_parameters()) task_to_keys = { "cola": ("sentence", None), "mnli": ("premise", "hypothesis"), "mnli-mm": ("premise", "hypothesis"), "mrpc": ("sentence1", "sentence2"), "qnli": ("question", "sentence"), "qqp": ("question1", "question2"), "rte": ("sentence1", "sentence2"), "sst2": ("sentence", None), "stsb": ("sentence1", "sentence2"), "wnli": ("sentence1", "sentence2"), } sentence1_key, sentence2_key = task_to_keys[task] if sentence2_key is None: print(f"Sentence: {dataset['train'][0][sentence1_key]}") else: print(f"Sentence 1: {dataset['train'][0][sentence1_key]}") print(f"Sentence 2: {dataset['train'][0][sentence2_key]}") def preprocess_function(examples): if sentence2_key is None: return tokenizer(examples[sentence1_key], truncation=True) return tokenizer(examples[sentence1_key], examples[sentence2_key], truncation=True) encoded_dataset = dataset.map(preprocess_function, batched=True) metric_name = ( "pearson" if task == "stsb" else "matthews_correlation" if task == "cola" else "accuracy" ) args = TrainingArguments( f"test-glue/{task}_{attention_type}", evaluation_strategy="steps", learning_rate=1e-5, per_device_train_batch_size=batch_size, per_device_eval_batch_size=batch_size, logging_steps=200, num_train_epochs=5, gradient_accumulation_steps=1, warmup_steps=10000, fp16=True, dataloader_num_workers=10, weight_decay=0.1, load_best_model_at_end=True, metric_for_best_model=metric_name, ) def compute_metrics(eval_pred): predictions, labels = eval_pred if task != "stsb": predictions = np.argmax(predictions, axis=1) else: predictions = predictions[:, 0] return metric.compute(predictions=predictions, references=labels) validation_key = ( "validation_mismatched" if task == "mnli-mm" else "validation_matched" if task == "mnli" else "validation" ) trainer = Trainer( model, args, train_dataset=encoded_dataset["train"], eval_dataset=encoded_dataset[validation_key], tokenizer=tokenizer, compute_metrics=compute_metrics, ) trainer.train() ``` Now, I have come back to pre-training. The changes that I think I have done are: not formatting the dataset to torch: ~~`big_dataset.set_format(type='torch', columns=["text", "input_ids", "attention_mask", "token_type_ids"])`~~ so maybe some column is dropped and not freezed in memory and now I have not setted any validation dataset in the trainer. My validation dataset before: ``` book_corpus_eval = load_dataset( "bookcorpus", "plain_text", cache_dir="/home/ad/Desktop/bookcorpus", split="train[98:99%]", ) book_corpus_eval = book_corpus_eval.map(encode, batched=True) book_corpus_eval.set_format( type="torch", columns=["text", "input_ids", "attention_mask", "token_type_ids"] ) **book_corpus_eval = book_corpus_eval.select([i for i in range(1500)])** ``` Maybe _selecting_ or indexing the dataset before feeding it to the trainer, do something strange. My trainer now: ``` big_dataset = load_from_disk("/home/ad/Desktop/35percent_data.arrow/") from transformers import DataCollatorForWholeWordMask data_collator = DataCollatorForWholeWordMask( tokenizer=tokenizer, mlm=True, mlm_probability=0.15) from transformers import Trainer, TrainingArguments training_args = TrainingArguments( output_dir="./big_linear_layerdrop_shared_silu_secondtry", overwrite_output_dir=True, per_device_train_batch_size=60, per_device_eval_batch_size=60, save_steps=500, save_total_limit=10, logging_first_step=True, logging_steps=100, # evaluation_strategy='steps', # eval_steps=250, gradient_accumulation_steps=8, fp16=True, dataloader_num_workers=10, warmup_steps=15000, learning_rate=6e-4, adam_epsilon=1e-6, adam_beta2=0.98, weight_decay=0.01, max_grad_norm=1.0, max_steps=500000, ) trainer = Trainer( model=model, args=training_args, data_collator=data_collator, train_dataset=big_dataset, # eval_dataset=book_corpus_eval, tokenizer=tokenizer) import wandb wandb.login() trainer.train() ``` And surprisingly, the ram now keeps going up and down. The training is up now for 12h without collapse the ram. I don't know what could cause the leakage. :mag: Edit: I didn't see the swap memory, that keeps increasing. So the problem persist.
https://github.com/huggingface/datasets/issues/633
Load large text file for LM pre-training resulting in OOM
Thanks for sharing your results. So you still had the issue for fine-tuning ? And the issue still appears with a bare-bone dataset from an arrow file...
I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks.
27
Load large text file for LM pre-training resulting in OOM I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks. Thanks for sharing your results. So you still had the issue for fine-tuning ? And the issue still appears with a bare-bone dataset from an arrow file...
https://github.com/huggingface/datasets/issues/633
Load large text file for LM pre-training resulting in OOM
Yes, on both cases. Fine-tuning a pre-trained model and pre-training from scratch with a local arrow file already pre-processed.
I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks.
19
Load large text file for LM pre-training resulting in OOM I tried to pretrain Longformer using transformers and datasets. But I got OOM issues with loading a large text file. My script is almost like this: ```python from datasets import load_dataset @dataclass class DataCollatorForDatasetsLanguageModeling(DataCollatorForLanguageModeling): """ Data collator used for language modeling based on DataCollatorForLazyLanguageModeling - collates batches of tensors, honoring their tokenizer's pad_token - preprocesses batches for masked language modeling """ block_size: int = 512 def __call__(self, examples: List[dict]) -> Dict[str, torch.Tensor]: examples = [example['text'] for example in examples] batch, attention_mask = self._tensorize_batch(examples) if self.mlm: inputs, labels = self.mask_tokens(batch) return {"input_ids": inputs, "labels": labels} else: labels = batch.clone().detach() if self.tokenizer.pad_token_id is not None: labels[labels == self.tokenizer.pad_token_id] = -100 return {"input_ids": batch, "labels": labels} def _tensorize_batch(self, examples: List[str]) -> Tuple[torch.Tensor, torch.Tensor]: if self.tokenizer._pad_token is None: raise ValueError( "You are attempting to pad samples but the tokenizer you are using" f" ({self.tokenizer.__class__.__name__}) does not have one." ) tensor_examples = self.tokenizer.batch_encode_plus( [ex for ex in examples if ex], max_length=self.block_size, return_tensors="pt", pad_to_max_length=True, return_attention_mask=True, truncation=True, ) input_ids, attention_mask = tensor_examples["input_ids"], tensor_examples["attention_mask"] return input_ids, attention_mask dataset = load_dataset('text', data_files='train.txt',cache_dir="./", , split='train') data_collator = DataCollatorForDatasetsLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15, block_size=tokenizer.max_len) trainer = Trainer(model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, prediction_loss_only=True, ) trainer.train(model_path=model_path) ``` This train.txt is about 1.1GB and has 90k lines where each line is a sequence of 4k words. During training, the memory usage increased fast as the following graph and resulted in OOM before the finish of training. ![image](https://user-images.githubusercontent.com/29704017/93292112-5576b280-f817-11ea-8da2-b2db9bf35665.png) Could you please give me any suggestions on why this happened and how to fix it? Thanks. Yes, on both cases. Fine-tuning a pre-trained model and pre-training from scratch with a local arrow file already pre-processed.
https://github.com/huggingface/datasets/issues/630
Text dataset not working with large files
Basically ~600MB txt files(UTF-8) * 59. contents like ```์•ˆ๋…•ํ•˜์„ธ์š”, ์ด๊ฒƒ์€ ์˜ˆ์ œ๋กœ ํ•œ๋ฒˆ ๋งํ•ด๋ณด๋Š” ํ…์ŠคํŠธ์ž…๋‹ˆ๋‹ค. ๊ทธ๋ƒฅ ์ด๋ ‡๋‹ค๊ณ ์š”.<|endoftext|>\n``` Also, it gets stuck for a loooong time at ```Testing the mapped function outputs```, for more than 12 hours(currently ongoing)
``` Traceback (most recent call last): File "examples/language-modeling/run_language_modeling.py", line 333, in <module> main() File "examples/language-modeling/run_language_modeling.py", line 262, in main get_dataset(data_args, tokenizer=tokenizer, cache_dir=model_args.cache_dir) if training_args.do_train else None File "examples/language-modeling/run_language_modeling.py", line 144, in get_dataset dataset = load_dataset("text", data_files=file_path, split='train+test') File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/load.py", line 611, in load_dataset ignore_verifications=ignore_verifications, File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 469, in download_and_prepare dl_manager=dl_manager, verify_infos=verify_infos, **download_and_prepare_kwargs File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 546, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 888, in _prepare_split for key, table in utils.tqdm(generator, unit=" tables", leave=False, disable=not_verbose): File "/home/ksjae/.local/lib/python3.7/site-packages/tqdm/std.py", line 1129, in __iter__ for obj in iterable: File "/home/ksjae/.cache/huggingface/modules/datasets_modules/datasets/text/7e13bc0fa76783d4ef197f079dc8acfe54c3efda980f2c9adfab046ede2f0ff7/text.py", line 104, in _generate_tables convert_options=self.config.convert_options, File "pyarrow/_csv.pyx", line 714, in pyarrow._csv.read_csv File "pyarrow/error.pxi", line 122, in pyarrow.lib.pyarrow_internal_check_status File "pyarrow/error.pxi", line 84, in pyarrow.lib.check_status ``` **pyarrow.lib.ArrowInvalid: straddling object straddles two block boundaries (try to increase block size?)** It gives the same message for both 200MB, 10GB .tx files but not for 700MB file. Can't upload due to size & copyright problem. sorry.
36
Text dataset not working with large files ``` Traceback (most recent call last): File "examples/language-modeling/run_language_modeling.py", line 333, in <module> main() File "examples/language-modeling/run_language_modeling.py", line 262, in main get_dataset(data_args, tokenizer=tokenizer, cache_dir=model_args.cache_dir) if training_args.do_train else None File "examples/language-modeling/run_language_modeling.py", line 144, in get_dataset dataset = load_dataset("text", data_files=file_path, split='train+test') File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/load.py", line 611, in load_dataset ignore_verifications=ignore_verifications, File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 469, in download_and_prepare dl_manager=dl_manager, verify_infos=verify_infos, **download_and_prepare_kwargs File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 546, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 888, in _prepare_split for key, table in utils.tqdm(generator, unit=" tables", leave=False, disable=not_verbose): File "/home/ksjae/.local/lib/python3.7/site-packages/tqdm/std.py", line 1129, in __iter__ for obj in iterable: File "/home/ksjae/.cache/huggingface/modules/datasets_modules/datasets/text/7e13bc0fa76783d4ef197f079dc8acfe54c3efda980f2c9adfab046ede2f0ff7/text.py", line 104, in _generate_tables convert_options=self.config.convert_options, File "pyarrow/_csv.pyx", line 714, in pyarrow._csv.read_csv File "pyarrow/error.pxi", line 122, in pyarrow.lib.pyarrow_internal_check_status File "pyarrow/error.pxi", line 84, in pyarrow.lib.check_status ``` **pyarrow.lib.ArrowInvalid: straddling object straddles two block boundaries (try to increase block size?)** It gives the same message for both 200MB, 10GB .tx files but not for 700MB file. Can't upload due to size & copyright problem. sorry. Basically ~600MB txt files(UTF-8) * 59. contents like ```์•ˆ๋…•ํ•˜์„ธ์š”, ์ด๊ฒƒ์€ ์˜ˆ์ œ๋กœ ํ•œ๋ฒˆ ๋งํ•ด๋ณด๋Š” ํ…์ŠคํŠธ์ž…๋‹ˆ๋‹ค. ๊ทธ๋ƒฅ ์ด๋ ‡๋‹ค๊ณ ์š”.<|endoftext|>\n``` Also, it gets stuck for a loooong time at ```Testing the mapped function outputs```, for more than 12 hours(currently ongoing)
https://github.com/huggingface/datasets/issues/630
Text dataset not working with large files
It gets stuck while doing `.map()` ? Are you using multiprocessing ? If you could provide a code snippet it could be very useful
``` Traceback (most recent call last): File "examples/language-modeling/run_language_modeling.py", line 333, in <module> main() File "examples/language-modeling/run_language_modeling.py", line 262, in main get_dataset(data_args, tokenizer=tokenizer, cache_dir=model_args.cache_dir) if training_args.do_train else None File "examples/language-modeling/run_language_modeling.py", line 144, in get_dataset dataset = load_dataset("text", data_files=file_path, split='train+test') File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/load.py", line 611, in load_dataset ignore_verifications=ignore_verifications, File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 469, in download_and_prepare dl_manager=dl_manager, verify_infos=verify_infos, **download_and_prepare_kwargs File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 546, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 888, in _prepare_split for key, table in utils.tqdm(generator, unit=" tables", leave=False, disable=not_verbose): File "/home/ksjae/.local/lib/python3.7/site-packages/tqdm/std.py", line 1129, in __iter__ for obj in iterable: File "/home/ksjae/.cache/huggingface/modules/datasets_modules/datasets/text/7e13bc0fa76783d4ef197f079dc8acfe54c3efda980f2c9adfab046ede2f0ff7/text.py", line 104, in _generate_tables convert_options=self.config.convert_options, File "pyarrow/_csv.pyx", line 714, in pyarrow._csv.read_csv File "pyarrow/error.pxi", line 122, in pyarrow.lib.pyarrow_internal_check_status File "pyarrow/error.pxi", line 84, in pyarrow.lib.check_status ``` **pyarrow.lib.ArrowInvalid: straddling object straddles two block boundaries (try to increase block size?)** It gives the same message for both 200MB, 10GB .tx files but not for 700MB file. Can't upload due to size & copyright problem. sorry.
24
Text dataset not working with large files ``` Traceback (most recent call last): File "examples/language-modeling/run_language_modeling.py", line 333, in <module> main() File "examples/language-modeling/run_language_modeling.py", line 262, in main get_dataset(data_args, tokenizer=tokenizer, cache_dir=model_args.cache_dir) if training_args.do_train else None File "examples/language-modeling/run_language_modeling.py", line 144, in get_dataset dataset = load_dataset("text", data_files=file_path, split='train+test') File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/load.py", line 611, in load_dataset ignore_verifications=ignore_verifications, File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 469, in download_and_prepare dl_manager=dl_manager, verify_infos=verify_infos, **download_and_prepare_kwargs File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 546, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 888, in _prepare_split for key, table in utils.tqdm(generator, unit=" tables", leave=False, disable=not_verbose): File "/home/ksjae/.local/lib/python3.7/site-packages/tqdm/std.py", line 1129, in __iter__ for obj in iterable: File "/home/ksjae/.cache/huggingface/modules/datasets_modules/datasets/text/7e13bc0fa76783d4ef197f079dc8acfe54c3efda980f2c9adfab046ede2f0ff7/text.py", line 104, in _generate_tables convert_options=self.config.convert_options, File "pyarrow/_csv.pyx", line 714, in pyarrow._csv.read_csv File "pyarrow/error.pxi", line 122, in pyarrow.lib.pyarrow_internal_check_status File "pyarrow/error.pxi", line 84, in pyarrow.lib.check_status ``` **pyarrow.lib.ArrowInvalid: straddling object straddles two block boundaries (try to increase block size?)** It gives the same message for both 200MB, 10GB .tx files but not for 700MB file. Can't upload due to size & copyright problem. sorry. It gets stuck while doing `.map()` ? Are you using multiprocessing ? If you could provide a code snippet it could be very useful
https://github.com/huggingface/datasets/issues/630
Text dataset not working with large files
From transformers/examples/language-modeling/run-language-modeling.py : ``` def get_dataset( args: DataTrainingArguments, tokenizer: PreTrainedTokenizer, evaluate: bool = False, cache_dir: Optional[str] = None, ): file_path = args.eval_data_file if evaluate else args.train_data_file if True: dataset = load_dataset("text", data_files=glob.glob(file_path), split='train', use_threads=True, ignore_verifications=True, save_infos=True, block_size=104857600) dataset = dataset.map(lambda ex: tokenizer(ex["text"], add_special_tokens=True, truncation=True, max_length=args.block_size), batched=True) dataset.set_format(type='torch', columns=['input_ids']) return dataset if args.line_by_line: return LineByLineTextDataset(tokenizer=tokenizer, file_path=file_path, block_size=args.block_size) else: return TextDataset( tokenizer=tokenizer, file_path=file_path, block_size=args.block_size, overwrite_cache=args.overwrite_cache, cache_dir=cache_dir, ) ``` No, I'm not using multiprocessing.
``` Traceback (most recent call last): File "examples/language-modeling/run_language_modeling.py", line 333, in <module> main() File "examples/language-modeling/run_language_modeling.py", line 262, in main get_dataset(data_args, tokenizer=tokenizer, cache_dir=model_args.cache_dir) if training_args.do_train else None File "examples/language-modeling/run_language_modeling.py", line 144, in get_dataset dataset = load_dataset("text", data_files=file_path, split='train+test') File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/load.py", line 611, in load_dataset ignore_verifications=ignore_verifications, File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 469, in download_and_prepare dl_manager=dl_manager, verify_infos=verify_infos, **download_and_prepare_kwargs File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 546, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 888, in _prepare_split for key, table in utils.tqdm(generator, unit=" tables", leave=False, disable=not_verbose): File "/home/ksjae/.local/lib/python3.7/site-packages/tqdm/std.py", line 1129, in __iter__ for obj in iterable: File "/home/ksjae/.cache/huggingface/modules/datasets_modules/datasets/text/7e13bc0fa76783d4ef197f079dc8acfe54c3efda980f2c9adfab046ede2f0ff7/text.py", line 104, in _generate_tables convert_options=self.config.convert_options, File "pyarrow/_csv.pyx", line 714, in pyarrow._csv.read_csv File "pyarrow/error.pxi", line 122, in pyarrow.lib.pyarrow_internal_check_status File "pyarrow/error.pxi", line 84, in pyarrow.lib.check_status ``` **pyarrow.lib.ArrowInvalid: straddling object straddles two block boundaries (try to increase block size?)** It gives the same message for both 200MB, 10GB .tx files but not for 700MB file. Can't upload due to size & copyright problem. sorry.
71
Text dataset not working with large files ``` Traceback (most recent call last): File "examples/language-modeling/run_language_modeling.py", line 333, in <module> main() File "examples/language-modeling/run_language_modeling.py", line 262, in main get_dataset(data_args, tokenizer=tokenizer, cache_dir=model_args.cache_dir) if training_args.do_train else None File "examples/language-modeling/run_language_modeling.py", line 144, in get_dataset dataset = load_dataset("text", data_files=file_path, split='train+test') File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/load.py", line 611, in load_dataset ignore_verifications=ignore_verifications, File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 469, in download_and_prepare dl_manager=dl_manager, verify_infos=verify_infos, **download_and_prepare_kwargs File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 546, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 888, in _prepare_split for key, table in utils.tqdm(generator, unit=" tables", leave=False, disable=not_verbose): File "/home/ksjae/.local/lib/python3.7/site-packages/tqdm/std.py", line 1129, in __iter__ for obj in iterable: File "/home/ksjae/.cache/huggingface/modules/datasets_modules/datasets/text/7e13bc0fa76783d4ef197f079dc8acfe54c3efda980f2c9adfab046ede2f0ff7/text.py", line 104, in _generate_tables convert_options=self.config.convert_options, File "pyarrow/_csv.pyx", line 714, in pyarrow._csv.read_csv File "pyarrow/error.pxi", line 122, in pyarrow.lib.pyarrow_internal_check_status File "pyarrow/error.pxi", line 84, in pyarrow.lib.check_status ``` **pyarrow.lib.ArrowInvalid: straddling object straddles two block boundaries (try to increase block size?)** It gives the same message for both 200MB, 10GB .tx files but not for 700MB file. Can't upload due to size & copyright problem. sorry. From transformers/examples/language-modeling/run-language-modeling.py : ``` def get_dataset( args: DataTrainingArguments, tokenizer: PreTrainedTokenizer, evaluate: bool = False, cache_dir: Optional[str] = None, ): file_path = args.eval_data_file if evaluate else args.train_data_file if True: dataset = load_dataset("text", data_files=glob.glob(file_path), split='train', use_threads=True, ignore_verifications=True, save_infos=True, block_size=104857600) dataset = dataset.map(lambda ex: tokenizer(ex["text"], add_special_tokens=True, truncation=True, max_length=args.block_size), batched=True) dataset.set_format(type='torch', columns=['input_ids']) return dataset if args.line_by_line: return LineByLineTextDataset(tokenizer=tokenizer, file_path=file_path, block_size=args.block_size) else: return TextDataset( tokenizer=tokenizer, file_path=file_path, block_size=args.block_size, overwrite_cache=args.overwrite_cache, cache_dir=cache_dir, ) ``` No, I'm not using multiprocessing.
https://github.com/huggingface/datasets/issues/630
Text dataset not working with large files
I am not able to reproduce on my side :/ Could you send the version of `datasets` and `pyarrow` you're using ? Could you try to update the lib and try again ? Or do you think you could try to reproduce it on google colab ?
``` Traceback (most recent call last): File "examples/language-modeling/run_language_modeling.py", line 333, in <module> main() File "examples/language-modeling/run_language_modeling.py", line 262, in main get_dataset(data_args, tokenizer=tokenizer, cache_dir=model_args.cache_dir) if training_args.do_train else None File "examples/language-modeling/run_language_modeling.py", line 144, in get_dataset dataset = load_dataset("text", data_files=file_path, split='train+test') File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/load.py", line 611, in load_dataset ignore_verifications=ignore_verifications, File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 469, in download_and_prepare dl_manager=dl_manager, verify_infos=verify_infos, **download_and_prepare_kwargs File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 546, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 888, in _prepare_split for key, table in utils.tqdm(generator, unit=" tables", leave=False, disable=not_verbose): File "/home/ksjae/.local/lib/python3.7/site-packages/tqdm/std.py", line 1129, in __iter__ for obj in iterable: File "/home/ksjae/.cache/huggingface/modules/datasets_modules/datasets/text/7e13bc0fa76783d4ef197f079dc8acfe54c3efda980f2c9adfab046ede2f0ff7/text.py", line 104, in _generate_tables convert_options=self.config.convert_options, File "pyarrow/_csv.pyx", line 714, in pyarrow._csv.read_csv File "pyarrow/error.pxi", line 122, in pyarrow.lib.pyarrow_internal_check_status File "pyarrow/error.pxi", line 84, in pyarrow.lib.check_status ``` **pyarrow.lib.ArrowInvalid: straddling object straddles two block boundaries (try to increase block size?)** It gives the same message for both 200MB, 10GB .tx files but not for 700MB file. Can't upload due to size & copyright problem. sorry.
47
Text dataset not working with large files ``` Traceback (most recent call last): File "examples/language-modeling/run_language_modeling.py", line 333, in <module> main() File "examples/language-modeling/run_language_modeling.py", line 262, in main get_dataset(data_args, tokenizer=tokenizer, cache_dir=model_args.cache_dir) if training_args.do_train else None File "examples/language-modeling/run_language_modeling.py", line 144, in get_dataset dataset = load_dataset("text", data_files=file_path, split='train+test') File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/load.py", line 611, in load_dataset ignore_verifications=ignore_verifications, File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 469, in download_and_prepare dl_manager=dl_manager, verify_infos=verify_infos, **download_and_prepare_kwargs File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 546, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 888, in _prepare_split for key, table in utils.tqdm(generator, unit=" tables", leave=False, disable=not_verbose): File "/home/ksjae/.local/lib/python3.7/site-packages/tqdm/std.py", line 1129, in __iter__ for obj in iterable: File "/home/ksjae/.cache/huggingface/modules/datasets_modules/datasets/text/7e13bc0fa76783d4ef197f079dc8acfe54c3efda980f2c9adfab046ede2f0ff7/text.py", line 104, in _generate_tables convert_options=self.config.convert_options, File "pyarrow/_csv.pyx", line 714, in pyarrow._csv.read_csv File "pyarrow/error.pxi", line 122, in pyarrow.lib.pyarrow_internal_check_status File "pyarrow/error.pxi", line 84, in pyarrow.lib.check_status ``` **pyarrow.lib.ArrowInvalid: straddling object straddles two block boundaries (try to increase block size?)** It gives the same message for both 200MB, 10GB .tx files but not for 700MB file. Can't upload due to size & copyright problem. sorry. I am not able to reproduce on my side :/ Could you send the version of `datasets` and `pyarrow` you're using ? Could you try to update the lib and try again ? Or do you think you could try to reproduce it on google colab ?
https://github.com/huggingface/datasets/issues/630
Text dataset not working with large files
Huh, weird. It's fixed on my side too. But now ```Caching processed dataset``` is taking forever - how can I disable it? Any flags?
``` Traceback (most recent call last): File "examples/language-modeling/run_language_modeling.py", line 333, in <module> main() File "examples/language-modeling/run_language_modeling.py", line 262, in main get_dataset(data_args, tokenizer=tokenizer, cache_dir=model_args.cache_dir) if training_args.do_train else None File "examples/language-modeling/run_language_modeling.py", line 144, in get_dataset dataset = load_dataset("text", data_files=file_path, split='train+test') File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/load.py", line 611, in load_dataset ignore_verifications=ignore_verifications, File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 469, in download_and_prepare dl_manager=dl_manager, verify_infos=verify_infos, **download_and_prepare_kwargs File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 546, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 888, in _prepare_split for key, table in utils.tqdm(generator, unit=" tables", leave=False, disable=not_verbose): File "/home/ksjae/.local/lib/python3.7/site-packages/tqdm/std.py", line 1129, in __iter__ for obj in iterable: File "/home/ksjae/.cache/huggingface/modules/datasets_modules/datasets/text/7e13bc0fa76783d4ef197f079dc8acfe54c3efda980f2c9adfab046ede2f0ff7/text.py", line 104, in _generate_tables convert_options=self.config.convert_options, File "pyarrow/_csv.pyx", line 714, in pyarrow._csv.read_csv File "pyarrow/error.pxi", line 122, in pyarrow.lib.pyarrow_internal_check_status File "pyarrow/error.pxi", line 84, in pyarrow.lib.check_status ``` **pyarrow.lib.ArrowInvalid: straddling object straddles two block boundaries (try to increase block size?)** It gives the same message for both 200MB, 10GB .tx files but not for 700MB file. Can't upload due to size & copyright problem. sorry.
24
Text dataset not working with large files ``` Traceback (most recent call last): File "examples/language-modeling/run_language_modeling.py", line 333, in <module> main() File "examples/language-modeling/run_language_modeling.py", line 262, in main get_dataset(data_args, tokenizer=tokenizer, cache_dir=model_args.cache_dir) if training_args.do_train else None File "examples/language-modeling/run_language_modeling.py", line 144, in get_dataset dataset = load_dataset("text", data_files=file_path, split='train+test') File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/load.py", line 611, in load_dataset ignore_verifications=ignore_verifications, File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 469, in download_and_prepare dl_manager=dl_manager, verify_infos=verify_infos, **download_and_prepare_kwargs File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 546, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 888, in _prepare_split for key, table in utils.tqdm(generator, unit=" tables", leave=False, disable=not_verbose): File "/home/ksjae/.local/lib/python3.7/site-packages/tqdm/std.py", line 1129, in __iter__ for obj in iterable: File "/home/ksjae/.cache/huggingface/modules/datasets_modules/datasets/text/7e13bc0fa76783d4ef197f079dc8acfe54c3efda980f2c9adfab046ede2f0ff7/text.py", line 104, in _generate_tables convert_options=self.config.convert_options, File "pyarrow/_csv.pyx", line 714, in pyarrow._csv.read_csv File "pyarrow/error.pxi", line 122, in pyarrow.lib.pyarrow_internal_check_status File "pyarrow/error.pxi", line 84, in pyarrow.lib.check_status ``` **pyarrow.lib.ArrowInvalid: straddling object straddles two block boundaries (try to increase block size?)** It gives the same message for both 200MB, 10GB .tx files but not for 700MB file. Can't upload due to size & copyright problem. sorry. Huh, weird. It's fixed on my side too. But now ```Caching processed dataset``` is taking forever - how can I disable it? Any flags?
https://github.com/huggingface/datasets/issues/630
Text dataset not working with large files
Right after `Caching processed dataset`, your function is applied to the dataset and there's a progress bar that shows how much time is left. How much time does it take for you ? Also caching isn't supposed to slow down your processing. But if you still want to disable it you can do `.map(..., load_from_cache_file=False)`
``` Traceback (most recent call last): File "examples/language-modeling/run_language_modeling.py", line 333, in <module> main() File "examples/language-modeling/run_language_modeling.py", line 262, in main get_dataset(data_args, tokenizer=tokenizer, cache_dir=model_args.cache_dir) if training_args.do_train else None File "examples/language-modeling/run_language_modeling.py", line 144, in get_dataset dataset = load_dataset("text", data_files=file_path, split='train+test') File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/load.py", line 611, in load_dataset ignore_verifications=ignore_verifications, File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 469, in download_and_prepare dl_manager=dl_manager, verify_infos=verify_infos, **download_and_prepare_kwargs File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 546, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 888, in _prepare_split for key, table in utils.tqdm(generator, unit=" tables", leave=False, disable=not_verbose): File "/home/ksjae/.local/lib/python3.7/site-packages/tqdm/std.py", line 1129, in __iter__ for obj in iterable: File "/home/ksjae/.cache/huggingface/modules/datasets_modules/datasets/text/7e13bc0fa76783d4ef197f079dc8acfe54c3efda980f2c9adfab046ede2f0ff7/text.py", line 104, in _generate_tables convert_options=self.config.convert_options, File "pyarrow/_csv.pyx", line 714, in pyarrow._csv.read_csv File "pyarrow/error.pxi", line 122, in pyarrow.lib.pyarrow_internal_check_status File "pyarrow/error.pxi", line 84, in pyarrow.lib.check_status ``` **pyarrow.lib.ArrowInvalid: straddling object straddles two block boundaries (try to increase block size?)** It gives the same message for both 200MB, 10GB .tx files but not for 700MB file. Can't upload due to size & copyright problem. sorry.
55
Text dataset not working with large files ``` Traceback (most recent call last): File "examples/language-modeling/run_language_modeling.py", line 333, in <module> main() File "examples/language-modeling/run_language_modeling.py", line 262, in main get_dataset(data_args, tokenizer=tokenizer, cache_dir=model_args.cache_dir) if training_args.do_train else None File "examples/language-modeling/run_language_modeling.py", line 144, in get_dataset dataset = load_dataset("text", data_files=file_path, split='train+test') File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/load.py", line 611, in load_dataset ignore_verifications=ignore_verifications, File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 469, in download_and_prepare dl_manager=dl_manager, verify_infos=verify_infos, **download_and_prepare_kwargs File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 546, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 888, in _prepare_split for key, table in utils.tqdm(generator, unit=" tables", leave=False, disable=not_verbose): File "/home/ksjae/.local/lib/python3.7/site-packages/tqdm/std.py", line 1129, in __iter__ for obj in iterable: File "/home/ksjae/.cache/huggingface/modules/datasets_modules/datasets/text/7e13bc0fa76783d4ef197f079dc8acfe54c3efda980f2c9adfab046ede2f0ff7/text.py", line 104, in _generate_tables convert_options=self.config.convert_options, File "pyarrow/_csv.pyx", line 714, in pyarrow._csv.read_csv File "pyarrow/error.pxi", line 122, in pyarrow.lib.pyarrow_internal_check_status File "pyarrow/error.pxi", line 84, in pyarrow.lib.check_status ``` **pyarrow.lib.ArrowInvalid: straddling object straddles two block boundaries (try to increase block size?)** It gives the same message for both 200MB, 10GB .tx files but not for 700MB file. Can't upload due to size & copyright problem. sorry. Right after `Caching processed dataset`, your function is applied to the dataset and there's a progress bar that shows how much time is left. How much time does it take for you ? Also caching isn't supposed to slow down your processing. But if you still want to disable it you can do `.map(..., load_from_cache_file=False)`
https://github.com/huggingface/datasets/issues/630
Text dataset not working with large files
Ah, itโ€™s much faster now(Takes around 15~20min). BTW, any way to set default tensor output as plain tensors with distributed training? The ragged tensors are incompatible with tpustrategy :(
``` Traceback (most recent call last): File "examples/language-modeling/run_language_modeling.py", line 333, in <module> main() File "examples/language-modeling/run_language_modeling.py", line 262, in main get_dataset(data_args, tokenizer=tokenizer, cache_dir=model_args.cache_dir) if training_args.do_train else None File "examples/language-modeling/run_language_modeling.py", line 144, in get_dataset dataset = load_dataset("text", data_files=file_path, split='train+test') File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/load.py", line 611, in load_dataset ignore_verifications=ignore_verifications, File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 469, in download_and_prepare dl_manager=dl_manager, verify_infos=verify_infos, **download_and_prepare_kwargs File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 546, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 888, in _prepare_split for key, table in utils.tqdm(generator, unit=" tables", leave=False, disable=not_verbose): File "/home/ksjae/.local/lib/python3.7/site-packages/tqdm/std.py", line 1129, in __iter__ for obj in iterable: File "/home/ksjae/.cache/huggingface/modules/datasets_modules/datasets/text/7e13bc0fa76783d4ef197f079dc8acfe54c3efda980f2c9adfab046ede2f0ff7/text.py", line 104, in _generate_tables convert_options=self.config.convert_options, File "pyarrow/_csv.pyx", line 714, in pyarrow._csv.read_csv File "pyarrow/error.pxi", line 122, in pyarrow.lib.pyarrow_internal_check_status File "pyarrow/error.pxi", line 84, in pyarrow.lib.check_status ``` **pyarrow.lib.ArrowInvalid: straddling object straddles two block boundaries (try to increase block size?)** It gives the same message for both 200MB, 10GB .tx files but not for 700MB file. Can't upload due to size & copyright problem. sorry.
29
Text dataset not working with large files ``` Traceback (most recent call last): File "examples/language-modeling/run_language_modeling.py", line 333, in <module> main() File "examples/language-modeling/run_language_modeling.py", line 262, in main get_dataset(data_args, tokenizer=tokenizer, cache_dir=model_args.cache_dir) if training_args.do_train else None File "examples/language-modeling/run_language_modeling.py", line 144, in get_dataset dataset = load_dataset("text", data_files=file_path, split='train+test') File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/load.py", line 611, in load_dataset ignore_verifications=ignore_verifications, File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 469, in download_and_prepare dl_manager=dl_manager, verify_infos=verify_infos, **download_and_prepare_kwargs File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 546, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 888, in _prepare_split for key, table in utils.tqdm(generator, unit=" tables", leave=False, disable=not_verbose): File "/home/ksjae/.local/lib/python3.7/site-packages/tqdm/std.py", line 1129, in __iter__ for obj in iterable: File "/home/ksjae/.cache/huggingface/modules/datasets_modules/datasets/text/7e13bc0fa76783d4ef197f079dc8acfe54c3efda980f2c9adfab046ede2f0ff7/text.py", line 104, in _generate_tables convert_options=self.config.convert_options, File "pyarrow/_csv.pyx", line 714, in pyarrow._csv.read_csv File "pyarrow/error.pxi", line 122, in pyarrow.lib.pyarrow_internal_check_status File "pyarrow/error.pxi", line 84, in pyarrow.lib.check_status ``` **pyarrow.lib.ArrowInvalid: straddling object straddles two block boundaries (try to increase block size?)** It gives the same message for both 200MB, 10GB .tx files but not for 700MB file. Can't upload due to size & copyright problem. sorry. Ah, itโ€™s much faster now(Takes around 15~20min). BTW, any way to set default tensor output as plain tensors with distributed training? The ragged tensors are incompatible with tpustrategy :(
https://github.com/huggingface/datasets/issues/630
Text dataset not working with large files
> Ah, itโ€™s much faster now(Takes around 15~20min). Glad to see that it's faster now. What did you change exactly ? > BTW, any way to set default tensor output as plain tensors with distributed training? The ragged tensors are incompatible with tpustrategy :( Oh I didn't know about that. Feel free to open an issue to mention that. I guess what you can do for now is set the dataset format to numpy instead of tensorflow, and use a wrapper of the dataset that converts the numpy arrays to tf tensors.
``` Traceback (most recent call last): File "examples/language-modeling/run_language_modeling.py", line 333, in <module> main() File "examples/language-modeling/run_language_modeling.py", line 262, in main get_dataset(data_args, tokenizer=tokenizer, cache_dir=model_args.cache_dir) if training_args.do_train else None File "examples/language-modeling/run_language_modeling.py", line 144, in get_dataset dataset = load_dataset("text", data_files=file_path, split='train+test') File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/load.py", line 611, in load_dataset ignore_verifications=ignore_verifications, File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 469, in download_and_prepare dl_manager=dl_manager, verify_infos=verify_infos, **download_and_prepare_kwargs File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 546, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 888, in _prepare_split for key, table in utils.tqdm(generator, unit=" tables", leave=False, disable=not_verbose): File "/home/ksjae/.local/lib/python3.7/site-packages/tqdm/std.py", line 1129, in __iter__ for obj in iterable: File "/home/ksjae/.cache/huggingface/modules/datasets_modules/datasets/text/7e13bc0fa76783d4ef197f079dc8acfe54c3efda980f2c9adfab046ede2f0ff7/text.py", line 104, in _generate_tables convert_options=self.config.convert_options, File "pyarrow/_csv.pyx", line 714, in pyarrow._csv.read_csv File "pyarrow/error.pxi", line 122, in pyarrow.lib.pyarrow_internal_check_status File "pyarrow/error.pxi", line 84, in pyarrow.lib.check_status ``` **pyarrow.lib.ArrowInvalid: straddling object straddles two block boundaries (try to increase block size?)** It gives the same message for both 200MB, 10GB .tx files but not for 700MB file. Can't upload due to size & copyright problem. sorry.
92
Text dataset not working with large files ``` Traceback (most recent call last): File "examples/language-modeling/run_language_modeling.py", line 333, in <module> main() File "examples/language-modeling/run_language_modeling.py", line 262, in main get_dataset(data_args, tokenizer=tokenizer, cache_dir=model_args.cache_dir) if training_args.do_train else None File "examples/language-modeling/run_language_modeling.py", line 144, in get_dataset dataset = load_dataset("text", data_files=file_path, split='train+test') File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/load.py", line 611, in load_dataset ignore_verifications=ignore_verifications, File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 469, in download_and_prepare dl_manager=dl_manager, verify_infos=verify_infos, **download_and_prepare_kwargs File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 546, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 888, in _prepare_split for key, table in utils.tqdm(generator, unit=" tables", leave=False, disable=not_verbose): File "/home/ksjae/.local/lib/python3.7/site-packages/tqdm/std.py", line 1129, in __iter__ for obj in iterable: File "/home/ksjae/.cache/huggingface/modules/datasets_modules/datasets/text/7e13bc0fa76783d4ef197f079dc8acfe54c3efda980f2c9adfab046ede2f0ff7/text.py", line 104, in _generate_tables convert_options=self.config.convert_options, File "pyarrow/_csv.pyx", line 714, in pyarrow._csv.read_csv File "pyarrow/error.pxi", line 122, in pyarrow.lib.pyarrow_internal_check_status File "pyarrow/error.pxi", line 84, in pyarrow.lib.check_status ``` **pyarrow.lib.ArrowInvalid: straddling object straddles two block boundaries (try to increase block size?)** It gives the same message for both 200MB, 10GB .tx files but not for 700MB file. Can't upload due to size & copyright problem. sorry. > Ah, itโ€™s much faster now(Takes around 15~20min). Glad to see that it's faster now. What did you change exactly ? > BTW, any way to set default tensor output as plain tensors with distributed training? The ragged tensors are incompatible with tpustrategy :( Oh I didn't know about that. Feel free to open an issue to mention that. I guess what you can do for now is set the dataset format to numpy instead of tensorflow, and use a wrapper of the dataset that converts the numpy arrays to tf tensors.
https://github.com/huggingface/datasets/issues/630
Text dataset not working with large files
>>> Glad to see that it's faster now. What did you change exactly ? I don't know, it just worked...? Sorry I couldn't be more helpful. Setting with numpy array is a great idea! Thanks.
``` Traceback (most recent call last): File "examples/language-modeling/run_language_modeling.py", line 333, in <module> main() File "examples/language-modeling/run_language_modeling.py", line 262, in main get_dataset(data_args, tokenizer=tokenizer, cache_dir=model_args.cache_dir) if training_args.do_train else None File "examples/language-modeling/run_language_modeling.py", line 144, in get_dataset dataset = load_dataset("text", data_files=file_path, split='train+test') File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/load.py", line 611, in load_dataset ignore_verifications=ignore_verifications, File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 469, in download_and_prepare dl_manager=dl_manager, verify_infos=verify_infos, **download_and_prepare_kwargs File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 546, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 888, in _prepare_split for key, table in utils.tqdm(generator, unit=" tables", leave=False, disable=not_verbose): File "/home/ksjae/.local/lib/python3.7/site-packages/tqdm/std.py", line 1129, in __iter__ for obj in iterable: File "/home/ksjae/.cache/huggingface/modules/datasets_modules/datasets/text/7e13bc0fa76783d4ef197f079dc8acfe54c3efda980f2c9adfab046ede2f0ff7/text.py", line 104, in _generate_tables convert_options=self.config.convert_options, File "pyarrow/_csv.pyx", line 714, in pyarrow._csv.read_csv File "pyarrow/error.pxi", line 122, in pyarrow.lib.pyarrow_internal_check_status File "pyarrow/error.pxi", line 84, in pyarrow.lib.check_status ``` **pyarrow.lib.ArrowInvalid: straddling object straddles two block boundaries (try to increase block size?)** It gives the same message for both 200MB, 10GB .tx files but not for 700MB file. Can't upload due to size & copyright problem. sorry.
35
Text dataset not working with large files ``` Traceback (most recent call last): File "examples/language-modeling/run_language_modeling.py", line 333, in <module> main() File "examples/language-modeling/run_language_modeling.py", line 262, in main get_dataset(data_args, tokenizer=tokenizer, cache_dir=model_args.cache_dir) if training_args.do_train else None File "examples/language-modeling/run_language_modeling.py", line 144, in get_dataset dataset = load_dataset("text", data_files=file_path, split='train+test') File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/load.py", line 611, in load_dataset ignore_verifications=ignore_verifications, File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 469, in download_and_prepare dl_manager=dl_manager, verify_infos=verify_infos, **download_and_prepare_kwargs File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 546, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/home/ksjae/.local/lib/python3.7/site-packages/datasets/builder.py", line 888, in _prepare_split for key, table in utils.tqdm(generator, unit=" tables", leave=False, disable=not_verbose): File "/home/ksjae/.local/lib/python3.7/site-packages/tqdm/std.py", line 1129, in __iter__ for obj in iterable: File "/home/ksjae/.cache/huggingface/modules/datasets_modules/datasets/text/7e13bc0fa76783d4ef197f079dc8acfe54c3efda980f2c9adfab046ede2f0ff7/text.py", line 104, in _generate_tables convert_options=self.config.convert_options, File "pyarrow/_csv.pyx", line 714, in pyarrow._csv.read_csv File "pyarrow/error.pxi", line 122, in pyarrow.lib.pyarrow_internal_check_status File "pyarrow/error.pxi", line 84, in pyarrow.lib.check_status ``` **pyarrow.lib.ArrowInvalid: straddling object straddles two block boundaries (try to increase block size?)** It gives the same message for both 200MB, 10GB .tx files but not for 700MB file. Can't upload due to size & copyright problem. sorry. >>> Glad to see that it's faster now. What did you change exactly ? I don't know, it just worked...? Sorry I couldn't be more helpful. Setting with numpy array is a great idea! Thanks.