Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature] Add context manager to allow main process first. #98

Merged
merged 3 commits into from
Jun 3, 2021

Conversation

Guillem96
Copy link
Contributor

This feature is useful when downloading or processing data.

Example

accelerator = Accelerator() 
cache_fname = Path("cache.txt") 

with accelerator.main_process_first():  ## or accelerator.local_main_process_first()
    if cache_fname.exists(): 
        data = cache_fname.read_text() # Load from cache 
    else:
         data = "data" # Time consuming operation 
         cache_fname.write_text(data)  # Cache the data

This syntaxis is much more concise and contributes with more semantic than the older one:

if not accelerator.is_main_process:  # or is_local_main_process
    accelerator.wait_for_everybody()

if cache_fname.exists(): 
    data = cache_fname.read_text() # Load from cache 
else:
     data = "data" # Time consuming operation 
     cache_fname.write_text(data)  # Cache the data

if accelerator.is_main_process:  # or is_local_main_process
    accelerator.wait_for_everybody()

Copy link
Collaborator

@sgugger sgugger left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very nice addition, thanks a lot!

Comment on lines 205 to 206
def _goes_first(self, is_master):
if not is_master:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Small nit: can we use is_main for consistency here (as well as at line 211 below)?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes sure!

@Guillem96
Copy link
Contributor Author

Addressed the request.

@sgugger sgugger merged commit f0cdbf1 into huggingface:main Jun 3, 2021
@sgugger
Copy link
Collaborator

sgugger commented Jun 3, 2021

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants