-
Notifications
You must be signed in to change notification settings - Fork 467
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
Accelerate scaler #2677
Closed
avishniakov
wants to merge
23
commits into
develop
from
feature/OSSK-535-auto-create-a-cli-wrapper-for-a-function
Closed
Accelerate scaler #2677
Changes from all commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
004b77c
sugar for accelerate
avishniakov 95fa2c0
fix cli command format
avishniakov b5f0279
properly process collections
avishniakov ae012de
properly process collections
avishniakov 10135e2
properly process collections
avishniakov ecd4170
properly process collections
avishniakov c80d348
properly process collections
avishniakov 621f7f8
properly process collections
avishniakov d7388c6
lint
avishniakov 39dd1ac
add scalers setting to the step
avishniakov c250e3a
properly store ref to original scaler
avishniakov ce2386e
properly store ref to original scaler
avishniakov 8f1d2a9
clii wrapper as contextmanager
avishniakov 84a7e49
cli wrapper as contextmanager
avishniakov 4ecff7d
cli wrapper as contextmanager
avishniakov c01597d
return from accelerate command
avishniakov 6a43759
cli wrapper as contextmanager
avishniakov 86045b1
cli wrapper as contextmanager
avishniakov e4ed1e2
proper paths
avishniakov 88bfe64
add debug outputs
avishniakov 963c819
add debug outputs
avishniakov 5f06ddd
return from CLICK
avishniakov 52a81f9
add aggregate scaler
avishniakov File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -32,6 +32,7 @@ prev = "prev" | |
creat = "creat" | ||
ret = "ret" | ||
daa = "daa" | ||
cll = "cll" | ||
|
||
[default] | ||
locale = "en-us" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
# Copyright (c) ZenML GmbH 2024. All Rights Reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at: | ||
# | ||
# https://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express | ||
# or implied. See the License for the specific language governing | ||
# permissions and limitations under the License. | ||
"""Accelerate integration for ZenML.""" | ||
|
||
from zenml.integrations.accelerate.scalers.accelerate_scaler import AccelerateScaler | ||
|
||
__all__ = [ | ||
"AccelerateScaler", | ||
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
# Copyright (c) ZenML GmbH 2024. All Rights Reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at: | ||
# | ||
# https://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express | ||
# or implied. See the License for the specific language governing | ||
# permissions and limitations under the License. | ||
"""Accelerate scalers for ZenML.""" |
131 changes: 131 additions & 0 deletions
131
src/zenml/integrations/accelerate/scalers/accelerate_scaler.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,131 @@ | ||
# Copyright (c) ZenML GmbH 2024. All Rights Reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at: | ||
# | ||
# https://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express | ||
# or implied. See the License for the specific language governing | ||
# permissions and limitations under the License. | ||
"""Utility function to run Accelerate jobs.""" | ||
|
||
import subprocess | ||
from typing import Any, Callable, Optional, TypeVar | ||
|
||
import cloudpickle as pickle | ||
|
||
from zenml.logger import get_logger | ||
from zenml.models.v2.misc.scaler_models import ScalerModel | ||
from zenml.utils.function_utils import _cli_arg_name, create_cli_wrapped_script | ||
|
||
logger = get_logger(__name__) | ||
F = TypeVar("F", bound=Callable[..., None]) | ||
|
||
|
||
class AccelerateScaler(ScalerModel): | ||
"""Accelerate scaler model. | ||
|
||
Accelerate package: https://huggingface.co/docs/accelerate/en/index | ||
|
||
Example: | ||
```python | ||
from zenml import step | ||
from zenml.integrations.accelerate import AccelerateScaler | ||
|
||
@step(scaler=AccelerateScaler(num_processes=42)) | ||
def training_step(some_param: int, ...): | ||
# your training code is below | ||
... | ||
``` | ||
|
||
Args: | ||
num_processes: The number of processes to use (shall be less or equal to GPUs count). | ||
""" | ||
|
||
num_processes: Optional[int] = None | ||
|
||
def run(self, step_function: F, **function_kwargs: Any) -> Any: | ||
"""Run a function with accelerate. | ||
|
||
Accelerate package: https://huggingface.co/docs/accelerate/en/index | ||
|
||
Example: | ||
```python | ||
from zenml import step | ||
from zenml.integrations.accelerate import AccelerateScaler | ||
|
||
@step(scaler=AccelerateScaler(num_processes=42)) | ||
def training_step(some_param: int, ...): | ||
# your training code is below | ||
... | ||
``` | ||
|
||
Args: | ||
step_function: The function to run. | ||
**function_kwargs: The keyword arguments to pass to the function. | ||
|
||
Returns: | ||
The return value of the function in the main process. | ||
|
||
Raises: | ||
CalledProcessError: If the function fails. | ||
""" | ||
import torch | ||
|
||
logger.info("Starting accelerate job...") | ||
|
||
device_count = torch.cuda.device_count() | ||
if self.num_processes is None: | ||
num_processes = device_count | ||
else: | ||
if self.num_processes > device_count: | ||
logger.warning( | ||
f"Number of processes ({self.num_processes}) is greater than " | ||
f"the number of available GPUs ({device_count}). Using all GPUs." | ||
) | ||
num_processes = device_count | ||
num_processes = self.num_processes | ||
|
||
with create_cli_wrapped_script( | ||
step_function, flavour="accelerate" | ||
) as ( | ||
script_path, | ||
output_path, | ||
): | ||
command = f"accelerate launch --num_processes {num_processes} " | ||
command += str(script_path.absolute()) + " " | ||
for k, v in function_kwargs.items(): | ||
k = _cli_arg_name(k) | ||
if isinstance(v, bool): | ||
if v: | ||
command += f"--{k} " | ||
elif isinstance(v, str): | ||
command += f'--{k} "{v}" ' | ||
elif type(v) in (list, tuple, set): | ||
for each in v: | ||
command += f"--{k} {each} " | ||
else: | ||
command += f"--{k} {v} " | ||
|
||
logger.info(command) | ||
|
||
result = subprocess.run( | ||
command, | ||
shell=True, | ||
stdout=subprocess.PIPE, | ||
universal_newlines=True, | ||
) | ||
for stdout_line in result.stdout.split("\n"): | ||
logger.info(stdout_line) | ||
if result.returncode == 0: | ||
logger.info("Accelerate training job finished.") | ||
return pickle.load(open(output_path, "rb")) | ||
else: | ||
logger.error( | ||
f"Accelerate training job failed. With return code {result.returncode}." | ||
) | ||
raise subprocess.CalledProcessError(result.returncode, command) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,84 @@ | ||
# Copyright (c) ZenML GmbH 2024. All Rights Reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at: | ||
# | ||
# https://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express | ||
# or implied. See the License for the specific language governing | ||
# permissions and limitations under the License. | ||
"""Model definitions for ZenML scalers.""" | ||
|
||
from typing import Any, Callable, ClassVar, Dict, Optional, Set, TypeVar | ||
|
||
from pydantic import BaseModel, root_validator | ||
|
||
F = TypeVar("F", bound=Callable[..., None]) | ||
|
||
|
||
class ScalerModel(BaseModel): | ||
"""Domain model for scalers.""" | ||
|
||
scaler_flavor: Optional[str] = None | ||
|
||
ALLOWED_SCALER_FLAVORS: ClassVar[Set[str]] = { | ||
"AggregateScaler", | ||
"AccelerateScaler", | ||
} | ||
|
||
@root_validator(pre=True) | ||
def validate_scaler_flavor(cls, values: Dict[str, Any]) -> Dict[str, Any]: | ||
"""Validate the scaler flavor. | ||
|
||
Args: | ||
values: The values to validate. | ||
|
||
Returns: | ||
The validated values. | ||
|
||
Raises: | ||
ValueError: If the scaler flavor is not supported. | ||
""" | ||
if values.get("scaler_flavor", None) is None: | ||
values["scaler_flavor"] = cls.__name__ # type: ignore[attr-defined] | ||
if values["scaler_flavor"] not in cls.ALLOWED_SCALER_FLAVORS: | ||
raise ValueError( | ||
f"Invalid scaler flavor {values['scaler_flavor']}. " | ||
f"Allowed values are {cls.ALLOWED_SCALER_FLAVORS}" | ||
) | ||
return values | ||
|
||
def run(self, step_function: F, **kwargs: Any) -> Any: | ||
"""Run the step using scaler. | ||
|
||
Args: | ||
step_function: The step function to run. | ||
**kwargs: Additional arguments to pass to the step function. | ||
|
||
Returns: | ||
The result of the step function as per scaler config. | ||
|
||
Raises: | ||
NotImplementedError: If the scaler flavor is not supported. | ||
""" | ||
if self.scaler_flavor == "AccelerateScaler": | ||
from zenml.integrations.accelerate import AccelerateScaler | ||
|
||
runner = AccelerateScaler(**self.dict()) | ||
elif self.scaler_flavor == "AggregateScaler": | ||
from zenml.scalers import AggregateScaler | ||
|
||
runner = AggregateScaler(**self.dict()) # type: ignore[assignment] | ||
else: | ||
raise NotImplementedError | ||
|
||
return runner.run(step_function, **kwargs) | ||
|
||
class Config: | ||
"""Pydantic model configuration.""" | ||
|
||
extra = "allow" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
from zenml.scalers.aggregate_scaler import AggregateScaler | ||
|
||
__all__ = [ | ||
"AggregateScaler", | ||
] |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
is this an accelerate integration or is this just part of our huggingface integration? I'm pretty sure you'll get accelerate already with the packages we have defined there?