id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
2,966 | import importlib
import importlib.metadata
import os
import warnings
from functools import lru_cache
import torch
from packaging import version
from packaging.version import parse
from .environment import parse_flag_from_env, str_to_bool
from .versions import compare_versions, is_torch_version
def _is_package_available(pkg_name, metadata_name=None):
def is_boto3_available():
return _is_package_available("boto3") | null |
2,967 | import importlib
import importlib.metadata
import os
import warnings
from functools import lru_cache
import torch
from packaging import version
from packaging.version import parse
from .environment import parse_flag_from_env, str_to_bool
from .versions import compare_versions, is_torch_version
def _is_package_available(pkg_name, metadata_name=None):
# Check we're not importing a "pkg_name" directory somewhere but the actual library by trying to grab the version
package_exists = importlib.util.find_spec(pkg_name) is not None
if package_exists:
try:
# Some libraries have different names in the metadata
_ = importlib.metadata.metadata(pkg_name if metadata_name is None else metadata_name)
return True
except importlib.metadata.PackageNotFoundError:
return False
def parse_flag_from_env(key, default=False):
"""Returns truthy value for `key` from the env if available else the default."""
value = os.environ.get(key, str(default))
return str_to_bool(value) == 1 # As its name indicates `str_to_bool` actually returns an int...
def is_rich_available():
if _is_package_available("rich"):
if "ACCELERATE_DISABLE_RICH" in os.environ:
warnings.warn(
"`ACCELERATE_DISABLE_RICH` is deprecated and will be removed in v0.22.0 and deactivated by default. Please use `ACCELERATE_ENABLE_RICH` if you wish to use `rich`."
)
return not parse_flag_from_env("ACCELERATE_DISABLE_RICH", False)
return parse_flag_from_env("ACCELERATE_ENABLE_RICH", False)
return False | null |
2,968 | import importlib
import importlib.metadata
import os
import warnings
from functools import lru_cache
import torch
from packaging import version
from packaging.version import parse
from .environment import parse_flag_from_env, str_to_bool
from .versions import compare_versions, is_torch_version
def _is_package_available(pkg_name, metadata_name=None):
# Check we're not importing a "pkg_name" directory somewhere but the actual library by trying to grab the version
package_exists = importlib.util.find_spec(pkg_name) is not None
if package_exists:
try:
# Some libraries have different names in the metadata
_ = importlib.metadata.metadata(pkg_name if metadata_name is None else metadata_name)
return True
except importlib.metadata.PackageNotFoundError:
return False
def is_sagemaker_available():
return _is_package_available("sagemaker") | null |
2,969 | import importlib
import importlib.metadata
import os
import warnings
from functools import lru_cache
import torch
from packaging import version
from packaging.version import parse
from .environment import parse_flag_from_env, str_to_bool
from .versions import compare_versions, is_torch_version
def _is_package_available(pkg_name, metadata_name=None):
def is_clearml_available():
return _is_package_available("clearml") | null |
2,970 | import importlib
import importlib.metadata
import os
import warnings
from functools import lru_cache
import torch
from packaging import version
from packaging.version import parse
from .environment import parse_flag_from_env, str_to_bool
from .versions import compare_versions, is_torch_version
def _is_package_available(pkg_name, metadata_name=None):
def is_pandas_available():
return _is_package_available("pandas") | null |
2,971 | import importlib
import importlib.metadata
import os
import warnings
from functools import lru_cache
import torch
from packaging import version
from packaging.version import parse
from .environment import parse_flag_from_env, str_to_bool
from .versions import compare_versions, is_torch_version
def _is_package_available(pkg_name, metadata_name=None):
def is_mlflow_available():
if _is_package_available("mlflow"):
return True
if importlib.util.find_spec("mlflow") is not None:
try:
_ = importlib.metadata.metadata("mlflow-skinny")
return True
except importlib.metadata.PackageNotFoundError:
return False
return False | null |
2,972 | import importlib
import importlib.metadata
import os
import warnings
from functools import lru_cache
import torch
from packaging import version
from packaging.version import parse
from .environment import parse_flag_from_env, str_to_bool
from .versions import compare_versions, is_torch_version
def _is_package_available(pkg_name, metadata_name=None):
# Check we're not importing a "pkg_name" directory somewhere but the actual library by trying to grab the version
package_exists = importlib.util.find_spec(pkg_name) is not None
if package_exists:
try:
# Some libraries have different names in the metadata
_ = importlib.metadata.metadata(pkg_name if metadata_name is None else metadata_name)
return True
except importlib.metadata.PackageNotFoundError:
return False
def is_dvclive_available():
return _is_package_available("dvclive") | null |
2,973 | import contextlib
import gc
import importlib
import inspect
import json
import logging
import os
import re
import shutil
import tempfile
import warnings
from collections import OrderedDict, defaultdict
from typing import Dict, List, Optional, Tuple, Union
import packaging
import torch
import torch.nn as nn
from ..state import AcceleratorState
from .constants import SAFE_WEIGHTS_NAME, WEIGHTS_NAME
from .dataclasses import AutocastKwargs, CustomDtype, DistributedType
from .imports import is_mps_available, is_npu_available, is_peft_available, is_torch_xla_available, is_xpu_available
from .offload import load_offloaded_weight, offload_weight, save_offload_index
from .tqdm import is_tqdm_available, tqdm
from .versions import compare_versions
from safetensors import safe_open
from safetensors.torch import load_file as safe_load_file
def convert_file_size_to_int(size: Union[int, str]):
"""
Converts a size expressed as a string with digits an unit (like `"5MB"`) to an integer (in bytes).
Args:
size (`int` or `str`): The size to convert. Will be directly returned if an `int`.
Example:
```py
>>> convert_file_size_to_int("1MiB")
1048576
```
"""
mem_size = -1
err_msg = (
f"`size` {size} is not in a valid format. Use an integer for bytes, or a string with an unit (like '5.0GB')."
)
try:
if isinstance(size, int):
mem_size = size
elif size.upper().endswith("GIB"):
mem_size = int(float(size[:-3]) * (2**30))
elif size.upper().endswith("MIB"):
mem_size = int(float(size[:-3]) * (2**20))
elif size.upper().endswith("KIB"):
mem_size = int(float(size[:-3]) * (2**10))
elif size.upper().endswith("GB"):
int_size = int(float(size[:-2]) * (10**9))
mem_size = int_size // 8 if size.endswith("b") else int_size
elif size.upper().endswith("MB"):
int_size = int(float(size[:-2]) * (10**6))
mem_size = int_size // 8 if size.endswith("b") else int_size
elif size.upper().endswith("KB"):
int_size = int(float(size[:-2]) * (10**3))
mem_size = int_size // 8 if size.endswith("b") else int_size
except ValueError:
raise ValueError(err_msg)
if mem_size < 0:
raise ValueError(err_msg)
return mem_size
def dtype_byte_size(dtype: torch.dtype):
"""
Returns the size (in bytes) occupied by one parameter of type `dtype`.
Example:
```py
>>> dtype_byte_size(torch.float32)
4
```
"""
if dtype == torch.bool:
return 1 / 8
elif dtype == CustomDtype.INT2:
return 1 / 4
elif dtype == CustomDtype.INT4:
return 1 / 2
elif dtype == CustomDtype.FP8:
return 1
bit_search = re.search(r"[^\d](\d+)$", str(dtype))
if bit_search is None:
raise ValueError(f"`dtype` is not a valid dtype: {dtype}.")
bit_size = int(bit_search.groups()[0])
return bit_size // 8
def id_tensor_storage(tensor: torch.Tensor) -> Tuple[torch.device, int, int]:
"""
Unique identifier to a tensor storage. Multiple different tensors can share the same underlying storage. For
example, "meta" tensors all share the same storage, and thus their identifier will all be equal. This identifier is
guaranteed to be unique and constant for this tensor's storage during its lifetime. Two tensor storages with
non-overlapping lifetimes may have the same id.
"""
_SIZE = {
torch.int64: 8,
torch.float32: 4,
torch.int32: 4,
torch.bfloat16: 2,
torch.float16: 2,
torch.int16: 2,
torch.uint8: 1,
torch.int8: 1,
torch.bool: 1,
torch.float64: 8,
}
try:
storage_ptr = tensor.untyped_storage().data_ptr()
storage_size = tensor.untyped_storage().nbytes()
except Exception:
# Fallback for torch==1.10
try:
storage_ptr = tensor.storage().data_ptr()
storage_size = tensor.storage().size() * _SIZE[tensor.dtype]
except NotImplementedError:
# Fallback for meta storage
storage_ptr = 0
# On torch >=2.0 this is the tensor size
storage_size = tensor.nelement() * _SIZE[tensor.dtype]
return tensor.device, storage_ptr, storage_size
WEIGHTS_NAME = f"{MODEL_NAME}.bin"
The provided code snippet includes necessary dependencies for implementing the `shard_checkpoint` function. Write a Python function `def shard_checkpoint( state_dict: Dict[str, torch.Tensor], max_shard_size: Union[int, str] = "10GB", weights_name: str = WEIGHTS_NAME )` to solve the following problem:
Splits a model state dictionary in sub-checkpoints so that the final size of each sub-checkpoint does not exceed a given size. The sub-checkpoints are determined by iterating through the `state_dict` in the order of its keys, so there is no optimization made to make each sub-checkpoint as close as possible to the maximum size passed. For example, if the limit is 10GB and we have weights of sizes [6GB, 6GB, 2GB, 6GB, 2GB, 2GB] they will get sharded as [6GB], [6+2GB], [6+2+2GB] and not [6+2+2GB], [6+2GB], [6GB]. <Tip warning={true}> If one of the model's weight is bigger that `max_sahrd_size`, it will end up in its own sub-checkpoint which will have a size greater than `max_shard_size`. </Tip> Args: state_dict (`Dict[str, torch.Tensor]`): The state dictionary of a model to save. max_shard_size (`int` or `str`, *optional*, defaults to `"10GB"`): The maximum size of each sub-checkpoint. If expressed as a string, needs to be digits followed by a unit (like `"5MB"`). weights_name (`str`, *optional*, defaults to `"pytorch_model.bin"`): The name of the model save file.
Here is the function:
def shard_checkpoint(
state_dict: Dict[str, torch.Tensor], max_shard_size: Union[int, str] = "10GB", weights_name: str = WEIGHTS_NAME
):
"""
Splits a model state dictionary in sub-checkpoints so that the final size of each sub-checkpoint does not exceed a
given size.
The sub-checkpoints are determined by iterating through the `state_dict` in the order of its keys, so there is no
optimization made to make each sub-checkpoint as close as possible to the maximum size passed. For example, if the
limit is 10GB and we have weights of sizes [6GB, 6GB, 2GB, 6GB, 2GB, 2GB] they will get sharded as [6GB], [6+2GB],
[6+2+2GB] and not [6+2+2GB], [6+2GB], [6GB].
<Tip warning={true}>
If one of the model's weight is bigger that `max_sahrd_size`, it will end up in its own sub-checkpoint which will
have a size greater than `max_shard_size`.
</Tip>
Args:
state_dict (`Dict[str, torch.Tensor]`): The state dictionary of a model to save.
max_shard_size (`int` or `str`, *optional*, defaults to `"10GB"`):
The maximum size of each sub-checkpoint. If expressed as a string, needs to be digits followed by a unit
(like `"5MB"`).
weights_name (`str`, *optional*, defaults to `"pytorch_model.bin"`):
The name of the model save file.
"""
max_shard_size = convert_file_size_to_int(max_shard_size)
sharded_state_dicts = [{}]
last_block_size = 0
total_size = 0
storage_id_to_block = {}
for key, weight in state_dict.items():
# when bnb serialization is used the weights in the state dict can be strings
# check: https://github.com/huggingface/transformers/pull/24416 for more details
if isinstance(weight, str):
continue
else:
storage_id = id_tensor_storage(weight)
# If a `weight` shares the same underlying storage as another tensor, we put `weight` in the same `block`
if storage_id in storage_id_to_block:
block_id = storage_id_to_block[storage_id]
sharded_state_dicts[block_id][key] = weight
continue
weight_size = weight.numel() * dtype_byte_size(weight.dtype)
# If this weight is going to tip up over the maximal size, we split.
if last_block_size + weight_size > max_shard_size:
sharded_state_dicts.append({})
last_block_size = 0
sharded_state_dicts[-1][key] = weight
last_block_size += weight_size
total_size += weight_size
storage_id_to_block[storage_id] = len(sharded_state_dicts) - 1
# If we only have one shard, we return it
if len(sharded_state_dicts) == 1:
return {weights_name: sharded_state_dicts[0]}, None
# Otherwise, let's build the index
weight_map = {}
shards = {}
for idx, shard in enumerate(sharded_state_dicts):
shard_file = weights_name.replace(".bin", f"-{idx + 1:05d}-of-{len(sharded_state_dicts):05d}.bin")
shard_file = shard_file.replace(
".safetensors", f"-{idx + 1:05d}-of-{len(sharded_state_dicts):05d}.safetensors"
)
shards[shard_file] = shard
for key in shard.keys():
weight_map[key] = shard_file
# Add the metadata
metadata = {"total_size": total_size}
index = {"metadata": metadata, "weight_map": weight_map}
return shards, index | Splits a model state dictionary in sub-checkpoints so that the final size of each sub-checkpoint does not exceed a given size. The sub-checkpoints are determined by iterating through the `state_dict` in the order of its keys, so there is no optimization made to make each sub-checkpoint as close as possible to the maximum size passed. For example, if the limit is 10GB and we have weights of sizes [6GB, 6GB, 2GB, 6GB, 2GB, 2GB] they will get sharded as [6GB], [6+2GB], [6+2+2GB] and not [6+2+2GB], [6+2GB], [6GB]. <Tip warning={true}> If one of the model's weight is bigger that `max_sahrd_size`, it will end up in its own sub-checkpoint which will have a size greater than `max_shard_size`. </Tip> Args: state_dict (`Dict[str, torch.Tensor]`): The state dictionary of a model to save. max_shard_size (`int` or `str`, *optional*, defaults to `"10GB"`): The maximum size of each sub-checkpoint. If expressed as a string, needs to be digits followed by a unit (like `"5MB"`). weights_name (`str`, *optional*, defaults to `"pytorch_model.bin"`): The name of the model save file. |
2,974 | import contextlib
import gc
import importlib
import inspect
import json
import logging
import os
import re
import shutil
import tempfile
import warnings
from collections import OrderedDict, defaultdict
from typing import Dict, List, Optional, Tuple, Union
import packaging
import torch
import torch.nn as nn
from ..state import AcceleratorState
from .constants import SAFE_WEIGHTS_NAME, WEIGHTS_NAME
from .dataclasses import AutocastKwargs, CustomDtype, DistributedType
from .imports import is_mps_available, is_npu_available, is_peft_available, is_torch_xla_available, is_xpu_available
from .offload import load_offloaded_weight, offload_weight, save_offload_index
from .tqdm import is_tqdm_available, tqdm
from .versions import compare_versions
from safetensors import safe_open
from safetensors.torch import load_file as safe_load_file
def compute_module_sizes(
model: nn.Module,
dtype: Optional[Union[str, torch.device]] = None,
special_dtypes: Optional[Dict[str, Union[str, torch.device]]] = None,
buffers_only: bool = False,
):
"""
Compute the size of each submodule of a given model.
"""
if dtype is not None:
dtype = _get_proper_dtype(dtype)
dtype_size = dtype_byte_size(dtype)
if special_dtypes is not None:
special_dtypes = {key: _get_proper_dtype(dtyp) for key, dtyp in special_dtypes.items()}
special_dtypes_size = {key: dtype_byte_size(dtyp) for key, dtyp in special_dtypes.items()}
module_sizes = defaultdict(int)
module_list = []
if not buffers_only:
module_list = named_module_tensors(model, recurse=True)
else:
module_list = model.named_buffers(recurse=True)
for name, tensor in module_list:
if special_dtypes is not None and name in special_dtypes:
size = tensor.numel() * special_dtypes_size[name]
elif dtype is None:
size = tensor.numel() * dtype_byte_size(tensor.dtype)
elif str(tensor.dtype).startswith(("torch.uint", "torch.int", "torch.bool")):
# According to the code in set_module_tensor_to_device, these types won't be converted
# so use their original size here
size = tensor.numel() * dtype_byte_size(tensor.dtype)
else:
size = tensor.numel() * min(dtype_size, dtype_byte_size(tensor.dtype))
name_parts = name.split(".")
for idx in range(len(name_parts) + 1):
module_sizes[".".join(name_parts[:idx])] += size
return module_sizes
def get_max_layer_size(
modules: List[Tuple[str, torch.nn.Module]], module_sizes: Dict[str, int], no_split_module_classes: List[str]
):
"""
Utility function that will scan a list of named modules and return the maximum size used by one full layer. The
definition of a layer being:
- a module with no direct children (just parameters and buffers)
- a module whose class name is in the list `no_split_module_classes`
Args:
modules (`List[Tuple[str, torch.nn.Module]]`):
The list of named modules where we want to determine the maximum layer size.
module_sizes (`Dict[str, int]`):
A dictionary mapping each layer name to its size (as generated by `compute_module_sizes`).
no_split_module_classes (`List[str]`):
A list of class names for layers we don't want to be split.
Returns:
`Tuple[int, List[str]]`: The maximum size of a layer with the list of layer names realizing that maximum size.
"""
max_size = 0
layer_names = []
modules_to_treat = modules.copy()
while len(modules_to_treat) > 0:
module_name, module = modules_to_treat.pop(0)
modules_children = list(module.named_children()) if isinstance(module, torch.nn.Module) else []
if len(modules_children) == 0 or module.__class__.__name__ in no_split_module_classes:
# No splitting this one so we compare to the max_size
size = module_sizes[module_name]
if size > max_size:
max_size = size
layer_names = [module_name]
elif size == max_size:
layer_names.append(module_name)
else:
modules_to_treat = [(f"{module_name}.{n}", v) for n, v in modules_children] + modules_to_treat
return max_size, layer_names
The provided code snippet includes necessary dependencies for implementing the `calculate_maximum_sizes` function. Write a Python function `def calculate_maximum_sizes(model: torch.nn.Module)` to solve the following problem:
Computes the total size of the model and its largest layer
Here is the function:
def calculate_maximum_sizes(model: torch.nn.Module):
"Computes the total size of the model and its largest layer"
sizes = compute_module_sizes(model)
# `transformers` models store this information for us
no_split_modules = getattr(model, "_no_split_modules", None)
if no_split_modules is None:
no_split_modules = []
modules_to_treat = (
list(model.named_parameters(recurse=False))
+ list(model.named_children())
+ list(model.named_buffers(recurse=False))
)
largest_layer = get_max_layer_size(modules_to_treat, sizes, no_split_modules)
total_size = sizes[""]
return total_size, largest_layer | Computes the total size of the model and its largest layer |
2,975 | import contextlib
import gc
import importlib
import inspect
import json
import logging
import os
import re
import shutil
import tempfile
import warnings
from collections import OrderedDict, defaultdict
from typing import Dict, List, Optional, Tuple, Union
import packaging
import torch
import torch.nn as nn
from ..state import AcceleratorState
from .constants import SAFE_WEIGHTS_NAME, WEIGHTS_NAME
from .dataclasses import AutocastKwargs, CustomDtype, DistributedType
from .imports import is_mps_available, is_npu_available, is_peft_available, is_torch_xla_available, is_xpu_available
from .offload import load_offloaded_weight, offload_weight, save_offload_index
from .tqdm import is_tqdm_available, tqdm
from .versions import compare_versions
from safetensors import safe_open
from safetensors.torch import load_file as safe_load_file
The provided code snippet includes necessary dependencies for implementing the `check_device_map` function. Write a Python function `def check_device_map(model: nn.Module, device_map: Dict[str, Union[int, str, torch.device]])` to solve the following problem:
Checks a device map covers everything in a given model. Args: model (`torch.nn.Module`): The model to check the device map against. device_map (`Dict[str, Union[int, str, torch.device]]`): The device map to check.
Here is the function:
def check_device_map(model: nn.Module, device_map: Dict[str, Union[int, str, torch.device]]):
"""
Checks a device map covers everything in a given model.
Args:
model (`torch.nn.Module`): The model to check the device map against.
device_map (`Dict[str, Union[int, str, torch.device]]`): The device map to check.
"""
all_model_tensors = [name for name, _ in model.state_dict().items()]
for module_name in device_map.keys():
if module_name == "":
all_model_tensors.clear()
break
else:
all_model_tensors = [
name
for name in all_model_tensors
if not name == module_name and not name.startswith(module_name + ".")
]
if len(all_model_tensors) > 0:
non_covered_params = ", ".join(all_model_tensors)
raise ValueError(
f"The device_map provided does not give any device for the following parameters: {non_covered_params}"
) | Checks a device map covers everything in a given model. Args: model (`torch.nn.Module`): The model to check the device map against. device_map (`Dict[str, Union[int, str, torch.device]]`): The device map to check. |
2,976 | import contextlib
import gc
import importlib
import inspect
import json
import logging
import os
import re
import shutil
import tempfile
import warnings
from collections import OrderedDict, defaultdict
from typing import Dict, List, Optional, Tuple, Union
import packaging
import torch
import torch.nn as nn
from ..state import AcceleratorState
from .constants import SAFE_WEIGHTS_NAME, WEIGHTS_NAME
from .dataclasses import AutocastKwargs, CustomDtype, DistributedType
from .imports import is_mps_available, is_npu_available, is_peft_available, is_torch_xla_available, is_xpu_available
from .offload import load_offloaded_weight, offload_weight, save_offload_index
from .tqdm import is_tqdm_available, tqdm
from .versions import compare_versions
from safetensors import safe_open
from safetensors.torch import load_file as safe_load_file
logger = logging.getLogger(__name__)
class AlignDevicesHook(ModelHook):
"""
A generic `ModelHook` that ensures inputs and model weights are on the same device for the forward pass of the
associated module, potentially offloading the weights after the forward pass.
Args:
execution_device (`torch.device`, *optional*):
The device on which inputs and model weights should be placed before the forward pass.
offload (`bool`, *optional*, defaults to `False`):
Whether or not the weights should be offloaded after the forward pass.
io_same_device (`bool`, *optional*, defaults to `False`):
Whether or not the output should be placed on the same device as the input was.
weights_map (`Mapping[str, torch.Tensor]`, *optional*):
When the model weights are offloaded, a (potentially lazy) map from param names to the tensor values.
offload_buffers (`bool`, *optional*, defaults to `False`):
Whether or not to include the associated module's buffers when offloading.
place_submodules (`bool`, *optional*, defaults to `False`):
Whether to place the submodules on `execution_device` during the `init_hook` event.
"""
def __init__(
self,
execution_device: Optional[Union[int, str, torch.device]] = None,
offload: bool = False,
io_same_device: bool = False,
weights_map: Optional[Mapping] = None,
offload_buffers: bool = False,
place_submodules: bool = False,
skip_keys: Optional[Union[str, List[str]]] = None,
tied_params_map: Optional[Dict[int, Dict[torch.device, torch.Tensor]]] = None,
):
self.execution_device = execution_device
self.offload = offload
self.io_same_device = io_same_device
self.weights_map = weights_map
self.offload_buffers = offload_buffers
self.place_submodules = place_submodules
self.skip_keys = skip_keys
# Will contain the input device when `io_same_device=True`.
self.input_device = None
self.param_original_devices = {}
self.buffer_original_devices = {}
self.tied_params_names = set()
# The hook pre_forward/post_forward need to have knowledge of this dictionary, as with offloading we want to avoid duplicating memory
# for tied weights already loaded on the target execution device.
self.tied_params_map = tied_params_map
def __repr__(self):
return (
f"AlignDevicesHook(execution_device={self.execution_device}, offload={self.offload}, "
f"io_same_device={self.io_same_device}, offload_buffers={self.offload_buffers}, "
f"place_submodules={self.place_submodules}, skip_keys={repr(self.skip_keys)})"
)
def init_hook(self, module):
# In case the AlignDevicesHook is on meta device, ignore tied weights as data_ptr() is then always zero.
if self.execution_device == "meta" or self.execution_device == torch.device("meta"):
self.tied_params_map = None
if not self.offload and self.execution_device is not None:
for name, _ in named_module_tensors(module, recurse=self.place_submodules):
set_module_tensor_to_device(module, name, self.execution_device, tied_params_map=self.tied_params_map)
elif self.offload:
self.original_devices = {
name: param.device for name, param in named_module_tensors(module, recurse=self.place_submodules)
}
if self.weights_map is None:
self.weights_map = {
name: param.to("cpu")
for name, param in named_module_tensors(
module, include_buffers=self.offload_buffers, recurse=self.place_submodules
)
}
for name, _ in named_module_tensors(
module, include_buffers=self.offload_buffers, recurse=self.place_submodules, remove_non_persistent=True
):
# When using disk offloading, we can not rely on `weights_map[name].data_ptr()` as the reference pointer,
# as we have no guarantee that safetensors' `file.get_tensor()` will always give the same pointer.
# As we have no reliable way to track the shared data pointer of tied weights in this case, we use tied_params_names: List[str]
# to add on the fly pointers to `tied_params_map` in the pre_forward call.
if (
self.tied_params_map is not None
and recursive_getattr(module, name).data_ptr() in self.tied_params_map
):
self.tied_params_names.add(name)
set_module_tensor_to_device(module, name, "meta")
if not self.offload_buffers and self.execution_device is not None:
for name, _ in module.named_buffers(recurse=self.place_submodules):
set_module_tensor_to_device(
module, name, self.execution_device, tied_params_map=self.tied_params_map
)
elif self.offload_buffers and self.execution_device is not None:
for name in get_non_persistent_buffers(module, recurse=self.place_submodules):
set_module_tensor_to_device(
module, name, self.execution_device, tied_params_map=self.tied_params_map
)
return module
def pre_forward(self, module, *args, **kwargs):
if self.io_same_device:
self.input_device = find_device([args, kwargs])
if self.offload:
self.tied_pointers_to_remove = set()
for name, _ in named_module_tensors(
module,
include_buffers=self.offload_buffers,
recurse=self.place_submodules,
remove_non_persistent=True,
):
fp16_statistics = None
value = self.weights_map[name]
if "weight" in name and name.replace("weight", "SCB") in self.weights_map.keys():
if value.dtype == torch.int8:
fp16_statistics = self.weights_map[name.replace("weight", "SCB")]
# In case we are using offloading with tied weights, we need to keep track of the offloaded weights
# that are loaded on device at this point, as we will need to remove them as well from the dictionary
# self.tied_params_map in order to allow to free memory.
if name in self.tied_params_names and value.data_ptr() not in self.tied_params_map:
self.tied_params_map[value.data_ptr()] = {}
if (
value is not None
and self.tied_params_map is not None
and value.data_ptr() in self.tied_params_map
and self.execution_device not in self.tied_params_map[value.data_ptr()]
):
self.tied_pointers_to_remove.add((value.data_ptr(), self.execution_device))
set_module_tensor_to_device(
module,
name,
self.execution_device,
value=value,
fp16_statistics=fp16_statistics,
tied_params_map=self.tied_params_map,
)
return send_to_device(args, self.execution_device), send_to_device(
kwargs, self.execution_device, skip_keys=self.skip_keys
)
def post_forward(self, module, output):
if self.offload:
for name, _ in named_module_tensors(
module,
include_buffers=self.offload_buffers,
recurse=self.place_submodules,
remove_non_persistent=True,
):
set_module_tensor_to_device(module, name, "meta")
if type(module).__name__ == "Linear8bitLt":
module.state.SCB = None
module.state.CxB = None
# We may have loaded tied weights into self.tied_params_map (avoiding to load them several times in e.g. submodules): remove them from
# this dictionary to allow the garbage collector to do its job.
for value_pointer, device in self.tied_pointers_to_remove:
del self.tied_params_map[value_pointer][device]
self.tied_pointers_to_remove = set()
if self.io_same_device and self.input_device is not None:
output = send_to_device(output, self.input_device, skip_keys=self.skip_keys)
return output
def detach_hook(self, module):
if self.offload:
for name, device in self.original_devices.items():
if device != torch.device("meta"):
set_module_tensor_to_device(module, name, device, value=self.weights_map.get(name, None))
return module
The provided code snippet includes necessary dependencies for implementing the `get_state_dict_offloaded_model` function. Write a Python function `def get_state_dict_offloaded_model(model: nn.Module)` to solve the following problem:
Returns the state dictionary for an offloaded model via iterative onloading Args: model (`torch.nn.Module`): The offloaded model we want to save
Here is the function:
def get_state_dict_offloaded_model(model: nn.Module):
"""
Returns the state dictionary for an offloaded model via iterative onloading
Args:
model (`torch.nn.Module`):
The offloaded model we want to save
"""
from ..hooks import AlignDevicesHook
state_dict = {}
placeholders = set()
for name, module in model.named_modules():
if name == "":
continue
if hasattr(module, "_hf_hook") and isinstance(module._hf_hook, AlignDevicesHook) and module._hf_hook.offload:
original_device = module._hf_hook.execution_device
# assign hook execution device to cpu
module._hf_hook.execution_device = "cpu"
# onload meta tensors to execution device
try:
module._hf_hook.pre_forward(module)
except MemoryError:
raise MemoryError("Offloaded module must fit in CPU memory to call save_model!") from None
module_state_dict = module.state_dict()
# offload meta tensors from cpu
module._hf_hook.post_forward(module, torch.tensor([]))
# re-assign hook to original execution device
module._hf_hook.execution_device = original_device
else:
module_state_dict = module.state_dict()
for key in module_state_dict:
# ignore placeholder parameters that are still on the meta device
if module_state_dict[key].device == torch.device("meta"):
placeholders.add(name + f".{key}")
continue
params = module_state_dict[key]
state_dict[name + f".{key}"] = params
for key in placeholders.copy():
if key in state_dict:
placeholders.remove(key)
if placeholders:
logger.warning(f"The following tensors were not saved because they were still on meta device: {placeholders}")
return state_dict | Returns the state dictionary for an offloaded model via iterative onloading Args: model (`torch.nn.Module`): The offloaded model we want to save |
2,977 | import contextlib
import gc
import importlib
import inspect
import json
import logging
import os
import re
import shutil
import tempfile
import warnings
from collections import OrderedDict, defaultdict
from typing import Dict, List, Optional, Tuple, Union
import packaging
import torch
import torch.nn as nn
from ..state import AcceleratorState
from .constants import SAFE_WEIGHTS_NAME, WEIGHTS_NAME
from .dataclasses import AutocastKwargs, CustomDtype, DistributedType
from .imports import is_mps_available, is_npu_available, is_peft_available, is_torch_xla_available, is_xpu_available
from .offload import load_offloaded_weight, offload_weight, save_offload_index
from .tqdm import is_tqdm_available, tqdm
from .versions import compare_versions
from safetensors import safe_open
from safetensors.torch import load_file as safe_load_file
class AcceleratorState:
"""
Singleton class that has information about the current training environment.
**Available attributes:**
- **device** (`torch.device`) -- The device to use.
- **distributed_type** ([`~accelerate.state.DistributedType`]) -- The type of distributed environment currently
in use.
- **initialized** (`bool`) -- Whether or not the `AcceleratorState` has been initialized from `Accelerator`.
- **local_process_index** (`int`) -- The index of the current process on the current server.
- **mixed_precision** (`str`) -- Whether or not the current script will use mixed precision, and if so the type
of mixed precision being performed. (Choose from 'no','fp16','bf16 or 'fp8').
- **num_processes** (`int`) -- The number of processes currently launched in parallel.
- **process_index** (`int`) -- The index of the current process.
- **is_last_process** (`bool`) -- Whether or not the current process is the last one.
- **is_main_process** (`bool`) -- Whether or not the current process is the main one.
- **is_local_main_process** (`bool`) -- Whether or not the current process is the main one on the local node.
- **debug** (`bool`) -- Whether or not the current script is being run in debug mode.
"""
_shared_state = SharedDict()
def __init__(
self,
mixed_precision: str = None,
cpu: bool = False,
dynamo_plugin=None,
deepspeed_plugin=None,
fsdp_plugin=None,
megatron_lm_plugin=None,
_from_accelerator: bool = False,
**kwargs,
):
self.__dict__ = self._shared_state
if parse_flag_from_env("ACCELERATE_USE_CPU"):
cpu = True
if PartialState._shared_state == {}:
PartialState(cpu, **kwargs)
self.__dict__.update(PartialState._shared_state)
self._check_initialized(mixed_precision, cpu)
if not self.initialized:
self.deepspeed_plugin = None
self.use_ipex = None
mixed_precision = (
parse_choice_from_env("ACCELERATE_MIXED_PRECISION", "no")
if mixed_precision is None
else mixed_precision.lower()
)
if mixed_precision == "fp8":
if not is_fp8_available():
raise ValueError(
"Using `fp8` precision requires `transformer_engine` or `MS-AMP` to be installed."
)
elif not check_fp8_capability():
logger.warning(
f"The current device has compute capability of {torch.cuda.get_device_capability()} which is "
"insufficient for FP8 mixed precision training (requires a GPU Hopper/Ada Lovelace "
"or higher, compute capability of 8.9 or higher). Will use FP16 instead."
)
mixed_precision = "fp16"
self.dynamo_plugin = dynamo_plugin
if not _from_accelerator:
raise ValueError(
"Please make sure to properly initialize your accelerator via `accelerator = Accelerator()` "
"before using any functionality from the `accelerate` library."
)
# deepspeed handles mixed_precision using deepspeed_config
self._mixed_precision = "no" if self.distributed_type == DistributedType.DEEPSPEED else mixed_precision
if self.distributed_type == DistributedType.XLA and is_torch_xla_available(check_is_tpu=True):
if mixed_precision == "bf16":
if os.environ.get("ACCELERATE_DOWNCAST_BF16"):
os.environ["XLA_USE_BF16"] = str(0)
os.environ["XLA_DOWNCAST_BF16"] = str(1)
self.downcast_bfloat = True
else:
os.environ["XLA_USE_BF16"] = str(1)
os.environ["XLA_DOWNCAST_BF16"] = str(0)
self.downcast_bfloat = False
elif os.environ.get("ACCELERATE_USE_DEEPSPEED", "false") == "true" and not cpu:
self.deepspeed_plugin = deepspeed_plugin
elif self.distributed_type == DistributedType.MULTI_GPU:
if os.environ.get("ACCELERATE_USE_FSDP", "false") == "true":
self.distributed_type = DistributedType.FSDP
if self._mixed_precision != "no":
fsdp_plugin.set_mixed_precision(self._mixed_precision)
self.fsdp_plugin = fsdp_plugin
if os.environ.get("ACCELERATE_USE_MEGATRON_LM", "false") == "true":
self.distributed_type = DistributedType.MEGATRON_LM
megatron_lm_plugin.set_mixed_precision(self._mixed_precision)
self.megatron_lm_plugin = megatron_lm_plugin
elif self.distributed_type == DistributedType.MULTI_NPU:
if os.environ.get("ACCELERATE_USE_FSDP", "false") == "true":
self.distributed_type = DistributedType.FSDP
if self._mixed_precision != "no":
fsdp_plugin.set_mixed_precision(self._mixed_precision)
self.fsdp_plugin = fsdp_plugin
elif self.distributed_type in [DistributedType.MULTI_CPU, DistributedType.MULTI_XPU, DistributedType.NO]:
if is_ipex_available():
"check if user disables it explicitly"
self.use_ipex = parse_flag_from_env("ACCELERATE_USE_IPEX", default=True)
else:
self.use_ipex = False
if self.distributed_type == DistributedType.MULTI_XPU:
if os.environ.get("ACCELERATE_USE_FSDP", "false") == "true":
self.distributed_type = DistributedType.FSDP
if self._mixed_precision != "no":
fsdp_plugin.set_mixed_precision(self._mixed_precision)
self.fsdp_plugin = fsdp_plugin
if (
self.dynamo_plugin.backend != DynamoBackend.NO
and self._mixed_precision == "no"
and self.device.type == "cuda"
):
torch.backends.cuda.matmul.allow_tf32 = True
PartialState._shared_state["distributed_type"] = self.distributed_type
def initialized(self) -> bool:
return self._shared_state != PartialState._shared_state
def __repr__(self):
repr = PartialState().__repr__() + f"\nMixed precision type: {self.mixed_precision}\n"
if self.distributed_type == DistributedType.DEEPSPEED:
repr += f"ds_config: {self.deepspeed_plugin.deepspeed_config}\n"
return repr
def _check_initialized(self, mixed_precision=None, cpu=None):
"Checks if a modification is trying to be made and the `AcceleratorState` has already been initialized"
if self.initialized:
err = "AcceleratorState has already been initialized and cannot be changed, restart your runtime completely and pass `{flag}` to `Accelerator()`."
if cpu and self.device.type != "cpu":
raise ValueError(err.format(flag="cpu=True"))
if (
mixed_precision is not None
and mixed_precision != self._mixed_precision
and self.distributed_type != DistributedType.DEEPSPEED
):
raise ValueError(err.format(flag=f"mixed_precision='{mixed_precision}'"))
# For backward compatibility
def use_fp16(self):
warnings.warn(
"The `use_fp16` property is deprecated and will be removed in version 1.0 of Accelerate use "
"`AcceleratorState.mixed_precision == 'fp16'` instead.",
FutureWarning,
)
return self._mixed_precision != "no"
def mixed_precision(self):
if self.distributed_type == DistributedType.DEEPSPEED:
config = self.deepspeed_plugin.deepspeed_config
if config.get("fp16", {}).get("enabled", False):
mixed_precision = "fp16"
elif config.get("bf16", {}).get("enabled", False):
mixed_precision = "bf16"
else:
mixed_precision = "no"
else:
mixed_precision = self._mixed_precision
return mixed_precision
def _reset_state(reset_partial_state: bool = False):
"Resets `_shared_state`, is used internally and should not be called"
AcceleratorState._shared_state.clear()
if reset_partial_state:
PartialState._reset_state()
def use_distributed(self):
"""
Whether the Accelerator is configured for distributed training
"""
return PartialState().use_distributed
def is_last_process(self) -> bool:
"Returns whether the current process is the last one"
return PartialState().is_last_process
def is_main_process(self) -> bool:
"Returns whether the current process is the main process"
return PartialState().is_main_process
def is_local_main_process(self) -> bool:
"Returns whether the current process is the main process on the local node"
return PartialState().is_local_main_process
def wait_for_everyone(self):
PartialState().wait_for_everyone()
def split_between_processes(self, inputs: list | tuple | dict | torch.Tensor, apply_padding: bool = False):
"""
Splits `input` between `self.num_processes` quickly and can be then used on that process. Useful when doing
distributed inference, such as with different prompts.
Note that when using a `dict`, all keys need to have the same number of elements.
Args:
inputs (`list`, `tuple`, `torch.Tensor`, or `dict` of `list`/`tuple`/`torch.Tensor`):
The input to split between processes.
apply_padding (`bool`, `optional`, defaults to `False`):
Whether to apply padding by repeating the last element of the input so that all processes have the same
number of elements. Useful when trying to perform actions such as `gather()` on the outputs or passing
in less inputs than there are processes. If so, just remember to drop the padded elements afterwards.
Example:
```python
# Assume there are two processes
from accelerate.state import AcceleratorState
state = AcceleratorState()
with state.split_between_processes(["A", "B", "C"]) as inputs:
print(inputs)
# Process 0
["A", "B"]
# Process 1
["C"]
with state.split_between_processes(["A", "B", "C"], apply_padding=True) as inputs:
print(inputs)
# Process 0
["A", "B"]
# Process 1
["C", "C"]
```
"""
with PartialState().split_between_processes(inputs, apply_padding=apply_padding) as inputs:
yield inputs
def main_process_first(self):
"""
Lets the main process go first inside a with block.
The other processes will enter the with block after the main process exits.
"""
with PartialState().main_process_first():
yield
def local_main_process_first(self):
"""
Lets the local main process go inside a with block.
The other processes will enter the with block after the main process exits.
"""
with PartialState().local_main_process_first():
yield
def print(self, *args, **kwargs):
PartialState().print(*args, **kwargs)
class AutocastKwargs(KwargsHandler):
"""
Use this object in your [`Accelerator`] to customize how `torch.autocast` behaves. Please refer to the
documentation of this [context manager](https://pytorch.org/docs/stable/amp.html#torch.autocast) for more
information on each argument.
Example:
```python
from accelerate import Accelerator
from accelerate.utils import AutocastKwargs
kwargs = AutocastKwargs(cache_enabled=True)
accelerator = Accelerator(kwargs_handlers=[kwargs])
```
"""
enabled: bool = True
cache_enabled: bool = None
class DistributedType(str, enum.Enum):
"""
Represents a type of distributed environment.
Values:
- **NO** -- Not a distributed environment, just a single process.
- **MULTI_CPU** -- Distributed on multiple CPU nodes.
- **MULTI_GPU** -- Distributed on multiple GPUs.
- **MULTI_NPU** -- Distributed on multiple NPUs.
- **MULTI_XPU** -- Distributed on multiple XPUs.
- **DEEPSPEED** -- Using DeepSpeed.
- **XLA** -- Using TorchXLA.
- **TPU** -- This field will be deprecated in v0.27.0. Use XLA instead.
"""
# Subclassing str as well as Enum allows the `DistributedType` to be JSON-serializable out of the box.
NO = "NO"
MULTI_CPU = "MULTI_CPU"
MULTI_GPU = "MULTI_GPU"
MULTI_NPU = "MULTI_NPU"
MULTI_XPU = "MULTI_XPU"
DEEPSPEED = "DEEPSPEED"
FSDP = "FSDP"
XLA = "XLA"
MEGATRON_LM = "MEGATRON_LM"
TPU = DeprecatedFieldDescriptor("TPU", "XLA")
def is_torch_xla_available(check_is_tpu=False, check_is_gpu=False):
"""
Check if `torch_xla` is available. To train a native pytorch job in an environment with torch xla installed, set
the USE_TORCH_XLA to false.
"""
assert not (check_is_tpu and check_is_gpu), "The check_is_tpu and check_is_gpu cannot both be true."
if not _torch_xla_available:
return False
elif check_is_gpu:
return torch_xla.runtime.device_type() in ["GPU", "CUDA"]
elif check_is_tpu:
return torch_xla.runtime.device_type() == "TPU"
return True
The provided code snippet includes necessary dependencies for implementing the `get_mixed_precision_context_manager` function. Write a Python function `def get_mixed_precision_context_manager(native_amp: bool = False, autocast_kwargs: AutocastKwargs = None)` to solve the following problem:
Return a context manager for autocasting mixed precision Args: native_amp (`bool`, *optional*, defaults to False): Whether mixed precision is actually enabled. cache_enabled (`bool`, *optional*, defaults to True): Whether the weight cache inside autocast should be enabled.
Here is the function:
def get_mixed_precision_context_manager(native_amp: bool = False, autocast_kwargs: AutocastKwargs = None):
"""
Return a context manager for autocasting mixed precision
Args:
native_amp (`bool`, *optional*, defaults to False):
Whether mixed precision is actually enabled.
cache_enabled (`bool`, *optional*, defaults to True):
Whether the weight cache inside autocast should be enabled.
"""
state = AcceleratorState()
if autocast_kwargs is None:
autocast_kwargs = {}
else:
autocast_kwargs = autocast_kwargs.to_kwargs()
if native_amp:
device_type = (
"cuda"
if (state.distributed_type == DistributedType.XLA and is_torch_xla_available(check_is_gpu=True))
else state.device.type
)
if state.mixed_precision == "fp16":
return torch.autocast(device_type=device_type, dtype=torch.float16, **autocast_kwargs)
elif state.mixed_precision == "bf16" and state.distributed_type in [
DistributedType.NO,
DistributedType.MULTI_CPU,
DistributedType.MULTI_GPU,
DistributedType.MULTI_NPU,
DistributedType.MULTI_XPU,
DistributedType.FSDP,
DistributedType.XLA,
]:
return torch.autocast(device_type=device_type, dtype=torch.bfloat16, **autocast_kwargs)
else:
return torch.autocast(device_type=device_type, **autocast_kwargs)
else:
return contextlib.nullcontext() | Return a context manager for autocasting mixed precision Args: native_amp (`bool`, *optional*, defaults to False): Whether mixed precision is actually enabled. cache_enabled (`bool`, *optional*, defaults to True): Whether the weight cache inside autocast should be enabled. |
2,978 | import argparse
import os
import subprocess
import sys
import warnings
from ast import literal_eval
from shutil import which
from typing import Any, Dict, List, Tuple
import torch
from ..commands.config.config_args import SageMakerConfig
from ..utils import (
DynamoBackend,
PrecisionType,
is_ipex_available,
is_npu_available,
is_torch_xla_available,
is_xpu_available,
)
from ..utils.constants import DEEPSPEED_MULTINODE_LAUNCHERS
from ..utils.other import is_port_in_use, merge_dicts
from .dataclasses import DistributedType, SageMakerDistributedType
The provided code snippet includes necessary dependencies for implementing the `_filter_args` function. Write a Python function `def _filter_args(args, parser, default_args=[])` to solve the following problem:
Filters out all `accelerate` specific args
Here is the function:
def _filter_args(args, parser, default_args=[]):
"""
Filters out all `accelerate` specific args
"""
new_args, _ = parser.parse_known_args(default_args)
for key, value in vars(args).items():
if key in vars(new_args).keys():
setattr(new_args, key, value)
return new_args | Filters out all `accelerate` specific args |
2,979 | import argparse
import os
import subprocess
import sys
import warnings
from ast import literal_eval
from shutil import which
from typing import Any, Dict, List, Tuple
import torch
from ..commands.config.config_args import SageMakerConfig
from ..utils import (
DynamoBackend,
PrecisionType,
is_ipex_available,
is_npu_available,
is_torch_xla_available,
is_xpu_available,
)
from ..utils.constants import DEEPSPEED_MULTINODE_LAUNCHERS
from ..utils.other import is_port_in_use, merge_dicts
from .dataclasses import DistributedType, SageMakerDistributedType
def _get_mpirun_args():
"""
Determines the executable and argument names for mpirun, based on the type of install. The supported MPI programs
are: OpenMPI, Intel MPI, or MVAPICH.
Returns: Program name and arg names for hostfile, num processes, and processes per node
"""
# Find the MPI program name
mpi_apps = [x for x in ["mpirun", "mpiexec"] if which(x)]
if len(mpi_apps) == 0:
raise OSError("mpirun or mpiexec were not found. Ensure that Intel MPI, Open MPI, or MVAPICH are installed.")
# Call the app with the --version flag to determine which MPI app is installed
mpi_app = mpi_apps[0]
mpirun_version = subprocess.check_output([mpi_app, "--version"])
if b"Open MPI" in mpirun_version:
return mpi_app, "--hostfile", "-n", "--npernode"
else:
# Intel MPI and MVAPICH both use the same arg names
return mpi_app, "-f", "-n", "-ppn"
The provided code snippet includes necessary dependencies for implementing the `prepare_simple_launcher_cmd_env` function. Write a Python function `def prepare_simple_launcher_cmd_env(args: argparse.Namespace) -> Tuple[List[str], Dict[str, str]]` to solve the following problem:
Prepares and returns the command list and an environment with the correct simple launcher environment variables.
Here is the function:
def prepare_simple_launcher_cmd_env(args: argparse.Namespace) -> Tuple[List[str], Dict[str, str]]:
"""
Prepares and returns the command list and an environment with the correct simple launcher environment variables.
"""
cmd = []
if args.no_python and args.module:
raise ValueError("--module and --no_python cannot be used together")
if args.mpirun_hostfile is not None:
mpi_app_name, hostfile_arg, num_proc_arg, proc_per_node_arg = _get_mpirun_args()
mpirun_ccl = getattr(args, "mpirun_ccl", None)
num_machines = args.num_machines
num_processes = getattr(args, "num_processes", None)
nproc_per_node = str(num_processes // num_machines) if num_processes and num_machines else "1"
cmd += [mpi_app_name, hostfile_arg, args.mpirun_hostfile, proc_per_node_arg, nproc_per_node]
if num_processes:
cmd += [num_proc_arg, str(num_processes)]
if not args.no_python:
cmd.append(sys.executable)
if args.module:
cmd.append("-m")
cmd.append(args.training_script)
cmd.extend(args.training_script_args)
current_env = os.environ.copy()
current_env["ACCELERATE_USE_CPU"] = str(args.cpu or args.use_cpu)
if args.debug:
current_env["ACCELERATE_DEBUG_MODE"] = "true"
if args.gpu_ids != "all" and args.gpu_ids is not None:
if is_xpu_available():
current_env["ZE_AFFINITY_MASK"] = args.gpu_ids
elif is_npu_available():
current_env["ASCEND_RT_VISIBLE_DEVICES"] = args.gpu_ids
else:
current_env["CUDA_VISIBLE_DEVICES"] = args.gpu_ids
if args.num_machines > 1:
current_env["MASTER_ADDR"] = args.main_process_ip
current_env["MASTER_PORT"] = str(args.main_process_port)
if args.mpirun_hostfile is not None:
current_env["CCL_WORKER_COUNT"] = mpirun_ccl
elif args.num_processes > 1:
current_env["MASTER_ADDR"] = args.main_process_ip if args.main_process_ip is not None else "127.0.0.1"
current_env["MASTER_PORT"] = str(args.main_process_port) if args.main_process_port is not None else "29500"
try:
mixed_precision = PrecisionType(args.mixed_precision.lower())
except ValueError:
raise ValueError(
f"Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}."
)
current_env["ACCELERATE_MIXED_PRECISION"] = str(mixed_precision)
try:
dynamo_backend = DynamoBackend(args.dynamo_backend.upper())
except ValueError:
raise ValueError(
f"Unknown dynamo backend: {args.dynamo_backend.upper()}. Choose between {DynamoBackend.list()}."
)
current_env["ACCELERATE_DYNAMO_BACKEND"] = dynamo_backend.value
current_env["ACCELERATE_DYNAMO_MODE"] = args.dynamo_mode
current_env["ACCELERATE_DYNAMO_USE_FULLGRAPH"] = str(args.dynamo_use_fullgraph)
current_env["ACCELERATE_DYNAMO_USE_DYNAMIC"] = str(args.dynamo_use_dynamic)
current_env["OMP_NUM_THREADS"] = str(args.num_cpu_threads_per_process)
if is_ipex_available():
current_env["ACCELERATE_USE_IPEX"] = str(args.ipex).lower()
current_env["ACCELERATE_USE_XPU"] = str(args.use_xpu).lower()
return cmd, current_env | Prepares and returns the command list and an environment with the correct simple launcher environment variables. |
2,980 | import argparse
import os
import subprocess
import sys
import warnings
from ast import literal_eval
from shutil import which
from typing import Any, Dict, List, Tuple
import torch
from ..commands.config.config_args import SageMakerConfig
from ..utils import (
DynamoBackend,
PrecisionType,
is_ipex_available,
is_npu_available,
is_torch_xla_available,
is_xpu_available,
)
from ..utils.constants import DEEPSPEED_MULTINODE_LAUNCHERS
from ..utils.other import is_port_in_use, merge_dicts
from .dataclasses import DistributedType, SageMakerDistributedType
def is_port_in_use(port: int = None) -> bool:
"""
Checks if a port is in use on `localhost`. Useful for checking if multiple `accelerate launch` commands have been
run and need to see if the port is already in use.
"""
if port is None:
port = 29500
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
return s.connect_ex(("localhost", port)) == 0
The provided code snippet includes necessary dependencies for implementing the `prepare_multi_gpu_env` function. Write a Python function `def prepare_multi_gpu_env(args: argparse.Namespace) -> Dict[str, str]` to solve the following problem:
Prepares and returns an environment with the correct multi-GPU environment variables.
Here is the function:
def prepare_multi_gpu_env(args: argparse.Namespace) -> Dict[str, str]:
"""
Prepares and returns an environment with the correct multi-GPU environment variables.
"""
num_processes = args.num_processes
num_machines = args.num_machines
main_process_ip = args.main_process_ip
main_process_port = args.main_process_port
if num_machines > 1:
args.nproc_per_node = str(num_processes // num_machines)
args.nnodes = str(num_machines)
args.node_rank = int(args.machine_rank)
if getattr(args, "same_network", False):
args.master_addr = str(main_process_ip)
args.master_port = str(main_process_port)
else:
args.rdzv_endpoint = f"{main_process_ip}:{main_process_port}"
else:
args.nproc_per_node = str(num_processes)
if main_process_port is not None:
args.master_port = str(main_process_port)
if main_process_port is None:
main_process_port = 29500
# only need to check port availability in main process, in case we have to start multiple launchers on the same machine
# for some reasons like splitting log files.
need_port_check = num_machines <= 1 or int(args.machine_rank) == 0
if need_port_check and is_port_in_use(main_process_port):
raise ConnectionError(
f"Tried to launch distributed communication on port `{main_process_port}`, but another process is utilizing it. "
"Please specify a different port (such as using the `--main_process_port` flag or specifying a different `main_process_port` in your config file)"
" and rerun your script. To automatically use the next open port (on a single node), you can set this to `0`."
)
if args.module and args.no_python:
raise ValueError("--module and --no_python cannot be used together")
elif args.module:
args.module = True
elif args.no_python:
args.no_python = True
current_env = os.environ.copy()
if args.debug:
current_env["ACCELERATE_DEBUG_MODE"] = "true"
gpu_ids = getattr(args, "gpu_ids", "all")
if gpu_ids != "all" and args.gpu_ids is not None:
if is_xpu_available():
current_env["ZE_AFFINITY_MASK"] = gpu_ids
elif is_npu_available():
current_env["ASCEND_RT_VISIBLE_DEVICES"] = gpu_ids
else:
current_env["CUDA_VISIBLE_DEVICES"] = gpu_ids
mixed_precision = args.mixed_precision.lower()
try:
mixed_precision = PrecisionType(mixed_precision)
except ValueError:
raise ValueError(f"Unknown mixed_precision mode: {mixed_precision}. Choose between {PrecisionType.list()}.")
current_env["ACCELERATE_MIXED_PRECISION"] = str(mixed_precision)
try:
dynamo_backend = DynamoBackend(args.dynamo_backend.upper())
except ValueError:
raise ValueError(
f"Unknown dynamo backend: {args.dynamo_backend.upper()}. Choose between {DynamoBackend.list()}."
)
current_env["ACCELERATE_DYNAMO_BACKEND"] = dynamo_backend.value
current_env["ACCELERATE_DYNAMO_MODE"] = args.dynamo_mode
current_env["ACCELERATE_DYNAMO_USE_FULLGRAPH"] = str(args.dynamo_use_fullgraph)
current_env["ACCELERATE_DYNAMO_USE_DYNAMIC"] = str(args.dynamo_use_dynamic)
if args.use_fsdp:
current_env["ACCELERATE_USE_FSDP"] = "true"
if args.fsdp_cpu_ram_efficient_loading and not args.fsdp_sync_module_states:
raise ValueError("When using `--fsdp_cpu_ram_efficient_loading` set `--fsdp_sync_module_states` to `True`")
current_env["FSDP_SHARDING_STRATEGY"] = str(args.fsdp_sharding_strategy)
current_env["FSDP_OFFLOAD_PARAMS"] = str(args.fsdp_offload_params).lower()
current_env["FSDP_MIN_NUM_PARAMS"] = str(args.fsdp_min_num_params)
if args.fsdp_auto_wrap_policy is not None:
current_env["FSDP_AUTO_WRAP_POLICY"] = str(args.fsdp_auto_wrap_policy)
if args.fsdp_transformer_layer_cls_to_wrap is not None:
current_env["FSDP_TRANSFORMER_CLS_TO_WRAP"] = str(args.fsdp_transformer_layer_cls_to_wrap)
if args.fsdp_backward_prefetch_policy is not None:
warnings.warn(
"`fsdp_backward_prefetch_policy` is deprecated and will be removed in version 0.27.0 of 🤗 Accelerate. Use"
" `fsdp_backward_prefetch` instead",
FutureWarning,
)
args.fsdp_backward_prefetch = args.fsdp_backward_prefetch_policy
if args.fsdp_backward_prefetch is not None:
current_env["FSDP_BACKWARD_PREFETCH"] = str(args.fsdp_backward_prefetch)
if args.fsdp_state_dict_type is not None:
current_env["FSDP_STATE_DICT_TYPE"] = str(args.fsdp_state_dict_type)
current_env["FSDP_FORWARD_PREFETCH"] = str(args.fsdp_forward_prefetch).lower()
current_env["FSDP_USE_ORIG_PARAMS"] = str(args.fsdp_use_orig_params).lower()
current_env["FSDP_CPU_RAM_EFFICIENT_LOADING"] = str(args.fsdp_cpu_ram_efficient_loading).lower()
current_env["FSDP_SYNC_MODULE_STATES"] = str(args.fsdp_sync_module_states).lower()
if args.use_megatron_lm:
prefix = "MEGATRON_LM_"
current_env["ACCELERATE_USE_MEGATRON_LM"] = "true"
current_env[prefix + "TP_DEGREE"] = str(args.megatron_lm_tp_degree)
current_env[prefix + "PP_DEGREE"] = str(args.megatron_lm_pp_degree)
current_env[prefix + "GRADIENT_CLIPPING"] = str(args.megatron_lm_gradient_clipping)
if args.megatron_lm_num_micro_batches is not None:
current_env[prefix + "NUM_MICRO_BATCHES"] = str(args.megatron_lm_num_micro_batches)
if args.megatron_lm_sequence_parallelism is not None:
current_env[prefix + "SEQUENCE_PARALLELISM"] = str(args.megatron_lm_sequence_parallelism)
if args.megatron_lm_recompute_activations is not None:
current_env[prefix + "RECOMPUTE_ACTIVATIONS"] = str(args.megatron_lm_recompute_activations)
if args.megatron_lm_use_distributed_optimizer is not None:
current_env[prefix + "USE_DISTRIBUTED_OPTIMIZER"] = str(args.megatron_lm_use_distributed_optimizer)
current_env["OMP_NUM_THREADS"] = str(args.num_cpu_threads_per_process)
return current_env | Prepares and returns an environment with the correct multi-GPU environment variables. |
2,981 | import argparse
import os
import subprocess
import sys
import warnings
from ast import literal_eval
from shutil import which
from typing import Any, Dict, List, Tuple
import torch
from ..commands.config.config_args import SageMakerConfig
from ..utils import (
DynamoBackend,
PrecisionType,
is_ipex_available,
is_npu_available,
is_torch_xla_available,
is_xpu_available,
)
from ..utils.constants import DEEPSPEED_MULTINODE_LAUNCHERS
from ..utils.other import is_port_in_use, merge_dicts
from .dataclasses import DistributedType, SageMakerDistributedType
def env_var_path_add(env_var_name, path_to_add):
"""
Extends a path-based environment variable's value with a new path and returns the updated value. It's up to the
caller to set it in os.environ.
"""
paths = [p for p in os.environ.get(env_var_name, "").split(":") if len(p) > 0]
paths.append(str(path_to_add))
return ":".join(paths)
DEEPSPEED_MULTINODE_LAUNCHERS = ["pdsh", "standard", "openmpi", "mvapich", "mpich"]
def is_port_in_use(port: int = None) -> bool:
"""
Checks if a port is in use on `localhost`. Useful for checking if multiple `accelerate launch` commands have been
run and need to see if the port is already in use.
"""
if port is None:
port = 29500
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
return s.connect_ex(("localhost", port)) == 0
The provided code snippet includes necessary dependencies for implementing the `prepare_deepspeed_cmd_env` function. Write a Python function `def prepare_deepspeed_cmd_env(args: argparse.Namespace) -> Tuple[List[str], Dict[str, str]]` to solve the following problem:
Prepares and returns the command list and an environment with the correct DeepSpeed environment variables.
Here is the function:
def prepare_deepspeed_cmd_env(args: argparse.Namespace) -> Tuple[List[str], Dict[str, str]]:
"""
Prepares and returns the command list and an environment with the correct DeepSpeed environment variables.
"""
num_processes = args.num_processes
num_machines = args.num_machines
main_process_ip = args.main_process_ip
main_process_port = args.main_process_port
cmd = None
# make sure launcher is not None
if args.deepspeed_multinode_launcher is None:
# set to default pdsh
args.deepspeed_multinode_launcher = DEEPSPEED_MULTINODE_LAUNCHERS[0]
if num_machines > 1 and args.deepspeed_multinode_launcher != DEEPSPEED_MULTINODE_LAUNCHERS[1]:
cmd = ["deepspeed", "--no_local_rank"]
cmd.extend(["--hostfile", str(args.deepspeed_hostfile), "--launcher", str(args.deepspeed_multinode_launcher)])
if args.deepspeed_exclusion_filter is not None:
cmd.extend(
[
"--exclude",
str(args.deepspeed_exclusion_filter),
]
)
elif args.deepspeed_inclusion_filter is not None:
cmd.extend(
[
"--include",
str(args.deepspeed_inclusion_filter),
]
)
else:
cmd.extend(["--num_gpus", str(args.num_processes // args.num_machines)])
if main_process_ip:
cmd.extend(["--master_addr", str(main_process_ip)])
cmd.extend(["--master_port", str(main_process_port)])
if args.module and args.no_python:
raise ValueError("--module and --no_python cannot be used together")
elif args.module:
cmd.append("--module")
elif args.no_python:
cmd.append("--no_python")
cmd.append(args.training_script)
cmd.extend(args.training_script_args)
elif num_machines > 1 and args.deepspeed_multinode_launcher == DEEPSPEED_MULTINODE_LAUNCHERS[1]:
args.nproc_per_node = str(num_processes // num_machines)
args.nnodes = str(num_machines)
args.node_rank = int(args.machine_rank)
if getattr(args, "same_network", False):
args.master_addr = str(main_process_ip)
args.master_port = str(main_process_port)
else:
args.rdzv_endpoint = f"{main_process_ip}:{main_process_port}"
else:
args.nproc_per_node = str(num_processes)
if main_process_port is not None:
args.master_port = str(main_process_port)
if main_process_port is None:
main_process_port = 29500
# only need to check port availability in main process, in case we have to start multiple launchers on the same machine
# for some reasons like splitting log files.
need_port_check = num_machines <= 1 or int(args.machine_rank) == 0
if need_port_check and is_port_in_use(main_process_port):
raise ConnectionError(
f"Tried to launch distributed communication on port `{main_process_port}`, but another process is utilizing it. "
"Please specify a different port (such as using the `--main_process_port` flag or specifying a different `main_process_port` in your config file)"
" and rerun your script. To automatically use the next open port (on a single node), you can set this to `0`."
)
if args.module and args.no_python:
raise ValueError("--module and --no_python cannot be used together")
elif args.module:
args.module = True
elif args.no_python:
args.no_python = True
current_env = os.environ.copy()
if args.debug:
current_env["ACCELERATE_DEBUG_MODE"] = "true"
gpu_ids = getattr(args, "gpu_ids", "all")
if gpu_ids != "all" and args.gpu_ids is not None:
if is_xpu_available():
current_env["ZE_AFFINITY_MASK"] = gpu_ids
elif is_npu_available():
current_env["ASCEND_RT_VISIBLE_DEVICES"] = gpu_ids
else:
current_env["CUDA_VISIBLE_DEVICES"] = gpu_ids
try:
mixed_precision = PrecisionType(args.mixed_precision.lower())
except ValueError:
raise ValueError(
f"Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}."
)
current_env["PYTHONPATH"] = env_var_path_add("PYTHONPATH", os.path.abspath("."))
current_env["ACCELERATE_MIXED_PRECISION"] = str(mixed_precision)
current_env["ACCELERATE_CONFIG_DS_FIELDS"] = str(args.deepspeed_fields_from_accelerate_config).lower()
current_env["ACCELERATE_USE_DEEPSPEED"] = "true"
if args.zero_stage is not None:
current_env["ACCELERATE_DEEPSPEED_ZERO_STAGE"] = str(args.zero_stage)
if args.gradient_accumulation_steps is not None:
current_env["ACCELERATE_GRADIENT_ACCUMULATION_STEPS"] = str(args.gradient_accumulation_steps)
if args.gradient_clipping is not None:
current_env["ACCELERATE_GRADIENT_CLIPPING"] = str(args.gradient_clipping).lower()
if args.offload_optimizer_device is not None:
current_env["ACCELERATE_DEEPSPEED_OFFLOAD_OPTIMIZER_DEVICE"] = str(args.offload_optimizer_device).lower()
if args.offload_param_device is not None:
current_env["ACCELERATE_DEEPSPEED_OFFLOAD_PARAM_DEVICE"] = str(args.offload_param_device).lower()
if args.zero3_init_flag is not None:
current_env["ACCELERATE_DEEPSPEED_ZERO3_INIT"] = str(args.zero3_init_flag).lower()
if args.zero3_save_16bit_model is not None:
current_env["ACCELERATE_DEEPSPEED_ZERO3_SAVE_16BIT_MODEL"] = str(args.zero3_save_16bit_model).lower()
if args.deepspeed_config_file is not None:
current_env["ACCELERATE_DEEPSPEED_CONFIG_FILE"] = str(args.deepspeed_config_file)
return cmd, current_env | Prepares and returns the command list and an environment with the correct DeepSpeed environment variables. |
2,982 | import argparse
import os
import subprocess
import sys
import warnings
from ast import literal_eval
from shutil import which
from typing import Any, Dict, List, Tuple
import torch
from ..commands.config.config_args import SageMakerConfig
from ..utils import (
DynamoBackend,
PrecisionType,
is_ipex_available,
is_npu_available,
is_torch_xla_available,
is_xpu_available,
)
from ..utils.constants import DEEPSPEED_MULTINODE_LAUNCHERS
from ..utils.other import is_port_in_use, merge_dicts
from .dataclasses import DistributedType, SageMakerDistributedType
The provided code snippet includes necessary dependencies for implementing the `prepare_tpu` function. Write a Python function `def prepare_tpu( args: argparse.Namespace, current_env: Dict[str, str], pod: bool = False ) -> Tuple[argparse.Namespace, Dict[str, str]]` to solve the following problem:
Prepares and returns an environment with the correct TPU environment variables.
Here is the function:
def prepare_tpu(
args: argparse.Namespace, current_env: Dict[str, str], pod: bool = False
) -> Tuple[argparse.Namespace, Dict[str, str]]:
"""
Prepares and returns an environment with the correct TPU environment variables.
"""
if args.mixed_precision == "bf16" and is_torch_xla_available(check_is_tpu=True):
if args.downcast_bf16:
current_env["XLA_DOWNCAST_BF16"] = "1"
else:
current_env["XLA_USE_BF16"] = "1"
if args.debug:
current_env["ACCELERATE_DEBUG_MODE"] = "true"
if pod:
# Take explicit args and set them up for XLA
args.vm = args.tpu_vm
args.tpu = args.tpu_name
return args, current_env | Prepares and returns an environment with the correct TPU environment variables. |
2,983 | import argparse
import os
import subprocess
import sys
import warnings
from ast import literal_eval
from shutil import which
from typing import Any, Dict, List, Tuple
import torch
from ..commands.config.config_args import SageMakerConfig
from ..utils import (
DynamoBackend,
PrecisionType,
is_ipex_available,
is_npu_available,
is_torch_xla_available,
is_xpu_available,
)
from ..utils.constants import DEEPSPEED_MULTINODE_LAUNCHERS
from ..utils.other import is_port_in_use, merge_dicts
from .dataclasses import DistributedType, SageMakerDistributedType
def _convert_nargs_to_dict(nargs: List[str]) -> Dict[str, str]:
if len(nargs) < 0:
return {}
# helper function to infer type for argsparser
def _infer_type(s):
try:
s = float(s)
if s // 1 == s:
return int(s)
return s
except ValueError:
return s
parser = argparse.ArgumentParser()
_, unknown = parser.parse_known_args(nargs)
for index, argument in enumerate(unknown):
if argument.startswith(("-", "--")):
action = None
if index + 1 < len(unknown): # checks if next index would be in list
if unknown[index + 1].startswith(("-", "--")): # checks if next element is an key
# raise an error if element is store_true or store_false
raise ValueError(
"SageMaker doesn’t support argparse actions for `store_true` or `store_false`. Please define explicit types"
)
else: # raise an error if last element is store_true or store_false
raise ValueError(
"SageMaker doesn’t support argparse actions for `store_true` or `store_false`. Please define explicit types"
)
# adds argument to parser based on action_store true
if action is None:
parser.add_argument(argument, type=_infer_type)
else:
parser.add_argument(argument, action=action)
return {
key: (literal_eval(value) if value in ("True", "False") else value)
for key, value in parser.parse_args(nargs).__dict__.items()
}
class SageMakerConfig(BaseConfig):
ec2_instance_type: str
iam_role_name: str
image_uri: Optional[str] = None
profile: Optional[str] = None
region: str = "us-east-1"
num_machines: int = 1
gpu_ids: str = "all"
base_job_name: str = f"accelerate-sagemaker-{num_machines}"
pytorch_version: str = SAGEMAKER_PYTORCH_VERSION
transformers_version: str = SAGEMAKER_TRANSFORMERS_VERSION
py_version: str = SAGEMAKER_PYTHON_VERSION
sagemaker_inputs_file: str = None
sagemaker_metrics_file: str = None
additional_args: dict = None
dynamo_config: dict = None
def merge_dicts(source, destination):
"""
Recursively merges two dictionaries.
Args:
source (`dict`): The dictionary to merge into `destination`.
destination (`dict`): The dictionary to merge `source` into.
"""
for key, value in source.items():
if isinstance(value, dict):
node = destination.setdefault(key, {})
merge_dicts(value, node)
else:
destination[key] = value
return destination
class SageMakerDistributedType(str, enum.Enum):
"""
Represents a type of distributed environment.
Values:
- **NO** -- Not a distributed environment, just a single process.
- **DATA_PARALLEL** -- using sagemaker distributed data parallelism.
- **MODEL_PARALLEL** -- using sagemaker distributed model parallelism.
"""
# Subclassing str as well as Enum allows the `SageMakerDistributedType` to be JSON-serializable out of the box.
NO = "NO"
DATA_PARALLEL = "DATA_PARALLEL"
MODEL_PARALLEL = "MODEL_PARALLEL"
def prepare_sagemager_args_inputs(
sagemaker_config: SageMakerConfig, args: argparse.Namespace
) -> Tuple[argparse.Namespace, Dict[str, Any]]:
# configure environment
print("Configuring Amazon SageMaker environment")
os.environ["AWS_DEFAULT_REGION"] = sagemaker_config.region
# configure credentials
if sagemaker_config.profile is not None:
os.environ["AWS_PROFILE"] = sagemaker_config.profile
elif args.aws_access_key_id is not None and args.aws_secret_access_key is not None:
os.environ["AWS_ACCESS_KEY_ID"] = args.aws_access_key_id
os.environ["AWS_SECRET_ACCESS_KEY"] = args.aws_secret_access_key
else:
raise OSError("You need to provide an aws_access_key_id and aws_secret_access_key when not using aws_profile")
# extract needed arguments
source_dir = os.path.dirname(args.training_script)
if not source_dir: # checks if string is empty
source_dir = "."
entry_point = os.path.basename(args.training_script)
if not entry_point.endswith(".py"):
raise ValueError(f'Your training script should be a python script and not "{entry_point}"')
print("Converting Arguments to Hyperparameters")
hyperparameters = _convert_nargs_to_dict(args.training_script_args)
try:
mixed_precision = PrecisionType(args.mixed_precision.lower())
except ValueError:
raise ValueError(
f"Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}."
)
try:
dynamo_backend = DynamoBackend(args.dynamo_backend.upper())
except ValueError:
raise ValueError(
f"Unknown dynamo backend: {args.dynamo_backend.upper()}. Choose between {DynamoBackend.list()}."
)
# Environment variables to be set for use during training job
environment = {
"ACCELERATE_USE_SAGEMAKER": "true",
"ACCELERATE_MIXED_PRECISION": str(mixed_precision),
"ACCELERATE_DYNAMO_BACKEND": dynamo_backend.value,
"ACCELERATE_DYNAMO_MODE": args.dynamo_mode,
"ACCELERATE_DYNAMO_USE_FULLGRAPH": str(args.dynamo_use_fullgraph),
"ACCELERATE_DYNAMO_USE_DYNAMIC": str(args.dynamo_use_dynamic),
"ACCELERATE_SAGEMAKER_DISTRIBUTED_TYPE": sagemaker_config.distributed_type.value,
}
# configure distribution set up
distribution = None
if sagemaker_config.distributed_type == SageMakerDistributedType.DATA_PARALLEL:
distribution = {"smdistributed": {"dataparallel": {"enabled": True}}}
# configure sagemaker inputs
sagemaker_inputs = None
if sagemaker_config.sagemaker_inputs_file is not None:
print(f"Loading SageMaker Inputs from {sagemaker_config.sagemaker_inputs_file} file")
sagemaker_inputs = {}
with open(sagemaker_config.sagemaker_inputs_file) as file:
for i, line in enumerate(file):
if i == 0:
continue
l = line.split("\t")
sagemaker_inputs[l[0]] = l[1].strip()
print(f"Loaded SageMaker Inputs: {sagemaker_inputs}")
# configure sagemaker metrics
sagemaker_metrics = None
if sagemaker_config.sagemaker_metrics_file is not None:
print(f"Loading SageMaker Metrics from {sagemaker_config.sagemaker_metrics_file} file")
sagemaker_metrics = []
with open(sagemaker_config.sagemaker_metrics_file) as file:
for i, line in enumerate(file):
if i == 0:
continue
l = line.split("\t")
metric_dict = {
"Name": l[0],
"Regex": l[1].strip(),
}
sagemaker_metrics.append(metric_dict)
print(f"Loaded SageMaker Metrics: {sagemaker_metrics}")
# configure session
print("Creating Estimator")
args = {
"image_uri": sagemaker_config.image_uri,
"entry_point": entry_point,
"source_dir": source_dir,
"role": sagemaker_config.iam_role_name,
"transformers_version": sagemaker_config.transformers_version,
"pytorch_version": sagemaker_config.pytorch_version,
"py_version": sagemaker_config.py_version,
"base_job_name": sagemaker_config.base_job_name,
"instance_count": sagemaker_config.num_machines,
"instance_type": sagemaker_config.ec2_instance_type,
"debugger_hook_config": False,
"distribution": distribution,
"hyperparameters": hyperparameters,
"environment": environment,
"metric_definitions": sagemaker_metrics,
}
if sagemaker_config.additional_args is not None:
args = merge_dicts(sagemaker_config.additional_args, args)
return args, sagemaker_inputs | null |
2,984 | import argparse
import runhouse as rh
import torch
from nlp_example import training_function
from accelerate.utils import PrepareForLaunch, patch_environment
def training_function(config, args):
# Initialize accelerator
accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision)
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
lr = config["lr"]
num_epochs = int(config["num_epochs"])
seed = int(config["seed"])
batch_size = int(config["batch_size"])
metric = evaluate.load("glue", "mrpc")
# If the batch size is too big we use gradient accumulation
gradient_accumulation_steps = 1
if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.XLA:
gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE
batch_size = MAX_GPU_BATCH_SIZE
set_seed(seed)
train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
model = model.to(accelerator.device)
# Instantiate optimizer
optimizer = AdamW(params=model.parameters(), lr=lr)
# Instantiate scheduler
lr_scheduler = get_linear_schedule_with_warmup(
optimizer=optimizer,
num_warmup_steps=100,
num_training_steps=(len(train_dataloader) * num_epochs) // gradient_accumulation_steps,
)
# Prepare everything
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
# prepare method.
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
)
# Now we train the model
for epoch in range(num_epochs):
model.train()
for step, batch in enumerate(train_dataloader):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device)
outputs = model(**batch)
loss = outputs.loss
loss = loss / gradient_accumulation_steps
accelerator.backward(loss)
if step % gradient_accumulation_steps == 0:
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
model.eval()
for step, batch in enumerate(eval_dataloader):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device)
with torch.no_grad():
outputs = model(**batch)
predictions = outputs.logits.argmax(dim=-1)
predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
metric.add_batch(
predictions=predictions,
references=references,
)
eval_metric = metric.compute()
# Use accelerator.print to print only on the main process.
accelerator.print(f"epoch {epoch}:", eval_metric)
def launch_train(*args):
num_processes = torch.cuda.device_count()
print(f"Device count: {num_processes}")
with patch_environment(
world_size=num_processes, master_addr="127.0.0.1", master_port="29500", mixed_precision=args[1].mixed_precision
):
launcher = PrepareForLaunch(training_function, distributed_type="MULTI_GPU")
torch.multiprocessing.start_processes(launcher, args=args, nprocs=num_processes, start_method="spawn") | null |
2,985 | import argparse
import os
import re
import numpy as np
import PIL
import torch
from timm import create_model
from torch.optim.lr_scheduler import OneCycleLR
from torch.utils.data import DataLoader, Dataset
from torchvision.transforms import Compose, RandomResizedCrop, Resize, ToTensor
from accelerate import Accelerator
def extract_label(fname):
stem = fname.split(os.path.sep)[-1]
return re.search(r"^(.*)_\d+\.jpg$", stem).groups()[0]
class PetsDataset(Dataset):
def __init__(self, file_names, image_transform=None, label_to_id=None):
self.file_names = file_names
self.image_transform = image_transform
self.label_to_id = label_to_id
def __len__(self):
return len(self.file_names)
def __getitem__(self, idx):
fname = self.file_names[idx]
raw_image = PIL.Image.open(fname)
image = raw_image.convert("RGB")
if self.image_transform is not None:
image = self.image_transform(image)
label = extract_label(fname)
if self.label_to_id is not None:
label = self.label_to_id[label]
return {"image": image, "label": label}
def training_function(config, args):
# Initialize accelerator
accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision)
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
lr = config["lr"]
num_epochs = int(config["num_epochs"])
seed = int(config["seed"])
batch_size = int(config["batch_size"])
image_size = config["image_size"]
if not isinstance(image_size, (list, tuple)):
image_size = (image_size, image_size)
# Grab all the image filenames
file_names = [os.path.join(args.data_dir, fname) for fname in os.listdir(args.data_dir) if fname.endswith(".jpg")]
# Build the label correspondences
all_labels = [extract_label(fname) for fname in file_names]
id_to_label = list(set(all_labels))
id_to_label.sort()
label_to_id = {lbl: i for i, lbl in enumerate(id_to_label)}
# Set the seed before splitting the data.
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
# Split our filenames between train and validation
random_perm = np.random.permutation(len(file_names))
cut = int(0.8 * len(file_names))
train_split = random_perm[:cut]
eval_split = random_perm[cut:]
# For training we use a simple RandomResizedCrop
train_tfm = Compose([RandomResizedCrop(image_size, scale=(0.5, 1.0)), ToTensor()])
train_dataset = PetsDataset(
[file_names[i] for i in train_split], image_transform=train_tfm, label_to_id=label_to_id
)
# For evaluation, we use a deterministic Resize
eval_tfm = Compose([Resize(image_size), ToTensor()])
eval_dataset = PetsDataset([file_names[i] for i in eval_split], image_transform=eval_tfm, label_to_id=label_to_id)
# Instantiate dataloaders.
train_dataloader = DataLoader(train_dataset, shuffle=True, batch_size=batch_size, num_workers=4)
eval_dataloader = DataLoader(eval_dataset, shuffle=False, batch_size=batch_size, num_workers=4)
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
model = create_model("resnet50d", pretrained=True, num_classes=len(label_to_id))
# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
model = model.to(accelerator.device)
# Freezing the base model
for param in model.parameters():
param.requires_grad = False
for param in model.get_classifier().parameters():
param.requires_grad = True
# We normalize the batches of images to be a bit faster.
mean = torch.tensor(model.default_cfg["mean"])[None, :, None, None].to(accelerator.device)
std = torch.tensor(model.default_cfg["std"])[None, :, None, None].to(accelerator.device)
# Instantiate optimizer
optimizer = torch.optim.Adam(params=model.parameters(), lr=lr / 25)
# Instantiate learning rate scheduler
lr_scheduler = OneCycleLR(optimizer=optimizer, max_lr=lr, epochs=num_epochs, steps_per_epoch=len(train_dataloader))
# Prepare everything
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
# prepare method.
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
)
# Now we train the model
for epoch in range(num_epochs):
model.train()
for step, batch in enumerate(train_dataloader):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch = {k: v.to(accelerator.device) for k, v in batch.items()}
inputs = (batch["image"] - mean) / std
outputs = model(inputs)
loss = torch.nn.functional.cross_entropy(outputs, batch["label"])
accelerator.backward(loss)
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
model.eval()
accurate = 0
num_elems = 0
for _, batch in enumerate(eval_dataloader):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch = {k: v.to(accelerator.device) for k, v in batch.items()}
inputs = (batch["image"] - mean) / std
with torch.no_grad():
outputs = model(inputs)
predictions = outputs.argmax(dim=-1)
predictions, references = accelerator.gather_for_metrics((predictions, batch["label"]))
accurate_preds = predictions == references
num_elems += accurate_preds.shape[0]
accurate += accurate_preds.long().sum()
eval_metric = accurate.item() / num_elems
# Use accelerator.print to print only on the main process.
accelerator.print(f"epoch {epoch}: {100 * eval_metric:.2f}") | null |
2,986 | import argparse
import os
import re
import numpy as np
import PIL
import torch
from timm import create_model
from torch.optim.lr_scheduler import OneCycleLR
from torch.utils.data import DataLoader, Dataset
from torchvision.transforms import Compose, RandomResizedCrop, Resize, ToTensor
from accelerate import Accelerator
def extract_label(fname):
stem = fname.split(os.path.sep)[-1]
return re.search(r"^(.*)_\d+\.jpg$", stem).groups()[0]
class PetsDataset(Dataset):
def __init__(self, file_names, image_transform=None, label_to_id=None):
self.file_names = file_names
self.image_transform = image_transform
self.label_to_id = label_to_id
def __len__(self):
return len(self.file_names)
def __getitem__(self, idx):
fname = self.file_names[idx]
raw_image = PIL.Image.open(fname)
image = raw_image.convert("RGB")
if self.image_transform is not None:
image = self.image_transform(image)
label = extract_label(fname)
if self.label_to_id is not None:
label = self.label_to_id[label]
return {"image": image, "label": label}
def training_function(config, args):
# Initialize accelerator
if args.with_tracking:
accelerator = Accelerator(
cpu=args.cpu, mixed_precision=args.mixed_precision, log_with="all", project_dir=args.project_dir
)
else:
accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision)
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
lr = config["lr"]
num_epochs = int(config["num_epochs"])
seed = int(config["seed"])
batch_size = int(config["batch_size"])
image_size = config["image_size"]
if not isinstance(image_size, (list, tuple)):
image_size = (image_size, image_size)
# Parse out whether we are saving every epoch or after a certain number of batches
if hasattr(args.checkpointing_steps, "isdigit"):
if args.checkpointing_steps == "epoch":
checkpointing_steps = args.checkpointing_steps
elif args.checkpointing_steps.isdigit():
checkpointing_steps = int(args.checkpointing_steps)
else:
raise ValueError(
f"Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed."
)
else:
checkpointing_steps = None
# We need to initialize the trackers we use, and also store our configuration
if args.with_tracking:
run = os.path.split(__file__)[-1].split(".")[0]
accelerator.init_trackers(run, config)
# Grab all the image filenames
file_names = [os.path.join(args.data_dir, fname) for fname in os.listdir(args.data_dir) if fname.endswith(".jpg")]
# Build the label correspondences
all_labels = [extract_label(fname) for fname in file_names]
id_to_label = list(set(all_labels))
id_to_label.sort()
label_to_id = {lbl: i for i, lbl in enumerate(id_to_label)}
# Set the seed before splitting the data.
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
# Split our filenames between train and validation
random_perm = np.random.permutation(len(file_names))
cut = int(0.8 * len(file_names))
train_split = random_perm[:cut]
eval_split = random_perm[cut:]
# For training we use a simple RandomResizedCrop
train_tfm = Compose([RandomResizedCrop(image_size, scale=(0.5, 1.0)), ToTensor()])
train_dataset = PetsDataset(
[file_names[i] for i in train_split], image_transform=train_tfm, label_to_id=label_to_id
)
# For evaluation, we use a deterministic Resize
eval_tfm = Compose([Resize(image_size), ToTensor()])
eval_dataset = PetsDataset([file_names[i] for i in eval_split], image_transform=eval_tfm, label_to_id=label_to_id)
# Instantiate dataloaders.
train_dataloader = DataLoader(train_dataset, shuffle=True, batch_size=batch_size, num_workers=4)
eval_dataloader = DataLoader(eval_dataset, shuffle=False, batch_size=batch_size, num_workers=4)
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
model = create_model("resnet50d", pretrained=True, num_classes=len(label_to_id))
# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
model = model.to(accelerator.device)
# Freezing the base model
for param in model.parameters():
param.requires_grad = False
for param in model.get_classifier().parameters():
param.requires_grad = True
# We normalize the batches of images to be a bit faster.
mean = torch.tensor(model.default_cfg["mean"])[None, :, None, None].to(accelerator.device)
std = torch.tensor(model.default_cfg["std"])[None, :, None, None].to(accelerator.device)
# Instantiate optimizer
optimizer = torch.optim.Adam(params=model.parameters(), lr=lr / 25)
# Instantiate learning rate scheduler
lr_scheduler = OneCycleLR(optimizer=optimizer, max_lr=lr, epochs=num_epochs, steps_per_epoch=len(train_dataloader))
# Prepare everything
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
# prepare method.
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
)
# We need to keep track of how many total steps we have iterated over
overall_step = 0
# We also need to keep track of the starting epoch so files are named properly
starting_epoch = 0
# Potentially load in the weights and states from a previous save
if args.resume_from_checkpoint:
if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
accelerator.print(f"Resumed from checkpoint: {args.resume_from_checkpoint}")
accelerator.load_state(args.resume_from_checkpoint)
path = os.path.basename(args.resume_from_checkpoint)
else:
# Get the most recent checkpoint
dirs = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()]
dirs.sort(key=os.path.getctime)
path = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last
# Extract `epoch_{i}` or `step_{i}`
training_difference = os.path.splitext(path)[0]
if "epoch" in training_difference:
starting_epoch = int(training_difference.replace("epoch_", "")) + 1
resume_step = None
else:
resume_step = int(training_difference.replace("step_", ""))
starting_epoch = resume_step // len(train_dataloader)
resume_step -= starting_epoch * len(train_dataloader)
# Now we train the model
for epoch in range(starting_epoch, num_epochs):
model.train()
if args.with_tracking:
total_loss = 0
if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
# We need to skip steps until we reach the resumed step
active_dataloader = accelerator.skip_first_batches(train_dataloader, resume_step)
overall_step += resume_step
else:
# After the first iteration though, we need to go back to the original dataloader
active_dataloader = train_dataloader
for batch in active_dataloader:
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch = {k: v.to(accelerator.device) for k, v in batch.items()}
inputs = (batch["image"] - mean) / std
outputs = model(inputs)
loss = torch.nn.functional.cross_entropy(outputs, batch["label"])
# We keep track of the loss at each epoch
if args.with_tracking:
total_loss += loss.detach().float()
accelerator.backward(loss)
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
overall_step += 1
if isinstance(checkpointing_steps, int):
output_dir = f"step_{overall_step}"
if overall_step % checkpointing_steps == 0:
if args.output_dir is not None:
output_dir = os.path.join(args.output_dir, output_dir)
accelerator.save_state(output_dir)
model.eval()
accurate = 0
num_elems = 0
for step, batch in enumerate(eval_dataloader):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch = {k: v.to(accelerator.device) for k, v in batch.items()}
inputs = (batch["image"] - mean) / std
with torch.no_grad():
outputs = model(inputs)
predictions = outputs.argmax(dim=-1)
predictions, references = accelerator.gather_for_metrics((predictions, batch["label"]))
accurate_preds = predictions == references
num_elems += accurate_preds.shape[0]
accurate += accurate_preds.long().sum()
eval_metric = accurate.item() / num_elems
# Use accelerator.print to print only on the main process.
accelerator.print(f"epoch {epoch}: {100 * eval_metric:.2f}")
if args.with_tracking:
accelerator.log(
{
"accuracy": 100 * eval_metric,
"train_loss": total_loss.item() / len(train_dataloader),
"epoch": epoch,
},
step=overall_step,
)
if checkpointing_steps == "epoch":
output_dir = f"epoch_{epoch}"
if args.output_dir is not None:
output_dir = os.path.join(args.output_dir, output_dir)
accelerator.save_state(output_dir)
if args.with_tracking:
accelerator.end_training() | null |
2,987 | import argparse
import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
from accelerate import Accelerator, DistributedType
MAX_GPU_BATCH_SIZE = 16
def get_dataloaders(accelerator: Accelerator, batch_size: int = 16):
callback = EarlyStoppingCallback()
def training_function(config, args):
# Initialize accelerator
accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision)
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
lr = config["lr"]
num_epochs = int(config["num_epochs"])
seed = int(config["seed"])
batch_size = int(config["batch_size"])
metric = evaluate.load("glue", "mrpc")
# If the batch size is too big we use gradient accumulation
gradient_accumulation_steps = 1
if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.XLA:
gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE
batch_size = MAX_GPU_BATCH_SIZE
set_seed(seed)
train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
model = model.to(accelerator.device)
# Instantiate optimizer
optimizer = AdamW(params=model.parameters(), lr=lr)
# Instantiate scheduler
lr_scheduler = get_linear_schedule_with_warmup(
optimizer=optimizer,
num_warmup_steps=100,
num_training_steps=(len(train_dataloader) * num_epochs) // gradient_accumulation_steps,
)
# Prepare everything
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
# prepare method.
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
)
# Now we train the model
for epoch in range(num_epochs):
model.train()
for step, batch in enumerate(train_dataloader):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device)
outputs = model(**batch)
loss = outputs.loss
loss = loss / gradient_accumulation_steps
accelerator.backward(loss)
if step % gradient_accumulation_steps == 0:
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
# New code
# Check if we should stop the training on any processes
if callback.check_early_stopping(loss.item()):
accelerator.set_trigger()
# If so, we break the loop
if accelerator.check_trigger():
break
model.eval()
for step, batch in enumerate(eval_dataloader):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device)
with torch.no_grad():
outputs = model(**batch)
predictions = outputs.logits.argmax(dim=-1)
predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
metric.add_batch(
predictions=predictions,
references=references,
)
eval_metric = metric.compute()
# Use accelerator.print to print only on the main process.
accelerator.print(f"epoch {epoch}:", eval_metric) | null |
2,988 | import argparse
import os
import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
from accelerate import Accelerator, DistributedType
MAX_GPU_BATCH_SIZE = 16
def get_dataloaders(accelerator: Accelerator, batch_size: int = 16):
"""
Creates a set of `DataLoader`s for the `glue` dataset,
using "bert-base-cased" as the tokenizer.
Args:
accelerator (`Accelerator`):
An `Accelerator` object
batch_size (`int`, *optional*):
The batch size for the train and validation DataLoaders.
"""
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
datasets = load_dataset("glue", "mrpc")
def tokenize_function(examples):
# max_length=None => use the model max length (it's actually the default)
outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
return outputs
# Apply the method we just defined to all the examples in all the splits of the dataset
# starting with the main process first:
with accelerator.main_process_first():
tokenized_datasets = datasets.map(
tokenize_function,
batched=True,
remove_columns=["idx", "sentence1", "sentence2"],
)
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
# transformers library
tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
def collate_fn(examples):
# On TPU it's best to pad everything to the same length or training will be very slow.
max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None
# When using mixed precision we want round multiples of 8/16
if accelerator.mixed_precision == "fp8":
pad_to_multiple_of = 16
elif accelerator.mixed_precision != "no":
pad_to_multiple_of = 8
else:
pad_to_multiple_of = None
return tokenizer.pad(
examples,
padding="longest",
max_length=max_length,
pad_to_multiple_of=pad_to_multiple_of,
return_tensors="pt",
)
# Instantiate dataloaders.
train_dataloader = DataLoader(
tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
)
eval_dataloader = DataLoader(
tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
)
return train_dataloader, eval_dataloader
if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
from accelerate.test_utils.training import mocked_dataloaders
get_dataloaders = mocked_dataloaders # noqa: F811
def training_function(config, args):
# For testing only
if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
config["num_epochs"] = 2
# Initialize accelerator
accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision)
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
lr = config["lr"]
num_epochs = int(config["num_epochs"])
seed = int(config["seed"])
batch_size = int(config["batch_size"])
# New Code #
# Parse out whether we are saving every epoch or after a certain number of batches
if hasattr(args.checkpointing_steps, "isdigit"):
if args.checkpointing_steps == "epoch":
checkpointing_steps = args.checkpointing_steps
elif args.checkpointing_steps.isdigit():
checkpointing_steps = int(args.checkpointing_steps)
else:
raise ValueError(
f"Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed."
)
else:
checkpointing_steps = None
set_seed(seed)
train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)
metric = evaluate.load("glue", "mrpc")
# If the batch size is too big we use gradient accumulation
gradient_accumulation_steps = 1
if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.XLA:
gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE
batch_size = MAX_GPU_BATCH_SIZE
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
model = model.to(accelerator.device)
# Instantiate optimizer
optimizer = AdamW(params=model.parameters(), lr=lr)
# Instantiate scheduler
lr_scheduler = get_linear_schedule_with_warmup(
optimizer=optimizer,
num_warmup_steps=100,
num_training_steps=(len(train_dataloader) * num_epochs) // gradient_accumulation_steps,
)
# Prepare everything
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
# prepare method.
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
)
# New Code #
# We need to keep track of how many total steps we have iterated over
overall_step = 0
# We also need to keep track of the stating epoch so files are named properly
starting_epoch = 0
# We need to load the checkpoint back in before training here with `load_state`
# The total number of epochs is adjusted based on where the state is being loaded from,
# as we assume continuation of the same training script
if args.resume_from_checkpoint:
if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
accelerator.print(f"Resumed from checkpoint: {args.resume_from_checkpoint}")
accelerator.load_state(args.resume_from_checkpoint)
path = os.path.basename(args.resume_from_checkpoint)
else:
# Get the most recent checkpoint
dirs = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()]
dirs.sort(key=os.path.getctime)
path = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last
# Extract `epoch_{i}` or `step_{i}`
training_difference = os.path.splitext(path)[0]
if "epoch" in training_difference:
starting_epoch = int(training_difference.replace("epoch_", "")) + 1
resume_step = None
else:
resume_step = int(training_difference.replace("step_", ""))
starting_epoch = resume_step // len(train_dataloader)
resume_step -= starting_epoch * len(train_dataloader)
# Now we train the model
for epoch in range(starting_epoch, num_epochs):
model.train()
# New Code #
if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
# We need to skip steps until we reach the resumed step
active_dataloader = accelerator.skip_first_batches(train_dataloader, resume_step)
overall_step += resume_step
else:
# After the first iteration though, we need to go back to the original dataloader
active_dataloader = train_dataloader
for step, batch in enumerate(active_dataloader):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device)
outputs = model(**batch)
loss = outputs.loss
loss = loss / gradient_accumulation_steps
accelerator.backward(loss)
if step % gradient_accumulation_steps == 0:
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
# New Code #
overall_step += 1
# New Code #
# We save the model, optimizer, lr_scheduler, and seed states by calling `save_state`
# These are saved to folders named `step_{overall_step}`
# Will contain files: "pytorch_model.bin", "optimizer.bin", "scheduler.bin", and "random_states.pkl"
# If mixed precision was used, will also save a "scalar.bin" file
if isinstance(checkpointing_steps, int):
output_dir = f"step_{overall_step}"
if overall_step % checkpointing_steps == 0:
if args.output_dir is not None:
output_dir = os.path.join(args.output_dir, output_dir)
accelerator.save_state(output_dir)
model.eval()
for step, batch in enumerate(eval_dataloader):
# We could avoid this line since we set the accelerator with `device_placement=True` (the default).
batch.to(accelerator.device)
with torch.no_grad():
outputs = model(**batch)
predictions = outputs.logits.argmax(dim=-1)
predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
metric.add_batch(
predictions=predictions,
references=references,
)
eval_metric = metric.compute()
# Use accelerator.print to print only on the main process.
accelerator.print(f"epoch {epoch}:", eval_metric)
# New Code #
# We save the model, optimizer, lr_scheduler, and seed states by calling `save_state`
# These are saved to folders named `epoch_{epoch}`
# Will contain files: "pytorch_model.bin", "optimizer.bin", "scheduler.bin", and "random_states.pkl"
# If mixed precision was used, will also save a "scalar.bin" file
if checkpointing_steps == "epoch":
output_dir = f"epoch_{epoch}"
if args.output_dir is not None:
output_dir = os.path.join(args.output_dir, output_dir)
accelerator.save_state(output_dir) | null |
2,989 | import argparse
import gc
import os
import threading
import evaluate
import psutil
import torch
from datasets import load_dataset
from torch.distributed.fsdp.fully_sharded_data_parallel import FullOptimStateDictConfig, FullStateDictConfig
from torch.utils.data import DataLoader
from transformers import (
AutoModelForSequenceClassification,
AutoTokenizer,
get_linear_schedule_with_warmup,
set_seed,
)
from accelerate import Accelerator, DistributedType, FullyShardedDataParallelPlugin
from accelerate.utils import is_npu_available, is_xpu_available
MAX_GPU_BATCH_SIZE = 16
EVAL_BATCH_SIZE = 32
def b2mb(x):
return int(x / 2**20)
class TorchTracemalloc:
def __enter__(self):
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero
self.begin = torch.cuda.memory_allocated()
elif is_xpu_available():
torch.xpu.empty_cache()
torch.xpu.reset_max_memory_allocated() # reset the peak gauge to zero
self.begin = torch.xpu.memory_allocated()
elif is_npu_available():
torch.npu.empty_cache()
torch.npu.reset_max_memory_allocated() # reset the peak gauge to zero
self.begin = torch.npu.memory_allocated()
self.process = psutil.Process()
self.cpu_begin = self.cpu_mem_used()
self.peak_monitoring = True
peak_monitor_thread = threading.Thread(target=self.peak_monitor_func)
peak_monitor_thread.daemon = True
peak_monitor_thread.start()
return self
def cpu_mem_used(self):
"""get resident set size memory for the current process"""
return self.process.memory_info().rss
def peak_monitor_func(self):
self.cpu_peak = -1
while True:
self.cpu_peak = max(self.cpu_mem_used(), self.cpu_peak)
# can't sleep or will not catch the peak right (this comment is here on purpose)
# time.sleep(0.001) # 1msec
if not self.peak_monitoring:
break
def __exit__(self, *exc):
self.peak_monitoring = False
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
self.end = torch.cuda.memory_allocated()
self.peak = torch.cuda.max_memory_allocated()
elif is_xpu_available():
torch.xpu.empty_cache()
self.end = torch.xpu.memory_allocated()
self.peak = torch.xpu.max_memory_allocated()
elif is_npu_available():
torch.npu.empty_cache()
self.end = torch.npu.memory_allocated()
self.peak = torch.npu.max_memory_allocated()
self.used = b2mb(self.end - self.begin)
self.peaked = b2mb(self.peak - self.begin)
self.cpu_end = self.cpu_mem_used()
self.cpu_used = b2mb(self.cpu_end - self.cpu_begin)
self.cpu_peaked = b2mb(self.cpu_peak - self.cpu_begin)
# print(f"delta used/peak {self.used:4d}/{self.peaked:4d}")
if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
from accelerate.test_utils.training import mocked_dataloaders
get_dataloaders = mocked_dataloaders # noqa: F811
def training_function(config, args):
# For testing only
if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
config["num_epochs"] = 2
# New Code #
# Pass the advanced FSDP settings not part of the accelerate config by creating fsdp_plugin
fsdp_plugin = FullyShardedDataParallelPlugin(
state_dict_config=FullStateDictConfig(offload_to_cpu=False, rank0_only=False),
optim_state_dict_config=FullOptimStateDictConfig(offload_to_cpu=False, rank0_only=False),
)
# Initialize accelerator
if args.with_tracking:
accelerator = Accelerator(
cpu=args.cpu,
mixed_precision=args.mixed_precision,
log_with="wandb",
project_dir=args.logging_dir,
fsdp_plugin=fsdp_plugin,
)
else:
accelerator = Accelerator(fsdp_plugin=fsdp_plugin)
accelerator.print(accelerator.distributed_type)
if hasattr(args.checkpointing_steps, "isdigit"):
if args.checkpointing_steps == "epoch":
checkpointing_steps = args.checkpointing_steps
elif args.checkpointing_steps.isdigit():
checkpointing_steps = int(args.checkpointing_steps)
else:
raise ValueError(
f"Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed."
)
else:
checkpointing_steps = None
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
lr = config["lr"]
num_epochs = int(config["num_epochs"])
seed = int(config["seed"])
batch_size = int(config["batch_size"])
# We need to initialize the trackers we use, and also store our configuration
if args.with_tracking:
experiment_config = vars(args)
accelerator.init_trackers("fsdp_glue_no_trainer", experiment_config)
tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path)
datasets = load_dataset("glue", "mrpc")
metric = evaluate.load("glue", "mrpc")
def tokenize_function(examples):
# max_length=None => use the model max length (it's actually the default)
outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
return outputs
# Apply the method we just defined to all the examples in all the splits of the dataset
# starting with the main process first:
with accelerator.main_process_first():
tokenized_datasets = datasets.map(
tokenize_function,
batched=True,
remove_columns=["idx", "sentence1", "sentence2"],
)
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
# transformers library
tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
# If the batch size is too big we use gradient accumulation
gradient_accumulation_steps = 1
if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.XLA:
gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE
batch_size = MAX_GPU_BATCH_SIZE
def collate_fn(examples):
# On TPU it's best to pad everything to the same length or training will be very slow.
max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None
# When using mixed precision we want round multiples of 8/16
if accelerator.mixed_precision == "fp8":
pad_to_multiple_of = 16
elif accelerator.mixed_precision != "no":
pad_to_multiple_of = 8
else:
pad_to_multiple_of = None
return tokenizer.pad(
examples,
padding="longest",
max_length=max_length,
pad_to_multiple_of=pad_to_multiple_of,
return_tensors="pt",
)
# Instantiate dataloaders.
train_dataloader = DataLoader(
tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
)
eval_dataloader = DataLoader(
tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
)
set_seed(seed)
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
model = AutoModelForSequenceClassification.from_pretrained(
args.model_name_or_path, return_dict=True, low_cpu_mem_usage=True
)
no_decay = ["bias", "LayerNorm.weight"]
optimizer_grouped_parameters = [
{
"params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)],
"weight_decay": 0.003,
},
{
"params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)],
"weight_decay": 0.0,
},
]
optimizer = torch.optim.AdamW(params=optimizer_grouped_parameters, lr=lr, weight_decay=2e-4)
# Instantiate scheduler
lr_scheduler = get_linear_schedule_with_warmup(
optimizer=optimizer,
num_warmup_steps=10,
num_training_steps=(len(train_dataloader) * num_epochs) // gradient_accumulation_steps,
)
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
)
overall_step = 0
# Potentially load in the weights and states from a previous save
if args.resume_from_checkpoint:
if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
accelerator.print(f"Resumed from checkpoint: {args.resume_from_checkpoint}")
accelerator.load_state(args.resume_from_checkpoint)
path = os.path.basename(args.resume_from_checkpoint)
else:
# Get the most recent checkpoint
dirs = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()]
dirs.sort(key=os.path.getctime)
path = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last
# Extract `epoch_{i}` or `step_{i}`
training_difference = os.path.splitext(path)[0]
if "epoch" in training_difference:
num_epochs -= int(training_difference.replace("epoch_", ""))
resume_step = None
else:
resume_step = int(training_difference.replace("step_", ""))
num_epochs -= resume_step // len(train_dataloader)
# If resuming by step, we also need to know exactly how far into the DataLoader we went
resume_step = (num_epochs * len(train_dataloader)) - resume_step
# Now we train the model
for epoch in range(num_epochs):
# New Code #
# context manager to track the peak memory usage during the training epoch
with TorchTracemalloc() as tracemalloc:
model.train()
if args.with_tracking:
total_loss = 0
for step, batch in enumerate(train_dataloader):
# We need to skip steps until we reach the resumed step
if args.resume_from_checkpoint and epoch == 0:
if resume_step is not None and step < resume_step:
pass
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device)
outputs = model(**batch)
loss = outputs.loss
# We keep track of the loss at each epoch
if args.with_tracking:
total_loss += loss.detach().float()
accelerator.backward(loss)
if step % gradient_accumulation_steps == 0:
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
# accelerator.print(lr_scheduler.get_lr())
overall_step += 1
if isinstance(checkpointing_steps, int):
output_dir = f"step_{overall_step}"
if overall_step % checkpointing_steps == 0:
if args.output_dir is not None:
output_dir = os.path.join(args.output_dir, output_dir)
accelerator.save_state(output_dir)
# New Code #
# Printing the GPU memory usage details such as allocated memory, peak memory, and total memory usage
accelerator.print(f"Memory before entering the train : {b2mb(tracemalloc.begin)}")
accelerator.print(f"Memory consumed at the end of the train (end-begin): {tracemalloc.used}")
accelerator.print(f"Peak Memory consumed during the train (max-begin): {tracemalloc.peaked}")
accelerator.print(
f"Total Peak Memory consumed during the train (max): {tracemalloc.peaked + b2mb(tracemalloc.begin)}"
)
# Logging the peak memory usage of the GPU to the tracker
if args.with_tracking:
accelerator.log(
{
"train_total_peak_memory": tracemalloc.peaked + b2mb(tracemalloc.begin),
},
step=epoch,
)
# New Code #
# context manager to track the peak memory usage during the evaluation
with TorchTracemalloc() as tracemalloc:
model.eval()
for step, batch in enumerate(eval_dataloader):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device)
with torch.no_grad():
outputs = model(**batch)
predictions = outputs.logits.argmax(dim=-1)
predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
metric.add_batch(
predictions=predictions,
references=references,
)
eval_metric = metric.compute()
# Use accelerator.print to print only on the main process.
accelerator.print(f"epoch {epoch}:", eval_metric)
if args.with_tracking:
accelerator.log(
{
"accuracy": eval_metric["accuracy"],
"f1": eval_metric["f1"],
"train_loss": total_loss.item() / len(train_dataloader),
},
step=epoch,
)
if checkpointing_steps == "epoch":
output_dir = f"epoch_{epoch}"
if args.output_dir is not None:
output_dir = os.path.join(args.output_dir, output_dir)
accelerator.save_state(output_dir)
# New Code #
# Printing the GPU memory usage details such as allocated memory, peak memory, and total memory usage
accelerator.print(f"Memory before entering the eval : {b2mb(tracemalloc.begin)}")
accelerator.print(f"Memory consumed at the end of the eval (end-begin): {tracemalloc.used}")
accelerator.print(f"Peak Memory consumed during the eval (max-begin): {tracemalloc.peaked}")
accelerator.print(
f"Total Peak Memory consumed during the eval (max): {tracemalloc.peaked + b2mb(tracemalloc.begin)}"
)
# Logging the peak memory usage of the GPU to the tracker
if args.with_tracking:
accelerator.log(
{
"eval_total_peak_memory": tracemalloc.peaked + b2mb(tracemalloc.begin),
},
step=epoch,
)
if args.with_tracking:
accelerator.end_training() | null |
2,990 | import argparse
import os
import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
from accelerate import Accelerator, DistributedType
def get_dataloaders(accelerator: Accelerator, batch_size: int = 16):
if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
from accelerate.test_utils.training import mocked_dataloaders
get_dataloaders = mocked_dataloaders # noqa: F811
def training_function(config, args):
# For testing only
if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
config["num_epochs"] = 2
# New Code #
gradient_accumulation_steps = int(args.gradient_accumulation_steps)
# Initialize accelerator
accelerator = Accelerator(
cpu=args.cpu, mixed_precision=args.mixed_precision, gradient_accumulation_steps=gradient_accumulation_steps
)
if accelerator.distributed_type == DistributedType.XLA and gradient_accumulation_steps > 1:
raise NotImplementedError(
"Gradient accumulation on TPUs is currently not supported. Pass `gradient_accumulation_steps=1`"
)
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
lr = config["lr"]
num_epochs = int(config["num_epochs"])
seed = int(config["seed"])
batch_size = int(config["batch_size"])
metric = evaluate.load("glue", "mrpc")
set_seed(seed)
train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
model = model.to(accelerator.device)
# Instantiate optimizer
optimizer = AdamW(params=model.parameters(), lr=lr)
# Instantiate scheduler
lr_scheduler = get_linear_schedule_with_warmup(
optimizer=optimizer,
num_warmup_steps=100,
num_training_steps=(len(train_dataloader) * num_epochs),
)
# Prepare everything
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
# prepare method.
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
)
# Now we train the model
for epoch in range(num_epochs):
model.train()
for step, batch in enumerate(train_dataloader):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device)
# New code #
# We use the new `accumulate` context manager to perform gradient accumulation
# We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests.
with accelerator.accumulate(model):
output = model(**batch)
loss = output.loss
accelerator.backward(loss)
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
model.eval()
for step, batch in enumerate(eval_dataloader):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device)
with torch.no_grad():
outputs = model(**batch)
predictions = outputs.logits.argmax(dim=-1)
predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
metric.add_batch(
predictions=predictions,
references=references,
)
eval_metric = metric.compute()
# Use accelerator.print to print only on the main process.
accelerator.print(f"epoch {epoch}:", eval_metric) | null |
2,991 | import argparse
import json
import logging
import math
import os
import random
from itertools import chain
from pathlib import Path
import datasets
import torch
import transformers
from datasets import load_dataset
from huggingface_hub import Repository
from torch.utils.data import DataLoader
from tqdm.auto import tqdm
from transformers import (
CONFIG_MAPPING,
MODEL_MAPPING,
AutoConfig,
AutoModelForCausalLM,
AutoTokenizer,
SchedulerType,
default_data_collator,
get_scheduler,
)
from transformers.utils import check_min_version, get_full_repo_name, send_example_telemetry
from transformers.utils.versions import require_version
from accelerate import Accelerator, DistributedType
from accelerate.logging import get_logger
from accelerate.utils import MegatronLMDummyScheduler, set_seed
MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
def parse_args():
parser = argparse.ArgumentParser(description="Finetune a transformers model on a causal language modeling task")
parser.add_argument(
"--dataset_name",
type=str,
default=None,
help="The name of the dataset to use (via the datasets library).",
)
parser.add_argument(
"--dataset_config_name",
type=str,
default=None,
help="The configuration name of the dataset to use (via the datasets library).",
)
parser.add_argument(
"--train_file", type=str, default=None, help="A csv or a json file containing the training data."
)
parser.add_argument(
"--validation_file", type=str, default=None, help="A csv or a json file containing the validation data."
)
parser.add_argument(
"--validation_split_percentage",
default=5,
help="The percentage of the train set used as validation set in case there's no validation split",
)
parser.add_argument(
"--model_name_or_path",
type=str,
help="Path to pretrained model or model identifier from huggingface.co/models.",
required=False,
)
parser.add_argument(
"--config_name",
type=str,
default=None,
help="Pretrained config name or path if not the same as model_name",
)
parser.add_argument(
"--tokenizer_name",
type=str,
default=None,
help="Pretrained tokenizer name or path if not the same as model_name",
)
parser.add_argument(
"--use_slow_tokenizer",
action="store_true",
help="If passed, will use a slow tokenizer (not backed by the 🤗 Tokenizers library).",
)
parser.add_argument(
"--per_device_train_batch_size",
type=int,
default=8,
help="Batch size (per device) for the training dataloader.",
)
parser.add_argument(
"--per_device_eval_batch_size",
type=int,
default=8,
help="Batch size (per device) for the evaluation dataloader.",
)
parser.add_argument(
"--learning_rate",
type=float,
default=5e-5,
help="Initial learning rate (after the potential warmup period) to use.",
)
parser.add_argument("--weight_decay", type=float, default=0.0, help="Weight decay to use.")
parser.add_argument("--num_train_epochs", type=int, default=3, help="Total number of training epochs to perform.")
parser.add_argument(
"--max_train_steps",
type=int,
default=None,
help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
)
parser.add_argument(
"--gradient_accumulation_steps",
type=int,
default=1,
help="Number of updates steps to accumulate before performing a backward/update pass.",
)
parser.add_argument(
"--lr_scheduler_type",
type=SchedulerType,
default="linear",
help="The scheduler type to use.",
choices=["linear", "cosine", "cosine_with_restarts", "polynomial", "constant", "constant_with_warmup"],
)
parser.add_argument(
"--num_warmup_steps", type=int, default=0, help="Number of steps for the warmup in the lr scheduler."
)
parser.add_argument("--output_dir", type=str, default=None, help="Where to store the final model.")
parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
parser.add_argument(
"--model_type",
type=str,
default=None,
help="Model type to use if training from scratch.",
choices=MODEL_TYPES,
)
parser.add_argument(
"--block_size",
type=int,
default=None,
help=(
"Optional input sequence length after tokenization. The training dataset will be truncated in block of"
" this size for training. Default to the model max input length for single sentence inputs (take into"
" account special tokens)."
),
)
parser.add_argument(
"--preprocessing_num_workers",
type=int,
default=None,
help="The number of processes to use for the preprocessing.",
)
parser.add_argument(
"--overwrite_cache", action="store_true", help="Overwrite the cached training and evaluation sets"
)
parser.add_argument(
"--no_keep_linebreaks", action="store_true", help="Do not keep line breaks when using TXT files."
)
parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
parser.add_argument(
"--hub_model_id", type=str, help="The name of the repository to keep in sync with the local `output_dir`."
)
parser.add_argument("--hub_token", type=str, help="The token to use to push to the Model Hub.")
parser.add_argument(
"--checkpointing_steps",
type=str,
default=None,
help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.",
)
parser.add_argument(
"--resume_from_checkpoint",
type=str,
default=None,
help="If the training should continue from a checkpoint folder.",
)
parser.add_argument(
"--with_tracking",
action="store_true",
help="Whether to enable experiment trackers for logging.",
)
parser.add_argument(
"--report_to",
type=str,
default="all",
help=(
'The integration to report the results and logs to. Supported platforms are `"tensorboard"`,'
' `"wandb"`, `"comet_ml"`, and `"dvclive"`. Use `"all"` (default) to report to all integrations.'
"Only applicable when `--with_tracking` is passed."
),
)
args = parser.parse_args()
# Sanity checks
if args.dataset_name is None and args.train_file is None and args.validation_file is None:
raise ValueError("Need either a dataset name or a training/validation file.")
else:
if args.train_file is not None:
extension = args.train_file.split(".")[-1]
assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, json or txt file."
if args.validation_file is not None:
extension = args.validation_file.split(".")[-1]
assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, json or txt file."
if args.push_to_hub:
assert args.output_dir is not None, "Need an `output_dir` to create a repo when `--push_to_hub` is passed."
return args | null |
2,992 | import argparse
import os
import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
from accelerate import Accelerator, DistributedType
from accelerate.local_sgd import LocalSGD
def get_dataloaders(accelerator: Accelerator, batch_size: int = 16):
"""
Creates a set of `DataLoader`s for the `glue` dataset,
using "bert-base-cased" as the tokenizer.
Args:
accelerator (`Accelerator`):
An `Accelerator` object
batch_size (`int`, *optional*):
The batch size for the train and validation DataLoaders.
"""
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
datasets = load_dataset("glue", "mrpc")
def tokenize_function(examples):
# max_length=None => use the model max length (it's actually the default)
outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
return outputs
# Apply the method we just defined to all the examples in all the splits of the dataset
# starting with the main process first:
with accelerator.main_process_first():
tokenized_datasets = datasets.map(
tokenize_function,
batched=True,
remove_columns=["idx", "sentence1", "sentence2"],
)
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
# transformers library
tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
def collate_fn(examples):
# On TPU it's best to pad everything to the same length or training will be very slow.
max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None
# When using mixed precision we want round multiples of 8/16
if accelerator.mixed_precision == "fp8":
pad_to_multiple_of = 16
elif accelerator.mixed_precision != "no":
pad_to_multiple_of = 8
else:
pad_to_multiple_of = None
return tokenizer.pad(
examples,
padding="longest",
max_length=max_length,
pad_to_multiple_of=pad_to_multiple_of,
return_tensors="pt",
)
# Instantiate dataloaders.
train_dataloader = DataLoader(
tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
)
eval_dataloader = DataLoader(
tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
)
return train_dataloader, eval_dataloader
if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
from accelerate.test_utils.training import mocked_dataloaders
get_dataloaders = mocked_dataloaders # noqa: F811
class LocalSGD:
"""
A helper class to support local SGD on top of Accelerator. It simply runs a given number of updates independently
on each device, and averages model weights every K synchronization step.
It should be used only in the multi-GPU (or multi-CPU) setup without extensions such as DeepSpeed. In particular,
this is a simple implementation that cannot support scenarios such as model parallelism.
Although we are not aware of the true origins of this simple approach, the idea of local SGD is quite old and goes
back to at least:
Zhang, J., De Sa, C., Mitliagkas, I., & Ré, C. (2016). [Parallel SGD: When does averaging help?. arXiv preprint
arXiv:1606.07365.](https://arxiv.org/abs/1606.07365)
We credit the term Local SGD to the following paper (but there might be earlier references we are not aware of).
Stich, Sebastian Urban. ["Local SGD Converges Fast and Communicates Little." ICLR 2019-International Conference on
Learning Representations. No. CONF. 2019.](https://arxiv.org/abs/1805.09767)
"""
def __enter__(self):
if self.enabled:
self.model_sync_obj = self.model.no_sync()
self.model_sync_obj.__enter__()
return self
def __exit__(self, type, value, tb):
if self.enabled:
# Average all models on exit
self._sync_and_avg_model_params()
self.model_sync_obj.__exit__(type, value, tb)
def __init__(self, accelerator: Accelerator, model: torch.nn.Module, local_sgd_steps: int, enabled: bool = True):
"""
Constructor.
Args:
model (`torch.nn.Module):
The model whose parameters we need to average.
accelerator (`Accelerator`):
Accelerator object.
local_sgd_steps (`int`):
A number of local SGD steps (before model parameters are synchronized).
enabled (`bool):
Local SGD is disabled if this parameter set to `False`.
"""
if accelerator.distributed_type not in [
DistributedType.NO,
DistributedType.MULTI_CPU,
DistributedType.MULTI_GPU,
DistributedType.MULTI_NPU,
]:
raise NotImplementedError("LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)")
self.enabled = enabled and accelerator.distributed_type != DistributedType.NO
self.num_steps = 0
if self.enabled:
self.accelerator = accelerator
self.model = model
self.local_sgd_steps = local_sgd_steps
def step(self):
"""
This function makes a "step" and synchronizes model parameters if necessary.
"""
self.num_steps += 1
if not self.enabled:
return
if self.num_steps % self.local_sgd_steps == 0:
self._sync_and_avg_model_params()
def _sync_and_avg_model_params(self):
"""
Synchronize + Average model parameters across all GPUs
"""
self.accelerator.wait_for_everyone()
with self.accelerator.autocast():
for param in self.model.parameters():
param.data = self.accelerator.reduce(param.data, reduction="mean")
def training_function(config, args):
# For testing only
if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
config["num_epochs"] = 2
# New Code #
gradient_accumulation_steps = int(args.gradient_accumulation_steps)
local_sgd_steps = int(args.local_sgd_steps)
# Initialize accelerator
accelerator = Accelerator(
cpu=args.cpu, mixed_precision=args.mixed_precision, gradient_accumulation_steps=gradient_accumulation_steps
)
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
lr = config["lr"]
num_epochs = int(config["num_epochs"])
seed = int(config["seed"])
batch_size = int(config["batch_size"])
metric = evaluate.load("glue", "mrpc")
set_seed(seed)
train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
model = model.to(accelerator.device)
# Instantiate optimizer
optimizer = AdamW(params=model.parameters(), lr=lr)
# Instantiate scheduler
lr_scheduler = get_linear_schedule_with_warmup(
optimizer=optimizer,
num_warmup_steps=100,
num_training_steps=(len(train_dataloader) * num_epochs),
)
# Prepare everything
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
# prepare method.
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
)
# Now we train the model
for epoch in range(num_epochs):
model.train()
with LocalSGD(
accelerator=accelerator, model=model, local_sgd_steps=local_sgd_steps, enabled=local_sgd_steps is not None
) as local_sgd:
for step, batch in enumerate(train_dataloader):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device)
# New code #
# We use the new `accumulate` context manager to perform gradient accumulation
# We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests.
with accelerator.accumulate(model):
output = model(**batch)
loss = output.loss
accelerator.backward(loss)
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
# LocalSGD-specific line
local_sgd.step()
model.eval()
for step, batch in enumerate(eval_dataloader):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device)
with torch.no_grad():
outputs = model(**batch)
predictions = outputs.logits.argmax(dim=-1)
predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
metric.add_batch(
predictions=predictions,
references=references,
)
eval_metric = metric.compute()
# Use accelerator.print to print only on the main process.
accelerator.print(f"epoch {epoch}:", eval_metric) | null |
2,993 | import argparse
import os
import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
from accelerate import Accelerator, DistributedType
MAX_GPU_BATCH_SIZE = 16
def get_dataloaders(accelerator: Accelerator, batch_size: int = 16):
"""
Creates a set of `DataLoader`s for the `glue` dataset,
using "bert-base-cased" as the tokenizer.
Args:
accelerator (`Accelerator`):
An `Accelerator` object
batch_size (`int`, *optional*):
The batch size for the train and validation DataLoaders.
"""
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
datasets = load_dataset("glue", "mrpc")
def tokenize_function(examples):
# max_length=None => use the model max length (it's actually the default)
outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
return outputs
# Apply the method we just defined to all the examples in all the splits of the dataset
# starting with the main process first:
with accelerator.main_process_first():
tokenized_datasets = datasets.map(
tokenize_function,
batched=True,
remove_columns=["idx", "sentence1", "sentence2"],
)
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
# transformers library
tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
def collate_fn(examples):
# On TPU it's best to pad everything to the same length or training will be very slow.
max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None
# When using mixed precision we want round multiples of 8/16
if accelerator.mixed_precision == "fp8":
pad_to_multiple_of = 16
elif accelerator.mixed_precision != "no":
pad_to_multiple_of = 8
else:
pad_to_multiple_of = None
return tokenizer.pad(
examples,
padding="longest",
max_length=max_length,
pad_to_multiple_of=pad_to_multiple_of,
return_tensors="pt",
)
# Instantiate dataloaders.
train_dataloader = DataLoader(
tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
)
eval_dataloader = DataLoader(
tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
)
return train_dataloader, eval_dataloader
if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
from accelerate.test_utils.training import mocked_dataloaders
get_dataloaders = mocked_dataloaders # noqa: F811
def training_function(config, args):
# For testing only
if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
config["num_epochs"] = 2
# Initialize accelerator
accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision)
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
lr = config["lr"]
num_epochs = int(config["num_epochs"])
seed = int(config["seed"])
batch_size = int(config["batch_size"])
metric = evaluate.load("glue", "mrpc")
# If the batch size is too big we use gradient accumulation
gradient_accumulation_steps = 1
if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.XLA:
gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE
batch_size = MAX_GPU_BATCH_SIZE
set_seed(seed)
train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
model = model.to(accelerator.device)
# Instantiate optimizer
optimizer = AdamW(params=model.parameters(), lr=lr)
# Instantiate scheduler
lr_scheduler = get_linear_schedule_with_warmup(
optimizer=optimizer,
num_warmup_steps=100,
num_training_steps=(len(train_dataloader) * num_epochs) // gradient_accumulation_steps,
)
# Prepare everything
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
# prepare method.
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
)
# Now we train the model
for epoch in range(num_epochs):
model.train()
for step, batch in enumerate(train_dataloader):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device)
outputs = model(**batch)
loss = outputs.loss
loss = loss / gradient_accumulation_steps
accelerator.backward(loss)
if step % gradient_accumulation_steps == 0:
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
model.eval()
samples_seen = 0
for step, batch in enumerate(eval_dataloader):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device)
with torch.no_grad():
outputs = model(**batch)
predictions = outputs.logits.argmax(dim=-1)
predictions, references = accelerator.gather((predictions, batch["labels"]))
# New Code #
# First we check if it's a distributed system
if accelerator.use_distributed:
# Then see if we're on the last batch of our eval dataloader
if step == len(eval_dataloader) - 1:
# Last batch needs to be truncated on distributed systems as it contains additional samples
predictions = predictions[: len(eval_dataloader.dataset) - samples_seen]
references = references[: len(eval_dataloader.dataset) - samples_seen]
else:
# Otherwise we add the number of samples seen
samples_seen += references.shape[0]
# All of this can be avoided if you use `Accelerator.gather_for_metrics` instead of `Accelerator.gather`:
# accelerator.gather_for_metrics((predictions, batch["labels"]))
metric.add_batch(
predictions=predictions,
references=references,
)
eval_metric = metric.compute()
# Use accelerator.print to print only on the main process.
accelerator.print(f"epoch {epoch}:", eval_metric) | null |
2,994 | import argparse
import os
import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
from accelerate import Accelerator, DistributedType
from accelerate.utils import find_executable_batch_size
def get_dataloaders(accelerator: Accelerator, batch_size: int = 16):
"""
Creates a set of `DataLoader`s for the `glue` dataset,
using "bert-base-cased" as the tokenizer.
Args:
accelerator (`Accelerator`):
An `Accelerator` object
batch_size (`int`, *optional*):
The batch size for the train and validation DataLoaders.
"""
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
datasets = load_dataset("glue", "mrpc")
def tokenize_function(examples):
# max_length=None => use the model max length (it's actually the default)
outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
return outputs
# Apply the method we just defined to all the examples in all the splits of the dataset
# starting with the main process first:
with accelerator.main_process_first():
tokenized_datasets = datasets.map(
tokenize_function,
batched=True,
remove_columns=["idx", "sentence1", "sentence2"],
)
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
# transformers library
tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
def collate_fn(examples):
# On TPU it's best to pad everything to the same length or training will be very slow.
max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None
# When using mixed precision we want round multiples of 8/16
if accelerator.mixed_precision == "fp8":
pad_to_multiple_of = 16
elif accelerator.mixed_precision != "no":
pad_to_multiple_of = 8
else:
pad_to_multiple_of = None
return tokenizer.pad(
examples,
padding="longest",
max_length=max_length,
pad_to_multiple_of=pad_to_multiple_of,
return_tensors="pt",
)
# Instantiate dataloaders.
train_dataloader = DataLoader(
tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
)
eval_dataloader = DataLoader(
tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
)
return train_dataloader, eval_dataloader
if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
from accelerate.test_utils.training import mocked_dataloaders
get_dataloaders = mocked_dataloaders # noqa: F811
def training_function(config, args):
# For testing only
if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
config["num_epochs"] = 2
# Initialize accelerator
accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision)
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
lr = config["lr"]
num_epochs = int(config["num_epochs"])
seed = int(config["seed"])
batch_size = int(config["batch_size"])
metric = evaluate.load("glue", "mrpc")
# New Code #
# We now can define an inner training loop function. It should take a batch size as the only parameter,
# and build the dataloaders in there.
# It also gets our decorator
@find_executable_batch_size(starting_batch_size=batch_size)
def inner_training_loop(batch_size):
# And now just move everything below under this function
# We need to bring in the Accelerator object from earlier
nonlocal accelerator
# And reset all of its attributes that could hold onto any memory:
accelerator.free_memory()
# Then we can declare the model, optimizer, and everything else:
set_seed(seed)
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
model = model.to(accelerator.device)
# Instantiate optimizer
optimizer = AdamW(params=model.parameters(), lr=lr)
train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)
# Instantiate scheduler
lr_scheduler = get_linear_schedule_with_warmup(
optimizer=optimizer,
num_warmup_steps=100,
num_training_steps=(len(train_dataloader) * num_epochs),
)
# Prepare everything
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
# prepare method.
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
)
# Now we train the model
for epoch in range(num_epochs):
model.train()
for step, batch in enumerate(train_dataloader):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device)
outputs = model(**batch)
loss = outputs.loss
accelerator.backward(loss)
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
model.eval()
for step, batch in enumerate(eval_dataloader):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device)
with torch.no_grad():
outputs = model(**batch)
predictions = outputs.logits.argmax(dim=-1)
predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
metric.add_batch(
predictions=predictions,
references=references,
)
eval_metric = metric.compute()
# Use accelerator.print to print only on the main process.
accelerator.print(f"epoch {epoch}:", eval_metric)
# New Code #
# And call it at the end with no arguments
# Note: You could also refactor this outside of your training loop function
inner_training_loop() | null |
2,995 | import argparse
import json
import logging
import math
import os
import random
from itertools import chain
from pathlib import Path
import datasets
import torch
import transformers
from datasets import load_dataset
from huggingface_hub import Repository
from torch.utils.data import DataLoader
from tqdm.auto import tqdm
from transformers import (
CONFIG_MAPPING,
MODEL_MAPPING,
AutoConfig,
AutoModelForCausalLM,
AutoTokenizer,
SchedulerType,
default_data_collator,
get_scheduler,
)
from transformers.utils import get_full_repo_name
from transformers.utils.versions import require_version
from accelerate import Accelerator, DistributedType
from accelerate.logging import get_logger
from accelerate.utils import DummyOptim, DummyScheduler, set_seed
MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
def parse_args():
parser = argparse.ArgumentParser(description="Finetune a transformers model on a causal language modeling task")
parser.add_argument(
"--dataset_name",
type=str,
default=None,
help="The name of the dataset to use (via the datasets library).",
)
parser.add_argument(
"--dataset_config_name",
type=str,
default=None,
help="The configuration name of the dataset to use (via the datasets library).",
)
parser.add_argument(
"--train_file", type=str, default=None, help="A csv or a json file containing the training data."
)
parser.add_argument(
"--validation_file", type=str, default=None, help="A csv or a json file containing the validation data."
)
parser.add_argument(
"--validation_split_percentage",
default=5,
help="The percentage of the train set used as validation set in case there's no validation split",
)
parser.add_argument(
"--model_name_or_path",
type=str,
help="Path to pretrained model or model identifier from huggingface.co/models.",
required=False,
)
parser.add_argument(
"--config_name",
type=str,
default=None,
help="Pretrained config name or path if not the same as model_name",
)
parser.add_argument(
"--tokenizer_name",
type=str,
default=None,
help="Pretrained tokenizer name or path if not the same as model_name",
)
parser.add_argument(
"--use_slow_tokenizer",
action="store_true",
help="If passed, will use a slow tokenizer (not backed by the 🤗 Tokenizers library).",
)
parser.add_argument(
"--per_device_train_batch_size",
type=int,
default=8,
help="Batch size (per device) for the training dataloader.",
)
parser.add_argument(
"--per_device_eval_batch_size",
type=int,
default=8,
help="Batch size (per device) for the evaluation dataloader.",
)
parser.add_argument(
"--learning_rate",
type=float,
default=5e-5,
help="Initial learning rate (after the potential warmup period) to use.",
)
parser.add_argument("--weight_decay", type=float, default=0.0, help="Weight decay to use.")
parser.add_argument("--num_train_epochs", type=int, default=3, help="Total number of training epochs to perform.")
parser.add_argument(
"--max_train_steps",
type=int,
default=None,
help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
)
parser.add_argument(
"--gradient_accumulation_steps",
type=int,
default=1,
help="Number of updates steps to accumulate before performing a backward/update pass.",
)
parser.add_argument(
"--lr_scheduler_type",
type=SchedulerType,
default="linear",
help="The scheduler type to use.",
choices=["linear", "cosine", "cosine_with_restarts", "polynomial", "constant", "constant_with_warmup"],
)
parser.add_argument(
"--num_warmup_steps", type=int, default=0, help="Number of steps for the warmup in the lr scheduler."
)
parser.add_argument("--output_dir", type=str, default=None, help="Where to store the final model.")
parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
parser.add_argument(
"--model_type",
type=str,
default=None,
help="Model type to use if training from scratch.",
choices=MODEL_TYPES,
)
parser.add_argument(
"--block_size",
type=int,
default=None,
help=(
"Optional input sequence length after tokenization. The training dataset will be truncated in block of"
" this size for training. Default to the model max input length for single sentence inputs (take into"
" account special tokens)."
),
)
parser.add_argument(
"--preprocessing_num_workers",
type=int,
default=None,
help="The number of processes to use for the preprocessing.",
)
parser.add_argument(
"--overwrite_cache", type=bool, default=False, help="Overwrite the cached training and evaluation sets"
)
parser.add_argument(
"--no_keep_linebreaks", action="store_true", help="Do not keep line breaks when using TXT files."
)
parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
parser.add_argument(
"--hub_model_id", type=str, help="The name of the repository to keep in sync with the local `output_dir`."
)
parser.add_argument("--hub_token", type=str, help="The token to use to push to the Model Hub.")
parser.add_argument(
"--checkpointing_steps",
type=str,
default=None,
help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.",
)
parser.add_argument(
"--resume_from_checkpoint",
type=str,
default=None,
help="If the training should continue from a checkpoint folder.",
)
# New Code #
# Whether to load the best model at the end of training
parser.add_argument(
"--load_best_model",
action="store_true",
help="Whether to load the best model at the end of training",
)
parser.add_argument(
"--with_tracking",
action="store_true",
help="Whether to enable experiment trackers for logging.",
)
parser.add_argument(
"--report_to",
type=str,
default="all",
help=(
'The integration to report the results and logs to. Supported platforms are `"tensorboard"`,'
' `"wandb"`, `"comet_ml"`, and `"dvclive"`. Use `"all"` (default) to report to all integrations.'
"Only applicable when `--with_tracking` is passed."
),
)
args = parser.parse_args()
# Sanity checks
if args.dataset_name is None and args.train_file is None and args.validation_file is None:
raise ValueError("Need either a dataset name or a training/validation file.")
else:
if args.train_file is not None:
extension = args.train_file.split(".")[-1]
assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, json or txt file."
if args.validation_file is not None:
extension = args.validation_file.split(".")[-1]
assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, json or txt file."
if args.push_to_hub:
assert args.output_dir is not None, "Need an `output_dir` to create a repo when `--push_to_hub` is passed."
return args | null |
2,996 | import argparse
import json
import logging
import math
import os
import random
from itertools import chain
from pathlib import Path
import datasets
import torch
import transformers
from datasets import load_dataset
from huggingface_hub import Repository
from torch.utils.data import DataLoader
from tqdm.auto import tqdm
from transformers import (
CONFIG_MAPPING,
MODEL_MAPPING,
AutoConfig,
AutoModelForCausalLM,
AutoTokenizer,
SchedulerType,
default_data_collator,
get_scheduler,
)
from transformers.utils import get_full_repo_name
from transformers.utils.versions import require_version
from accelerate import Accelerator, DistributedType
from accelerate.logging import get_logger
from accelerate.utils import DummyOptim, DummyScheduler, set_seed
def evaluate(args, model, eval_dataloader, accelerator, eval_dataset):
model.eval()
losses = []
for step, batch in enumerate(eval_dataloader):
with torch.no_grad():
outputs = model(**batch)
loss = outputs.loss
losses.append(accelerator.gather_for_metrics(loss.repeat(args.per_device_eval_batch_size)))
losses = torch.cat(losses)
try:
eval_loss = torch.mean(losses)
perplexity = math.exp(eval_loss)
except OverflowError:
perplexity = float("inf")
return perplexity, eval_loss | null |
2,997 | import argparse
import os
import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
from accelerate import Accelerator, DistributedType
MAX_GPU_BATCH_SIZE = 16
def get_dataloaders(accelerator: Accelerator, batch_size: int = 16):
"""
Creates a set of `DataLoader`s for the `glue` dataset,
using "bert-base-cased" as the tokenizer.
Args:
accelerator (`Accelerator`):
An `Accelerator` object
batch_size (`int`, *optional*):
The batch size for the train and validation DataLoaders.
"""
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
datasets = load_dataset("glue", "mrpc")
def tokenize_function(examples):
# max_length=None => use the model max length (it's actually the default)
outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
return outputs
# Apply the method we just defined to all the examples in all the splits of the dataset
# starting with the main process first:
with accelerator.main_process_first():
tokenized_datasets = datasets.map(
tokenize_function,
batched=True,
remove_columns=["idx", "sentence1", "sentence2"],
)
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
# transformers library
tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
def collate_fn(examples):
# On TPU it's best to pad everything to the same length or training will be very slow.
max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None
# When using mixed precision we want round multiples of 8/16
if accelerator.mixed_precision == "fp8":
pad_to_multiple_of = 16
elif accelerator.mixed_precision != "no":
pad_to_multiple_of = 8
else:
pad_to_multiple_of = None
return tokenizer.pad(
examples,
padding="longest",
max_length=max_length,
pad_to_multiple_of=pad_to_multiple_of,
return_tensors="pt",
)
# Instantiate dataloaders.
train_dataloader = DataLoader(
tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
)
eval_dataloader = DataLoader(
tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
)
return train_dataloader, eval_dataloader
if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
from accelerate.test_utils.training import mocked_dataloaders
get_dataloaders = mocked_dataloaders # noqa: F811
def training_function(config, args):
# For testing only
if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
config["num_epochs"] = 2
# Initialize Accelerator
# New Code #
# We pass in "all" to `log_with` to grab all available trackers in the environment
# Note: If using a custom `Tracker` class, should be passed in here such as:
# >>> log_with = ["all", MyCustomTrackerClassInstance()]
if args.with_tracking:
accelerator = Accelerator(
cpu=args.cpu, mixed_precision=args.mixed_precision, log_with="all", project_dir=args.project_dir
)
else:
accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision)
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
lr = config["lr"]
num_epochs = int(config["num_epochs"])
seed = int(config["seed"])
batch_size = int(config["batch_size"])
set_seed(seed)
train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)
metric = evaluate.load("glue", "mrpc")
# If the batch size is too big we use gradient accumulation
gradient_accumulation_steps = 1
if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.XLA:
gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE
batch_size = MAX_GPU_BATCH_SIZE
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
model = model.to(accelerator.device)
# Instantiate optimizer
optimizer = AdamW(params=model.parameters(), lr=lr)
# Instantiate scheduler
lr_scheduler = get_linear_schedule_with_warmup(
optimizer=optimizer,
num_warmup_steps=100,
num_training_steps=(len(train_dataloader) * num_epochs) // gradient_accumulation_steps,
)
# Prepare everything
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
# prepare method.
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
)
# New Code #
# We need to initialize the trackers we use. Overall configurations can also be stored
if args.with_tracking:
run = os.path.split(__file__)[-1].split(".")[0]
accelerator.init_trackers(run, config)
# Now we train the model
for epoch in range(num_epochs):
model.train()
# New Code #
# For our tracking example, we will log the total loss of each epoch
if args.with_tracking:
total_loss = 0
for step, batch in enumerate(train_dataloader):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device)
outputs = model(**batch)
loss = outputs.loss
# New Code #
if args.with_tracking:
total_loss += loss.detach().float()
loss = loss / gradient_accumulation_steps
accelerator.backward(loss)
if step % gradient_accumulation_steps == 0:
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
model.eval()
for step, batch in enumerate(eval_dataloader):
# We could avoid this line since we set the accelerator with `device_placement=True` (the default).
batch.to(accelerator.device)
with torch.no_grad():
outputs = model(**batch)
predictions = outputs.logits.argmax(dim=-1)
predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
metric.add_batch(
predictions=predictions,
references=references,
)
eval_metric = metric.compute()
# Use accelerator.print to print only on the main process.
accelerator.print(f"epoch {epoch}:", eval_metric)
# New Code #
# To actually log, we call `Accelerator.log`
# The values passed can be of `str`, `int`, `float` or `dict` of `str` to `float`/`int`
if args.with_tracking:
accelerator.log(
{
"accuracy": eval_metric["accuracy"],
"f1": eval_metric["f1"],
"train_loss": total_loss.item() / len(train_dataloader),
"epoch": epoch,
},
step=epoch,
)
# New Code #
# When a run is finished, you should call `accelerator.end_training()`
# to close all of the open trackers
if args.with_tracking:
accelerator.end_training() | null |
2,998 | import argparse
from typing import List
import evaluate
import numpy as np
import torch
from datasets import DatasetDict, load_dataset
from sklearn.model_selection import StratifiedKFold
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
from accelerate import Accelerator, DistributedType
MAX_GPU_BATCH_SIZE = 16
def get_fold_dataloaders(
accelerator: Accelerator, dataset: DatasetDict, train_idxs: List[int], valid_idxs: List[int], batch_size: int = 16
):
"""
Gets a set of train, valid, and test dataloaders for a particular fold
Args:
accelerator (`Accelerator`):
The main `Accelerator` object
train_idxs (list of `int`):
The split indices for the training dataset
valid_idxs (list of `int`):
The split indices for the validation dataset
batch_size (`int`):
The size of the minibatch. Default is 16
"""
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
datasets = DatasetDict(
{
"train": dataset["train"].select(train_idxs),
"validation": dataset["train"].select(valid_idxs),
"test": dataset["validation"],
}
)
def tokenize_function(examples):
# max_length=None => use the model max length (it's actually the default)
outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
return outputs
# Apply the method we just defined to all the examples in all the splits of the dataset
# starting with the main process first:
with accelerator.main_process_first():
tokenized_datasets = datasets.map(
tokenize_function,
batched=True,
remove_columns=["idx", "sentence1", "sentence2"],
)
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
# transformers library
tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
def collate_fn(examples):
# On TPU it's best to pad everything to the same length or training will be very slow.
max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None
# When using mixed precision we want round multiples of 8/16
if accelerator.mixed_precision == "fp8":
pad_to_multiple_of = 16
elif accelerator.mixed_precision != "no":
pad_to_multiple_of = 8
else:
pad_to_multiple_of = None
return tokenizer.pad(
examples,
padding="longest",
max_length=max_length,
pad_to_multiple_of=pad_to_multiple_of,
return_tensors="pt",
)
# Instantiate dataloaders.
train_dataloader = DataLoader(
tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
)
eval_dataloader = DataLoader(
tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
)
test_dataloader = DataLoader(
tokenized_datasets["test"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
)
return train_dataloader, eval_dataloader, test_dataloader
def training_function(config, args):
# New Code #
test_predictions = []
# Download the dataset
datasets = load_dataset("glue", "mrpc")
# Create our splits
kfold = StratifiedKFold(n_splits=int(args.num_folds))
# Initialize accelerator
accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision)
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
lr = config["lr"]
num_epochs = int(config["num_epochs"])
seed = int(config["seed"])
batch_size = int(config["batch_size"])
metric = evaluate.load("glue", "mrpc")
# If the batch size is too big we use gradient accumulation
gradient_accumulation_steps = 1
if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.XLA:
gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE
batch_size = MAX_GPU_BATCH_SIZE
set_seed(seed)
# New Code #
# Create our folds:
folds = kfold.split(np.zeros(datasets["train"].num_rows), datasets["train"]["label"])
test_references = []
# Iterate over them
for i, (train_idxs, valid_idxs) in enumerate(folds):
train_dataloader, eval_dataloader, test_dataloader = get_fold_dataloaders(
accelerator,
datasets,
train_idxs,
valid_idxs,
)
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
model = model.to(accelerator.device)
# Instantiate optimizer
optimizer = AdamW(params=model.parameters(), lr=lr)
# Instantiate scheduler
lr_scheduler = get_linear_schedule_with_warmup(
optimizer=optimizer,
num_warmup_steps=100,
num_training_steps=(len(train_dataloader) * num_epochs) // gradient_accumulation_steps,
)
# Prepare everything
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
# prepare method.
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
)
# Now we train the model
for epoch in range(num_epochs):
model.train()
for step, batch in enumerate(train_dataloader):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device)
outputs = model(**batch)
loss = outputs.loss
loss = loss / gradient_accumulation_steps
accelerator.backward(loss)
if step % gradient_accumulation_steps == 0:
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
model.eval()
for step, batch in enumerate(eval_dataloader):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device)
with torch.no_grad():
outputs = model(**batch)
predictions = outputs.logits.argmax(dim=-1)
predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
metric.add_batch(
predictions=predictions,
references=references,
)
eval_metric = metric.compute()
# Use accelerator.print to print only on the main process.
accelerator.print(f"epoch {epoch}:", eval_metric)
# New Code #
# We also run predictions on the test set at the very end
fold_predictions = []
for step, batch in enumerate(test_dataloader):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device)
with torch.no_grad():
outputs = model(**batch)
predictions = outputs.logits
predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
fold_predictions.append(predictions.cpu())
if i == 0:
# We need all of the test predictions
test_references.append(references.cpu())
# Use accelerator.print to print only on the main process.
test_predictions.append(torch.cat(fold_predictions, dim=0))
# We now need to release all our memory and get rid of the current model, optimizer, etc
accelerator.free_memory()
# New Code #
# Finally we check the accuracy of our folded results:
test_references = torch.cat(test_references, dim=0)
preds = torch.stack(test_predictions, dim=0).sum(dim=0).div(int(args.num_folds)).argmax(dim=-1)
test_metric = metric.compute(predictions=preds, references=test_references)
accelerator.print("Average test metrics from all folds:", test_metric) | null |
2,999 | import argparse
import os
import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
from accelerate import Accelerator
from accelerate.utils import find_executable_batch_size
def get_dataloaders(accelerator: Accelerator, batch_size: int = 16):
if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
from accelerate.test_utils.training import mocked_dataloaders
get_dataloaders = mocked_dataloaders # noqa: F811
def training_function(config, args):
# For testing only
if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
config["num_epochs"] = 2
# Initialize accelerator
accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision)
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
lr = config["lr"]
num_epochs = int(config["num_epochs"])
seed = int(config["seed"])
observed_batch_size = int(config["batch_size"])
metric = evaluate.load("glue", "mrpc")
# New Code #
# We use the `find_executable_batch_size` decorator, passing in the desired observed batch size
# to train on. If a CUDA OOM error occurs, it will retry this loop cutting the batch size in
# half each time. From this, we can calculate the number of gradient accumulation steps needed
# and modify the Accelerator object as a result
@find_executable_batch_size(starting_batch_size=int(observed_batch_size))
def inner_training_loop(batch_size):
# Since we need to modify the outside accelerator object, we need to bring it
# to the local scope
nonlocal accelerator
# We can calculate the number of gradient accumulation steps based on the current
# batch size vs the starting batch size
num_gradient_accumulation_steps = observed_batch_size // batch_size
# And then set it in the Accelerator directly:
accelerator.gradient_accumulation_steps = num_gradient_accumulation_steps
# Next we need to free all of the stored model references in the Accelerator each time
accelerator.free_memory()
# And set the seed so our results are reproducable each reset
set_seed(seed)
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
model = model.to(accelerator.device)
# Instantiate optimizer
optimizer = AdamW(params=model.parameters(), lr=lr)
train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)
# Instantiate scheduler
lr_scheduler = get_linear_schedule_with_warmup(
optimizer=optimizer,
num_warmup_steps=100,
num_training_steps=(len(train_dataloader) * num_epochs),
)
# Prepare everything
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
# prepare method.
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
)
# Now we train the model
for epoch in range(num_epochs):
model.train()
for step, batch in enumerate(train_dataloader):
# And perform gradient accumulation
with accelerator.accumulate(model):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device)
outputs = model(**batch)
loss = outputs.loss
accelerator.backward(loss)
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
model.eval()
for step, batch in enumerate(eval_dataloader):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device)
with torch.no_grad():
outputs = model(**batch)
predictions = outputs.logits.argmax(dim=-1)
predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
metric.add_batch(
predictions=predictions,
references=references,
)
eval_metric = metric.compute()
# Use accelerator.print to print only on the main process.
accelerator.print(f"epoch {epoch}:", eval_metric)
# New Code #
# And call it at the end with no arguments
# Note: You could also refactor this outside of your training loop function
inner_training_loop() | null |
3,000 | import argparse
import os
import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
from accelerate import Accelerator, DistributedType
MAX_GPU_BATCH_SIZE = 16
EVAL_BATCH_SIZE = 32
def training_function(config, args):
# Initialize accelerator
if args.with_tracking:
accelerator = Accelerator(
cpu=args.cpu, mixed_precision=args.mixed_precision, log_with="all", project_dir=args.project_dir
)
else:
accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision)
if hasattr(args.checkpointing_steps, "isdigit"):
if args.checkpointing_steps == "epoch":
checkpointing_steps = args.checkpointing_steps
elif args.checkpointing_steps.isdigit():
checkpointing_steps = int(args.checkpointing_steps)
else:
raise ValueError(
f"Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed."
)
else:
checkpointing_steps = None
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
lr = config["lr"]
num_epochs = int(config["num_epochs"])
seed = int(config["seed"])
batch_size = int(config["batch_size"])
# We need to initialize the trackers we use, and also store our configuration
if args.with_tracking:
run = os.path.split(__file__)[-1].split(".")[0]
accelerator.init_trackers(run, config)
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
datasets = load_dataset("glue", "mrpc")
metric = evaluate.load("glue", "mrpc")
def tokenize_function(examples):
# max_length=None => use the model max length (it's actually the default)
outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
return outputs
# Apply the method we just defined to all the examples in all the splits of the dataset
# starting with the main process first:
with accelerator.main_process_first():
tokenized_datasets = datasets.map(
tokenize_function,
batched=True,
remove_columns=["idx", "sentence1", "sentence2"],
)
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
# transformers library
tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
# If the batch size is too big we use gradient accumulation
gradient_accumulation_steps = 1
if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.XLA:
gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE
batch_size = MAX_GPU_BATCH_SIZE
def collate_fn(examples):
# On TPU it's best to pad everything to the same length or training will be very slow.
max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None
# When using mixed precision we want round multiples of 8/16
if accelerator.mixed_precision == "fp8":
pad_to_multiple_of = 16
elif accelerator.mixed_precision != "no":
pad_to_multiple_of = 8
else:
pad_to_multiple_of = None
return tokenizer.pad(
examples,
padding="longest",
max_length=max_length,
pad_to_multiple_of=pad_to_multiple_of,
return_tensors="pt",
)
# Instantiate dataloaders.
train_dataloader = DataLoader(
tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
)
eval_dataloader = DataLoader(
tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
)
set_seed(seed)
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
model = model.to(accelerator.device)
# Instantiate optimizer
optimizer = AdamW(params=model.parameters(), lr=lr)
# Instantiate scheduler
lr_scheduler = get_linear_schedule_with_warmup(
optimizer=optimizer,
num_warmup_steps=100,
num_training_steps=(len(train_dataloader) * num_epochs) // gradient_accumulation_steps,
)
# Prepare everything
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
# prepare method.
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
)
# We need to keep track of how many total steps we have iterated over
overall_step = 0
# We also need to keep track of the stating epoch so files are named properly
starting_epoch = 0
# Potentially load in the weights and states from a previous save
if args.resume_from_checkpoint:
if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
accelerator.print(f"Resumed from checkpoint: {args.resume_from_checkpoint}")
accelerator.load_state(args.resume_from_checkpoint)
path = os.path.basename(args.resume_from_checkpoint)
else:
# Get the most recent checkpoint
dirs = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()]
dirs.sort(key=os.path.getctime)
path = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last
# Extract `epoch_{i}` or `step_{i}`
training_difference = os.path.splitext(path)[0]
if "epoch" in training_difference:
starting_epoch = int(training_difference.replace("epoch_", "")) + 1
resume_step = None
else:
resume_step = int(training_difference.replace("step_", ""))
starting_epoch = resume_step // len(train_dataloader)
resume_step -= starting_epoch * len(train_dataloader)
# Now we train the model
for epoch in range(starting_epoch, num_epochs):
model.train()
if args.with_tracking:
total_loss = 0
if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
# We need to skip steps until we reach the resumed step
active_dataloader = accelerator.skip_first_batches(train_dataloader, resume_step)
overall_step += resume_step
else:
# After the first iteration though, we need to go back to the original dataloader
active_dataloader = train_dataloader
for step, batch in enumerate(active_dataloader):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device)
outputs = model(**batch)
loss = outputs.loss
loss = loss / gradient_accumulation_steps
# We keep track of the loss at each epoch
if args.with_tracking:
total_loss += loss.detach().float()
accelerator.backward(loss)
if step % gradient_accumulation_steps == 0:
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
overall_step += 1
if isinstance(checkpointing_steps, int):
output_dir = f"step_{overall_step}"
if overall_step % checkpointing_steps == 0:
if args.output_dir is not None:
output_dir = os.path.join(args.output_dir, output_dir)
accelerator.save_state(output_dir)
model.eval()
for step, batch in enumerate(eval_dataloader):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device)
with torch.no_grad():
outputs = model(**batch)
predictions = outputs.logits.argmax(dim=-1)
predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
metric.add_batch(
predictions=predictions,
references=references,
)
eval_metric = metric.compute()
# Use accelerator.print to print only on the main process.
accelerator.print(f"epoch {epoch}:", eval_metric)
if args.with_tracking:
accelerator.log(
{
"accuracy": eval_metric["accuracy"],
"f1": eval_metric["f1"],
"train_loss": total_loss.item() / len(train_dataloader),
"epoch": epoch,
},
step=epoch,
)
if checkpointing_steps == "epoch":
output_dir = f"epoch_{epoch}"
if args.output_dir is not None:
output_dir = os.path.join(args.output_dir, output_dir)
accelerator.save_state(output_dir)
if args.with_tracking:
accelerator.end_training() | null |
3,001 | import gc
import threading
import time
import psutil
import torch
cpu_peak_tracker = PeakCPUMemory()
def start_measure():
# Time
measures = {"time": time.time()}
gc.collect()
torch.cuda.empty_cache()
# CPU mem
measures["cpu"] = psutil.Process().memory_info().rss
cpu_peak_tracker.start()
# GPU mem
for i in range(torch.cuda.device_count()):
measures[str(i)] = torch.cuda.memory_allocated(i)
torch.cuda.reset_peak_memory_stats()
return measures | null |
3,002 | import gc
import threading
import time
import psutil
import torch
cpu_peak_tracker = PeakCPUMemory()
def end_measure(start_measures):
# Time
measures = {"time": time.time() - start_measures["time"]}
gc.collect()
torch.cuda.empty_cache()
# CPU mem
measures["cpu"] = (psutil.Process().memory_info().rss - start_measures["cpu"]) / 2**20
measures["cpu-peak"] = (cpu_peak_tracker.stop() - start_measures["cpu"]) / 2**20
# GPU mem
for i in range(torch.cuda.device_count()):
measures[str(i)] = (torch.cuda.memory_allocated(i) - start_measures[str(i)]) / 2**20
measures[f"{i}-peak"] = (torch.cuda.max_memory_allocated(i) - start_measures[str(i)]) / 2**20
return measures | null |
3,003 | import gc
import threading
import time
import psutil
import torch
def log_measures(measures, description):
print(f"{description}:")
print(f"- Time: {measures['time']:.2f}s")
for i in range(torch.cuda.device_count()):
print(f"- GPU {i} allocated: {measures[str(i)]:.2f}MiB")
peak = measures[f"{i}-peak"]
print(f"- GPU {i} peak: {peak:.2f}MiB")
print(f"- CPU RAM allocated: {measures['cpu']:.2f}MiB")
print(f"- CPU RAM peak: {measures['cpu-peak']:.2f}MiB") | null |
3,004 | import argparse
import time
import torch
import transformers
from measures_util import end_measure, log_measures, start_measure
from transformers import AutoConfig, AutoModelForCausalLM, AutoModelForSeq2SeqLM, AutoTokenizer
from accelerate.utils import compute_module_sizes
DEFAULT_MODELS = {
"gpt-j-6b": {"is_causal": True, "model": "sgugger/sharded-gpt-j-6B", "tokenizer": "EleutherAI/gpt-j-6B"},
"gpt-neox": {"is_causal": True, "model": "EleutherAI/gpt-neox-20b"},
"opt": {"is_causal": True, "model": "facebook/opt-30b"},
"T0pp": {"is_causal": False, "model": "bigscience/T0pp", "model_revision": "sharded"},
}
def parse_args():
parser = argparse.ArgumentParser(description="Run and time generations on a big model using Accelerate.")
parser.add_argument("model_name", type=str, default=None, help="The name of the model to try.")
parser.add_argument(
"--tokenizer_name", type=str, default=None, help="The name of the tokenizer (if different from the model."
)
parser.add_argument("--is_causal", type=bool, default=None, help="Whether or not the model is causal.")
parser.add_argument(
"--model_revision", type=str, default=None, help="The revision to use for the model checkpoint."
)
parser.add_argument("--torch_dtype", type=str, default=None, help="The dtype for the model.")
parser.add_argument("--disk_offload", action="store_true")
args = parser.parse_args()
# Sanitize args
if args.model_name in DEFAULT_MODELS:
defaults = DEFAULT_MODELS[args.model_name]
args.model_name = defaults["model"]
if args.tokenizer_name is None:
args.tokenizer_name = defaults.get("tokenizer", args.model_name)
if args.is_causal is None:
args.is_causal = defaults["is_causal"]
if args.model_revision is None:
args.model_revision = defaults.get("model_revision", "main")
if args.is_causal is None:
raise ValueError("Could not infer the default for `--is_causal`, pass either True or False for it.")
if args.tokenizer_name is None:
args.tokenizer_name = args.model_name
if args.model_revision is None:
args.model_revision = "main"
return args | null |
3,005 | import typing
from decimal import Decimal
from borb.io.read.types import AnyPDFType
from borb.pdf.canvas.geometry.line_segment import LineSegment
from borb.pdf.canvas.operator.canvas_operator import CanvasOperator
class LineSegment:
"""
This class represents a line segment
"""
#
# CONSTRUCTOR
#
def __init__(self, x0: Decimal, y0: Decimal, x1: Decimal, y1: Decimal):
self.x0: Decimal = x0
self.y0: Decimal = y0
self.x1: Decimal = x1
self.y1: Decimal = y1
#
# PRIVATE
#
#
# PUBLIC
#
def get_end(self) -> typing.Tuple[Decimal, Decimal]:
"""
This function returns the end of this LineSegment
:return: the end (second point) of this LineSegment
"""
return (self.x1, self.y1)
def get_start(self) -> typing.Tuple[Decimal, Decimal]:
"""
This function returns the start of this LineSegment
:return: the start (first point) of this LineSegment
"""
return (self.x0, self.y0)
def length(self) -> Decimal:
"""
This function returns the length of this LineSegment
:return: the length of this LineSegment
"""
return Decimal(math.sqrt((self.x0 - self.x1) ** 2 + (self.y0 - self.y1) ** 2))
def transform_by(self, matrix: Matrix) -> "LineSegment":
"""
This function transforms the start and end of this LineSegment by a given Matrix,
it returns the transformed LineSegment
:param matrix: the matrix to transform by
:return: a new (transformed) LineSegment
"""
p0 = matrix.cross(self.x0, self.y0, Decimal(1))
p1 = matrix.cross(self.x1, self.y1, Decimal(1))
return LineSegment(p0[0], p0[1], p1[0], p1[1])
def _bezier(p0, p1, p2, p3) -> typing.List[LineSegment]:
pts = []
ONE = Decimal(1)
for t in [
Decimal(x) for x in [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
]:
x = (
(ONE - t) ** 3 * p0[0]
+ 3 * t * (ONE - t) ** 2 * p1[0]
+ 3 * t ** 2 * (ONE - t) * p2[0]
+ t ** 3 * p3[0]
)
y = (
(ONE - t) ** 3 * p0[1]
+ 3 * t * (ONE - t) ** 2 * p1[1]
+ 3 * t ** 2 * (ONE - t) * p2[1]
+ t ** 3 * p3[1]
)
pts.append((x, y))
# build List of LineSegments
out: typing.List[LineSegment] = []
for i in range(1, len(pts)):
out.append(LineSegment(pts[i - 1][0], pts[i - 1][1], pts[i][0], pts[i][1]))
# return
return out | null |
3,006 | ADOBE_STANDARD_ENCODING_LOOKUP = [
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55,
56, 57, 58, 59, 60, 61, 62, 63,
64, 65, 66, 67, 68, 69, 70, 71,
72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87,
88, 89, 90, 91, 92, 93, 94, 95,
8216, 97, 98, 99, 100, 101, 102, 103,
104, 105, 106, 107, 108, 109, 110, 111,
112, 113, 114, 115, 116, 117, 118, 119,
120, 121, 122, 123, 124, 125, 126, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 161, 162, 163, 8260, 165, 402, 167,
164, 39, 8220, 171, 8249, 8250, 64257, 64258,
0, 8211, 8224, 8225, 183, 0, 182, 8226,
8218, 8222, 8221, 187, 8230, 8240, 0, 191,
0, 96, 180, 710, 732, 175, 728, 729,
168, 0, 730, 184, 0, 733, 731, 711,
8212, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 198, 0, 170, 0, 0, 0, 0,
321, 216, 338, 186, 0, 0, 0, 0,
0, 230, 0, 0, 0, 305, 0, 0,
322, 248, 339, 223, 0, 0, 0, 0,
]
The provided code snippet includes necessary dependencies for implementing the `adobe_standard_decode` function. Write a Python function `def adobe_standard_decode(byte_input: bytes) -> str` to solve the following problem:
This function decodes bytes using StandardEncoding :param byte_input: the input :return: a str (representing the decoded bytes)
Here is the function:
def adobe_standard_decode(byte_input: bytes) -> str:
"""
This function decodes bytes using StandardEncoding
:param byte_input: the input
:return: a str (representing the decoded bytes)
"""
s: str = ""
for b in byte_input:
s += chr(ADOBE_STANDARD_ENCODING_LOOKUP[b])
return s | This function decodes bytes using StandardEncoding :param byte_input: the input :return: a str (representing the decoded bytes) |
3,007 | ADOBE_STANDARD_ENCODING_LOOKUP = [
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55,
56, 57, 58, 59, 60, 61, 62, 63,
64, 65, 66, 67, 68, 69, 70, 71,
72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87,
88, 89, 90, 91, 92, 93, 94, 95,
8216, 97, 98, 99, 100, 101, 102, 103,
104, 105, 106, 107, 108, 109, 110, 111,
112, 113, 114, 115, 116, 117, 118, 119,
120, 121, 122, 123, 124, 125, 126, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 161, 162, 163, 8260, 165, 402, 167,
164, 39, 8220, 171, 8249, 8250, 64257, 64258,
0, 8211, 8224, 8225, 183, 0, 182, 8226,
8218, 8222, 8221, 187, 8230, 8240, 0, 191,
0, 96, 180, 710, 732, 175, 728, 729,
168, 0, 730, 184, 0, 733, 731, 711,
8212, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 198, 0, 170, 0, 0, 0, 0,
321, 216, 338, 186, 0, 0, 0, 0,
0, 230, 0, 0, 0, 305, 0, 0,
322, 248, 339, 223, 0, 0, 0, 0,
]
The provided code snippet includes necessary dependencies for implementing the `adobe_standard_encode` function. Write a Python function `def adobe_standard_encode(str_input: str) -> bytes` to solve the following problem:
This function encodes a str using StandardEncoding :param str_input: the input :return: bytes (representing the encoded str)
Here is the function:
def adobe_standard_encode(str_input: str) -> bytes:
"""
This function encodes a str using StandardEncoding
:param str_input: the input
:return: bytes (representing the encoded str)
"""
b: bytearray = bytearray()
for c in str_input:
char_index: int = -1
try:
char_index = ADOBE_STANDARD_ENCODING_LOOKUP.index(ord(c))
except ValueError:
pass
if char_index != -1:
b.append(char_index)
return b | This function encodes a str using StandardEncoding :param str_input: the input :return: bytes (representing the encoded str) |
3,008 | SYMBOL_ENCODING_LOOKUP = [
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
32, 33, 8704, 35, 8707, 37, 38, 8715,
40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55,
56, 57, 58, 59, 60, 61, 62, 63,
8773, 913, 914, 935, 916, 917, 934, 915,
919, 921, 977, 922, 923, 924, 925, 927,
928, 920, 929, 931, 932, 933, 962, 937,
926, 936, 918, 91, 8756, 93, 8869, 95,
773, 945, 946, 967, 948, 949, 981, 947,
951, 953, 966, 954, 955, 956, 957, 959,
960, 952, 961, 963, 964, 965, 982, 969,
958, 968, 950, 123, 124, 125, 126, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
8364, 978, 8242, 8804, 8260, 8734, 402, 9827,
9830, 9829, 9824, 8596, 8592, 8593, 8594, 8595,
176, 177, 8243, 8805, 215, 8733, 8706, 8226,
247, 8800, 8801, 8776, 8230, 9474, 9472, 8629,
8501, 8465, 8476, 8472, 8855, 8853, 8709, 8745,
8746, 8835, 8839, 8836, 8834, 8838, 8712, 8713,
8736, 8711, 174, 169, 8482, 8719, 8730, 8901,
172, 8743, 8744, 8660, 8656, 8657, 8658, 8659,
9674, 9001, 0, 0, 0, 8721, 9115, 9116,
9117, 9121, 9122, 9123, 9127, 9128, 9129, 9130,
0, 9002, 8747, 8992, 9134, 8993, 9118, 9119,
9120, 9124, 9125, 9126, 9131, 9132, 9133, 0,
]
The provided code snippet includes necessary dependencies for implementing the `symbol_decode` function. Write a Python function `def symbol_decode(byte_input: bytes) -> str` to solve the following problem:
This function decodes bytes using SymbolEncoding :param byte_input: the input :return: a str (representing the decoded bytes)
Here is the function:
def symbol_decode(byte_input: bytes) -> str:
"""
This function decodes bytes using SymbolEncoding
:param byte_input: the input
:return: a str (representing the decoded bytes)
"""
s: str = ""
for b in byte_input:
s += chr(SYMBOL_ENCODING_LOOKUP[b])
return s | This function decodes bytes using SymbolEncoding :param byte_input: the input :return: a str (representing the decoded bytes) |
3,009 | SYMBOL_ENCODING_LOOKUP = [
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
32, 33, 8704, 35, 8707, 37, 38, 8715,
40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55,
56, 57, 58, 59, 60, 61, 62, 63,
8773, 913, 914, 935, 916, 917, 934, 915,
919, 921, 977, 922, 923, 924, 925, 927,
928, 920, 929, 931, 932, 933, 962, 937,
926, 936, 918, 91, 8756, 93, 8869, 95,
773, 945, 946, 967, 948, 949, 981, 947,
951, 953, 966, 954, 955, 956, 957, 959,
960, 952, 961, 963, 964, 965, 982, 969,
958, 968, 950, 123, 124, 125, 126, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
8364, 978, 8242, 8804, 8260, 8734, 402, 9827,
9830, 9829, 9824, 8596, 8592, 8593, 8594, 8595,
176, 177, 8243, 8805, 215, 8733, 8706, 8226,
247, 8800, 8801, 8776, 8230, 9474, 9472, 8629,
8501, 8465, 8476, 8472, 8855, 8853, 8709, 8745,
8746, 8835, 8839, 8836, 8834, 8838, 8712, 8713,
8736, 8711, 174, 169, 8482, 8719, 8730, 8901,
172, 8743, 8744, 8660, 8656, 8657, 8658, 8659,
9674, 9001, 0, 0, 0, 8721, 9115, 9116,
9117, 9121, 9122, 9123, 9127, 9128, 9129, 9130,
0, 9002, 8747, 8992, 9134, 8993, 9118, 9119,
9120, 9124, 9125, 9126, 9131, 9132, 9133, 0,
]
The provided code snippet includes necessary dependencies for implementing the `symbol_encode` function. Write a Python function `def symbol_encode(str_input: str) -> bytes` to solve the following problem:
This function encodes a str using SymbolEncoding :param str_input: the input :return: bytes (representing the encoded str)
Here is the function:
def symbol_encode(str_input: str) -> bytes:
"""
This function encodes a str using SymbolEncoding
:param str_input: the input
:return: bytes (representing the encoded str)
"""
b: bytearray = bytearray()
for c in str_input:
char_index: int = -1
try:
char_index = SYMBOL_ENCODING_LOOKUP.index(ord(c))
except ValueError:
pass
if char_index != -1:
b.append(char_index)
return b | This function encodes a str using SymbolEncoding :param str_input: the input :return: bytes (representing the encoded str) |
3,010 | ZAPFDINGBATS_ENCODING_LOOKUP = [
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
32, 9985, 9986, 9987, 9988, 9742, 9990, 9991,
9992, 9993, 9755, 9758, 9996, 9997, 9998, 9999,
10000, 10001, 10002, 10003, 10004, 10005, 10006, 10007,
10008, 10009, 10010, 10011, 10012, 10013, 10014, 10015,
10016, 10017, 10018, 10019, 10020, 10021, 10022, 10023,
9733, 10025, 10026, 10027, 10028, 10029, 10030, 10031,
10032, 10033, 10034, 10035, 10036, 10037, 10038, 10039,
10040, 10041, 10042, 10043, 10044, 10045, 10046, 10047,
10048, 10049, 10050, 10051, 10052, 10053, 10054, 10055,
10056, 10057, 10058, 10059, 9679, 10061, 9632, 10063,
10064, 10065, 10066, 9650, 9660, 9670, 10070, 9687,
10072, 10073, 10074, 10075, 10076, 10077, 10078, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 10081, 10082, 10083, 10084, 10085, 10086, 10087,
9827, 9830, 9829, 9824, 9312, 9313, 9314, 9315,
9316, 9317, 9318, 9319, 9320, 9321, 10102, 10103,
10104, 10105, 10106, 10107, 10108, 10109, 10110, 10111,
10112, 10113, 10114, 10115, 10116, 10117, 10118, 10119,
10120, 10121, 10122, 10123, 10124, 10125, 10126, 10127,
10128, 10129, 10130, 10131, 10132, 8594, 8596, 8597,
10136, 10137, 10138, 10139, 10140, 10141, 10142, 10143,
10144, 10145, 10146, 10147, 10148, 10149, 10150, 10151,
10152, 10153, 10154, 10155, 10156, 10157, 10158, 10159,
0, 10161, 10162, 10163, 10164, 10165, 10166, 10167,
10168, 10169, 10170, 10171, 10172, 10173, 10174, 0,
]
The provided code snippet includes necessary dependencies for implementing the `zapfdingbats_decode` function. Write a Python function `def zapfdingbats_decode(byte_input: bytes) -> str` to solve the following problem:
This function decodes bytes using ZapfDingbats :param byte_input: the input :return: a str (representing the decoded bytes)
Here is the function:
def zapfdingbats_decode(byte_input: bytes) -> str:
"""
This function decodes bytes using ZapfDingbats
:param byte_input: the input
:return: a str (representing the decoded bytes)
"""
s: str = ""
for b in byte_input:
s += chr(ZAPFDINGBATS_ENCODING_LOOKUP[b])
return s | This function decodes bytes using ZapfDingbats :param byte_input: the input :return: a str (representing the decoded bytes) |
3,011 | ZAPFDINGBATS_ENCODING_LOOKUP = [
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
32, 9985, 9986, 9987, 9988, 9742, 9990, 9991,
9992, 9993, 9755, 9758, 9996, 9997, 9998, 9999,
10000, 10001, 10002, 10003, 10004, 10005, 10006, 10007,
10008, 10009, 10010, 10011, 10012, 10013, 10014, 10015,
10016, 10017, 10018, 10019, 10020, 10021, 10022, 10023,
9733, 10025, 10026, 10027, 10028, 10029, 10030, 10031,
10032, 10033, 10034, 10035, 10036, 10037, 10038, 10039,
10040, 10041, 10042, 10043, 10044, 10045, 10046, 10047,
10048, 10049, 10050, 10051, 10052, 10053, 10054, 10055,
10056, 10057, 10058, 10059, 9679, 10061, 9632, 10063,
10064, 10065, 10066, 9650, 9660, 9670, 10070, 9687,
10072, 10073, 10074, 10075, 10076, 10077, 10078, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 10081, 10082, 10083, 10084, 10085, 10086, 10087,
9827, 9830, 9829, 9824, 9312, 9313, 9314, 9315,
9316, 9317, 9318, 9319, 9320, 9321, 10102, 10103,
10104, 10105, 10106, 10107, 10108, 10109, 10110, 10111,
10112, 10113, 10114, 10115, 10116, 10117, 10118, 10119,
10120, 10121, 10122, 10123, 10124, 10125, 10126, 10127,
10128, 10129, 10130, 10131, 10132, 8594, 8596, 8597,
10136, 10137, 10138, 10139, 10140, 10141, 10142, 10143,
10144, 10145, 10146, 10147, 10148, 10149, 10150, 10151,
10152, 10153, 10154, 10155, 10156, 10157, 10158, 10159,
0, 10161, 10162, 10163, 10164, 10165, 10166, 10167,
10168, 10169, 10170, 10171, 10172, 10173, 10174, 0,
]
The provided code snippet includes necessary dependencies for implementing the `zapfdingbats_encode` function. Write a Python function `def zapfdingbats_encode(str_input: str) -> bytes` to solve the following problem:
This function encodes a str using ZapfDingbats :param str_input: the input :return: bytes (representing the encoded str)
Here is the function:
def zapfdingbats_encode(str_input: str) -> bytes:
"""
This function encodes a str using ZapfDingbats
:param str_input: the input
:return: bytes (representing the encoded str)
"""
b: bytearray = bytearray()
for c in str_input:
char_index: int = -1
try:
char_index = ZAPFDINGBATS_ENCODING_LOOKUP.index(ord(c))
except ValueError:
pass
if char_index != -1:
b.append(char_index)
return b | This function encodes a str using ZapfDingbats :param str_input: the input :return: bytes (representing the encoded str) |
3,012 | import typing
from decimal import Decimal
from borb.io.filter.ascii85_decode import ASCII85Decode
from borb.io.filter.flate_decode import FlateDecode
from borb.io.filter.lzw_decode import LZWDecode
from borb.io.filter.run_length_decode import RunLengthDecode
from borb.io.read.types import Dictionary
from borb.io.read.types import List
from borb.io.read.types import Name
from borb.io.read.types import Stream
class ASCII85Decode:
"""
Decodes data encoded in an ASCII base-85 representation,
reproducing the original binary data.
"""
#
# CONSTRUCTOR
#
#
# PRIVATE
#
#
# PUBLIC
#
def decode(bytes_in: bytes) -> bytes:
"""
Decodes data encoded in an ASCII base-85 representation
:param bytes_in: the input bytes
:return: the output bytes
"""
exceptions_to_throw = []
# trivial case
if len(bytes_in) == 0:
return bytes_in
# trimming
if bytes_in[-1] == 10 and bytes_in[-2] == 13:
bytes_in = bytes_in[0:-2]
if bytes_in[-1] == 10:
bytes_in = bytes_in[0:-1]
if bytes_in[-1] == 13:
bytes_in = bytes_in[0:-1]
# normal decode
try:
return base64.a85decode(bytes_in)
except Exception as e:
exceptions_to_throw.append(e)
pass
# adobe decode
try:
return base64.a85decode(bytes_in, adobe=True)
except Exception as e:
exceptions_to_throw.append(e)
pass
# we should not be here
raise exceptions_to_throw[0]
class FlateDecode:
"""
LZW and Flate encoding compress more compactly if their input data is highly predictable.
One way of increasing the predictability of many continuous-tone sampled images is to replace each sample with the
difference between that sample and a predictor function applied to earlier neighboring samples.
If the predictor function works well, the postprediction data clusters toward 0.
PDF supports two groups of Predictor functions.
The first, the TIFF group, consists of the single function that is Predictor 2 in the TIFF 6.0 specification.
"""
#
# CONSTRUCTOR
#
#
# PRIVATE
#
#
# PUBLIC
#
def decode(
bytes_in: bytes,
bits_per_component: int = 8,
columns: int = 1,
predictor: int = 1,
) -> bytes:
"""
LZW and Flate encoding compress more compactly if their input data is highly predictable.
One way of increasing the predictability of many continuous-tone sampled images is to replace each sample with the
difference between that sample and a predictor function applied to earlier neighboring samples.
If the predictor function works well, the postprediction data clusters toward 0.
PDF supports two groups of Predictor functions.
The first, the TIFF group, consists of the single function that is Predictor 2 in the TIFF 6.0 specification.
:param bytes_in: the input bytes
:param bits_per_component: the number of bits per component
:param columns: the number of columns
:param predictor: which predictor to use
:return: the output bytes
"""
# trivial case
if len(bytes_in) == 0:
return bytes_in
# check /Predictor
# fmt: off
assert predictor in [1, 2, 10, 11, 12, 13, 14, 15,], "Illegal argument exception. predictor must be in [1, 2, 10, 11, 12, 13, 14, 15]."
# fmt: on
# check /BitsPerComponent
# fmt: off
assert bits_per_component in [1, 2, 4, 8], "Illegal argument exception. bits_per_component must be in [1, 2, 4, 8]."
# fmt: on
# initial transform
bytes_after_zlib = zlib.decompress(bytes_in, bufsize=4092)
# LZW and Flate encoding compress more compactly if their input data is highly predictable. One way of
# increasing the predictability of many continuous-tone sampled images is to replace each sample with the
# difference between that sample and a predictor function applied to earlier neighboring samples. If the predictor
# function works well, the postprediction data clusters toward 0.
# PDF supports two groups of Predictor functions. The first, the TIFF group, consists of the single function that is
# Predictor 2 in the TIFF 6.0 specification.
# check predictor
if predictor == 1:
return bytes_after_zlib
# set up everything to do PNG prediction
bytes_per_row: int = int((columns * bits_per_component + 7) / 8)
bytes_per_pixel = int(bits_per_component / 8)
current_row: typing.List[int] = [0 for _ in range(0, bytes_per_row)]
prior_row: typing.List[int] = [0 for _ in range(0, bytes_per_row)]
number_of_rows = int(len(bytes_after_zlib) / bytes_per_row)
# easy case
bytes_after_predictor = [int(x) for x in bytes_after_zlib]
if predictor == 2:
if bits_per_component == 8:
for row in range(0, number_of_rows):
row_start_index = row * bytes_per_row
for col in range(1, bytes_per_row):
bytes_after_predictor[row_start_index + col] = (
bytes_after_predictor[row_start_index + col]
+ bytes_after_predictor[row_start_index + col - 1]
) % 256
return bytes([(int(x) % 256) for x in bytes_after_predictor])
# harder cases
bytes_after_predictor = []
pos = 0
while pos + bytes_per_row <= len(bytes_after_zlib):
# Read the filter type byte and a row of data
filter_type = bytes_after_zlib[pos]
pos += 1
current_row = [x for x in bytes_after_zlib[pos : pos + bytes_per_row]]
pos += bytes_per_row
# PNG_FILTER_NONE
if filter_type == 0:
# DO NOTHING
pass
# PNG_FILTER_SUB
# Predicts the same as the sample to the left
if filter_type == 1:
for i in range(bytes_per_pixel, bytes_per_row):
current_row[i] = (
current_row[i] + current_row[i - bytes_per_pixel]
) % 256
# PNG_FILTER_UP
# Predicts the same as the sample above
if filter_type == 2:
for i in range(0, bytes_per_row):
current_row[i] = (current_row[i] + prior_row[i]) % 256
# PNG_FILTER_AVERAGE
# Predicts the average of the sample to the left and the
# sample above
if filter_type == 3:
for i in range(0, bytes_per_pixel):
current_row[i] += int(prior_row[i] / 2)
for i in range(bytes_per_pixel, bytes_per_row):
current_row[i] += (int)(
(current_row[i - bytes_per_pixel] + prior_row[i]) / 2
)
current_row[i] %= 256
# PNG_FILTER_PAETH
if filter_type == 4:
for i in range(0, bytes_per_pixel):
current_row[i] += prior_row[i]
for i in range(bytes_per_pixel, bytes_per_row):
a = current_row[i - bytes_per_pixel]
b = prior_row[i]
c = prior_row[i - bytes_per_pixel]
p = a + b - c
pa = abs(p - a)
pb = abs(p - b)
pc = abs(p - c)
ret = 0
if pa <= pb and pa <= pc:
ret = a
elif pb <= pc:
ret = b
else:
ret = c
current_row[i] = (current_row[i] + ret) % 256
# write current row
for i in range(0, len(current_row)):
bytes_after_predictor.append(current_row[i])
# Swap curr and prior
prior_row = copy.deepcopy(current_row)
# return
return bytes([(int(x) % 256) for x in bytes_after_predictor])
class LZWDecode:
"""
Decompresses data encoded using the LZW (Lempel-Ziv-Welch) adaptive compression method,
reproducing the original text or binary data.
"""
#
# CONSTRUCTOR
#
def __init__(self):
self._bits_to_read: int = 9
self._lookup_table: typing.Dict[int, bytearray] = {}
self._table_index: int = 0
#
# PRIVATE
#
def _add_to_lookup_table(self, new_bytes: bytes, prev_bytes: bytearray):
self._lookup_table[self._table_index] = prev_bytes + new_bytes
self._table_index += 1
if self._table_index == 511:
self._bits_to_read = 10
elif self._table_index == 1023:
self._bits_to_read = 11
elif self._table_index == 2047:
self._bits_to_read = 12
def _init_lookup_table(self):
self._lookup_table = {i: i.to_bytes(1, "big") for i in range(0, 256)}
self._table_index = 258
self._bits_to_read = 9
#
# PUBLIC
#
def decode(self, input: bytes):
"""
Decompresses data encoded using the LZW (Lempel-Ziv-Welch) adaptive compression method
:param input: the input bytes
:return: the output bytes
"""
# output
bytes_out: bytearray = bytearray()
# read
bit_input: bitarray = bitarray(input)
prev_code: int = 0
code: int = 0
while code != 257:
code = bit_input.next(self._bits_to_read)
if code == 257:
break
# init
if code == 256:
self._init_lookup_table()
code = bit_input.next(self._bits_to_read)
if code == 257:
break
bytes_out += self._lookup_table[code]
prev_code = code
continue
# normal behaviour
x: bytearray = bytearray()
if code < self._table_index:
x = self._lookup_table[code]
bytes_out += x
self._add_to_lookup_table(
new_bytes=x[0:1], prev_bytes=self._lookup_table[prev_code]
)
prev_code = code
else:
x = self._lookup_table[prev_code]
x = x + x[0:1]
bytes_out += x
self._add_to_lookup_table(new_bytes=bytearray(), prev_bytes=x)
prev_code = code
# return bytes
return bytes_out
class RunLengthDecode:
"""
Decompresses data encoded using a byte-oriented run-length
encoding algorithm, reproducing the original text or binary data
(typically monochrome image data, or any data that contains
frequent long runs of a single byte value).
"""
#
# CONSTRUCTOR
#
#
# PRIVATE
#
#
# PUBLIC
#
def decode(bytes_in: bytes) -> bytes:
"""
Decompresses data encoded using a byte-oriented run-length encoding algorithm
:param bytes_in: the input bytes
:return: the output bytes
"""
# trivial case
if len(bytes_in) == 0:
return bytes_in
# The RunLengthDecode filter decodes data that has been encoded in a simple byte-oriented format based on
# run length. The encoded data shall be a sequence of runs, where each run shall consist of a length byte
# followed by 1 to 128 bytes of data. If the length byte is in the range 0 to 127, the following length + 1 (1 to 128)
# bytes shall be copied literally during decompression. If length is in the range 129 to 255, the following single
# byte shall be copied 257 - length (2 to 128) times during decompression. A length value of 128 shall denote
# EOF.
bytes_out = bytearray()
i: int = 0
while i < len(bytes_in):
b = bytes_in[i]
# A length value of 128 shall denote EOF.
if b == 128:
break
# If the length byte is in the range 0 to 127, the following length + 1 (1 to 128)
# bytes shall be copied literally during decompression.
length: int = 0
if 0 <= b <= 127:
length = b + 1
i += 1
for j in range(0, length):
bytes_out.append(bytes_in[i + j])
i += length
continue
# If length is in the range 129 to 255, the following single
# byte shall be copied 257 - length (2 to 128) times during decompression
if 129 <= b <= 255:
length = 257 - b
i += 1
for _ in range(0, length):
bytes_out.append(bytes_in[i])
i += 1
# return
return bytes(bytes_out)
class Dictionary(PDFObject, dict):
"""
A dictionary object is an associative table containing pairs of objects, known as the dictionary’s entries. The first
element of each entry is the key and the second element is the value. The key shall be a name (unlike
dictionary keys in PostScript, which may be objects of any type). The value may be any kind of object, including
another dictionary. A dictionary entry whose value is null (see 7.3.9, "Null Object") shall be treated the same as
if the entry does not exist. (This differs from PostScript, where null behaves like any other object as the value
of a dictionary entry.) The number of entries in a dictionary shall be subject to an implementation limit; see
Annex C. A dictionary may have zero entries.
The entries in a dictionary represent an associative table and as such shall be unordered even though an
arbitrary order may be imposed upon them when written in a file. That ordering shall be ignored.
"""
#
# CONSTRUCTOR
#
def __init__(self):
super(Dictionary, self).__init__()
#
# PRIVATE
#
def __deepcopy__(self, memodict={}):
out = type(self).__new__(type(self))
Dictionary.__init__(out)
for k, v in self.items():
out[copy.deepcopy(k, memodict)] = copy.deepcopy(v, memodict)
return out
def __hash__(self):
hashcode: int = 1
for e in self:
hashcode = 31 * hashcode + (0 if e is None else hash(e))
return hashcode
def __setitem__(self, key, value):
assert isinstance(key, Name)
super(Dictionary, self).__setitem__(key, value)
#
# PUBLIC
#
class List(PDFObject, list):
"""
An array object is a one-dimensional collection of objects arranged sequentially. Unlike arrays in many other
computer languages, PDF arrays may be heterogeneous; that is, an array’s elements may be any combination
of numbers, strings, dictionaries, or any other objects, including other arrays. An array may have zero
elements.
"""
#
# CONSTRUCTOR
#
def __init__(self):
super(List, self).__init__()
#
# PRIVATE
#
def __hash__(self):
hashcode: int = 1
for e in self:
hashcode = 31 * hashcode + (0 if e is None else hash(e))
return hashcode
#
# PUBLIC
#
class Name(PDFObject):
"""
Beginning with PDF 1.2 a name object is an atomic symbol uniquely defined by a sequence of any characters
(8-bit values) except null (character code 0). Uniquely defined means that any two name objects made up of
the same sequence of characters denote the same object. Atomic means that a name has no internal structure;
although it is defined by a sequence of characters, those characters are not considered elements of the name.
"""
#
# CONSTRUCTOR
#
def __init__(self, text: str):
super().__init__()
self._text = text
#
# PRIVATE
#
def __eq__(self, other):
if isinstance(other, Name):
return other._text == self._text
if isinstance(other, str):
return other == self._text
return False
def __ge__(self, other):
if isinstance(other, Name):
return self._text >= other._text
if isinstance(other, str):
return self._text >= other
assert False
def __gt__(self, other):
if isinstance(other, Name):
return self._text > other._text
if isinstance(other, str):
return self._text > other
assert False
def __hash__(self):
return self._text.__hash__()
def __le__(self, other):
if isinstance(other, Name):
return self._text <= other._text
if isinstance(other, str):
return self._text <= other
assert False
def __lt__(self, other):
if isinstance(other, Name):
return self._text < other._text
if isinstance(other, str):
return self._text < other
assert False
def __str__(self):
return self._text
#
# PUBLIC
#
class Stream(Dictionary):
"""
A stream object, like a string object, is a sequence of bytes. Furthermore, a stream may be of unlimited length,
whereas a string shall be subject to an implementation limit. For this reason, objects with potentially large
amounts of data, such as images and page descriptions, shall be represented as streams.
"""
#
# CONSTRUCTOR
#
def __init__(self):
super(Stream, self).__init__()
#
# PRIVATE
#
#
# PUBLIC
#
The provided code snippet includes necessary dependencies for implementing the `decode_stream` function. Write a Python function `def decode_stream(s: Stream) -> Stream` to solve the following problem:
This function decodes a Stream, applying the filters specified in the Filter entry of its stream dictionary :param s: the input Stream object :return: the input Stream, modified to contain the decoded bytes
Here is the function:
def decode_stream(s: Stream) -> Stream:
"""
This function decodes a Stream, applying the filters specified in the Filter entry of its stream dictionary
:param s: the input Stream object
:return: the input Stream, modified to contain the decoded bytes
"""
# fmt: off
assert isinstance(s, Stream), "decode_stream only works on Stream objects"
assert ("Bytes" in s), "decode_stream only works on Stream objects with a `Bytes` key."
# fmt: on
# IF stream already has /DecodedBytes
# THEN return stream
if "DecodedBytes" in s:
return s
# determine filter(s) to apply
filters: typing.List[str] = []
if "Filter" in s:
if isinstance(s["Filter"], List):
filters = s["Filter"]
else:
filters = [s["Filter"]]
decode_params: typing.List[Dictionary] = []
if "DecodeParms" in s:
if isinstance(s["DecodeParms"], List):
decode_params = s["DecodeParms"]
decode_params = [x or Dictionary() for x in decode_params]
else:
assert s["DecodeParms"] is not None
assert isinstance(s["DecodeParms"], Dictionary)
decode_params = [s["DecodeParms"]]
else:
decode_params = [Dictionary() for x in range(0, len(filters))]
# apply filter(s)
transformed_bytes = s["Bytes"]
for filter_index, filter_name in enumerate(filters):
# FLATE
if filter_name in ["FlateDecode", "Fl"]:
transformed_bytes = FlateDecode.decode(
bytes_in=transformed_bytes,
columns=int(decode_params[filter_index].get("Columns", Decimal(1))),
predictor=int(decode_params[filter_index].get("Predictor", Decimal(1))),
bits_per_component=int(
decode_params[filter_index].get("BitsPerComponent", Decimal(8))
),
)
continue
# ASCII85
if filter_name in ["ASCII85Decode"]:
transformed_bytes = ASCII85Decode.decode(transformed_bytes)
continue
# LZW
if filter_name in ["LZWDecode"]:
transformed_bytes = LZWDecode().decode(transformed_bytes)
continue
# RunLengthDecode
if filter_name in ["RunLengthDecode"]:
transformed_bytes = RunLengthDecode.decode(transformed_bytes)
continue
# unknown filter
assert False, "Unknown /Filter %s" % filter_name
# set DecodedBytes
s[Name("DecodedBytes")] = transformed_bytes
# set Type if not yet set
# if "Type" not in s:
# s[Name("Type")] = Name("Stream")
# return
return s | This function decodes a Stream, applying the filters specified in the Filter entry of its stream dictionary :param s: the input Stream object :return: the input Stream, modified to contain the decoded bytes |
3,013 | import math
import warnings
from typing import Optional
import torch
import torch.nn as nn
from einops import rearrange
from torch import nn
from .norm import LPLayerNorm
def scaled_multihead_dot_product_attention(query, key, value, n_heads, softmax_scale=None, attn_bias=None, key_padding_mask=None, is_causal=False, dropout_p=0.0, training=False, needs_weights=False, multiquery=False):
q = rearrange(query, 'b s (h d) -> b h s d', h=n_heads)
k = rearrange(key, 'b s (h d) -> b h d s', h=1 if multiquery else n_heads)
v = rearrange(value, 'b s (h d) -> b h s d', h=1 if multiquery else n_heads)
min_val = torch.finfo(q.dtype).min
(b, _, s_q, d) = q.shape
s_k = k.size(-1)
if softmax_scale is None:
softmax_scale = 1 / math.sqrt(d)
attn_weight = q.matmul(k) * softmax_scale
if attn_bias is not None:
if attn_bias.size(-1) != 1 and attn_bias.size(-1) != s_k or (attn_bias.size(-2) != 1 and attn_bias.size(-2) != s_q):
raise RuntimeError(f'attn_bias (shape: {attn_bias.shape}) is expected to broadcast to shape: {attn_weight.shape}.')
attn_weight = attn_weight + attn_bias
if key_padding_mask is not None:
if attn_bias is not None:
warnings.warn('Propogating key_padding_mask to the attention module ' + 'and applying it within the attention module can cause ' + 'unneccessary computation/memory usage. Consider integrating ' + 'into attn_bias once and passing that to each attention ' + 'module instead.')
attn_weight = attn_weight.masked_fill(~key_padding_mask.view((b, 1, 1, s_k)), min_val)
if is_causal:
s = max(s_q, s_k)
causal_mask = attn_weight.new_ones(s, s, dtype=torch.float16)
causal_mask = causal_mask.tril()
causal_mask = causal_mask.to(torch.bool)
causal_mask = ~causal_mask
causal_mask = causal_mask[-s_q:, -s_k:]
attn_weight = attn_weight.masked_fill(causal_mask.view(1, 1, s_q, s_k), min_val)
attn_weight = torch.softmax(attn_weight, dim=-1)
if dropout_p:
attn_weight = torch.nn.functional.dropout(attn_weight, p=dropout_p, training=training, inplace=True)
out = attn_weight.matmul(v)
out = rearrange(out, 'b h s d -> b s (h d)')
if needs_weights:
return (out, attn_weight)
return (out, None) | null |
3,014 | import math
import warnings
from typing import Optional
import torch
import torch.nn as nn
from einops import rearrange
from torch import nn
from .norm import LPLayerNorm
def _reset_is_causal(num_query_tokens: int, num_key_tokens: int, original_is_causal: bool):
if original_is_causal and num_query_tokens != num_key_tokens:
if num_query_tokens != 1:
raise NotImplementedError('MPT does not support query and key with different number of tokens, unless number of query tokens is 1.')
else:
return False
return original_is_causal
def check_valid_inputs(*tensors, valid_dtypes=[torch.float16, torch.bfloat16]):
for tensor in tensors:
if tensor.dtype not in valid_dtypes:
raise TypeError(f'tensor.dtype={tensor.dtype!r} must be in valid_dtypes={valid_dtypes!r}.')
if not tensor.is_cuda:
raise TypeError(f'Inputs must be cuda tensors (tensor.is_cuda={tensor.is_cuda!r}).')
def flash_attn_fn(query, key, value, n_heads, softmax_scale=None, attn_bias=None, key_padding_mask=None, is_causal=False, dropout_p=0.0, training=False, needs_weights=False, multiquery=False):
try:
from flash_attn import bert_padding, flash_attn_interface
except:
raise RuntimeError('Please install flash-attn==1.0.3.post0')
check_valid_inputs(query, key, value)
if attn_bias is not None:
raise NotImplementedError(f'attn_bias not implemented for flash attn.')
(batch_size, seqlen) = query.shape[:2]
if key_padding_mask is None:
key_padding_mask = torch.ones_like(key[:, :, 0], dtype=torch.bool)
query_padding_mask = key_padding_mask[:, -query.size(1):]
(query_unpad, indices_q, cu_seqlens_q, max_seqlen_q) = bert_padding.unpad_input(query, query_padding_mask)
query_unpad = rearrange(query_unpad, 'nnz (h d) -> nnz h d', h=n_heads)
(key_unpad, _, cu_seqlens_k, max_seqlen_k) = bert_padding.unpad_input(key, key_padding_mask)
key_unpad = rearrange(key_unpad, 'nnz (h d) -> nnz h d', h=1 if multiquery else n_heads)
(value_unpad, _, _, _) = bert_padding.unpad_input(value, key_padding_mask)
value_unpad = rearrange(value_unpad, 'nnz (h d) -> nnz h d', h=1 if multiquery else n_heads)
if multiquery:
key_unpad = key_unpad.expand(key_unpad.size(0), n_heads, key_unpad.size(-1))
value_unpad = value_unpad.expand(value_unpad.size(0), n_heads, value_unpad.size(-1))
dropout_p = dropout_p if training else 0.0
reset_is_causal = _reset_is_causal(query.size(1), key.size(1), is_causal)
output_unpad = flash_attn_interface.flash_attn_unpadded_func(query_unpad, key_unpad, value_unpad, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k, dropout_p, softmax_scale=softmax_scale, causal=reset_is_causal, return_attn_probs=needs_weights)
output = bert_padding.pad_input(rearrange(output_unpad, 'nnz h d -> nnz (h d)'), indices_q, batch_size, seqlen)
return (output, None) | null |
3,015 | import math
import warnings
from typing import Optional
import torch
import torch.nn as nn
from einops import rearrange
from torch import nn
from .norm import LPLayerNorm
def _reset_is_causal(num_query_tokens: int, num_key_tokens: int, original_is_causal: bool):
if original_is_causal and num_query_tokens != num_key_tokens:
if num_query_tokens != 1:
raise NotImplementedError('MPT does not support query and key with different number of tokens, unless number of query tokens is 1.')
else:
return False
return original_is_causal
def check_valid_inputs(*tensors, valid_dtypes=[torch.float16, torch.bfloat16]):
for tensor in tensors:
if tensor.dtype not in valid_dtypes:
raise TypeError(f'tensor.dtype={tensor.dtype!r} must be in valid_dtypes={valid_dtypes!r}.')
if not tensor.is_cuda:
raise TypeError(f'Inputs must be cuda tensors (tensor.is_cuda={tensor.is_cuda!r}).')
def triton_flash_attn_fn(query, key, value, n_heads, softmax_scale=None, attn_bias=None, key_padding_mask=None, is_causal=False, dropout_p=0.0, training=False, needs_weights=False, multiquery=False):
try:
from flash_attn import flash_attn_triton
except:
raise RuntimeError('Please install flash-attn==1.0.3.post0 and triton==2.0.0.dev20221202')
check_valid_inputs(query, key, value)
if dropout_p:
raise NotImplementedError(f'Dropout not implemented for attn_impl: triton.')
if needs_weights:
raise NotImplementedError(f'attn_impl: triton cannot return attn weights.')
if key_padding_mask is not None:
warnings.warn('Propagating key_padding_mask to the attention module ' + 'and applying it within the attention module can cause ' + 'unnecessary computation/memory usage. Consider integrating ' + 'into attn_bias once and passing that to each attention ' + 'module instead.')
(b_size, s_k) = key_padding_mask.shape[:2]
if attn_bias is None:
attn_bias = query.new_zeros(b_size, 1, 1, s_k)
attn_bias = attn_bias.masked_fill(~key_padding_mask.view((b_size, 1, 1, s_k)), torch.finfo(query.dtype).min)
query = rearrange(query, 'b s (h d) -> b s h d', h=n_heads)
key = rearrange(key, 'b s (h d) -> b s h d', h=1 if multiquery else n_heads)
value = rearrange(value, 'b s (h d) -> b s h d', h=1 if multiquery else n_heads)
if multiquery:
key = key.expand(*key.shape[:2], n_heads, key.size(-1))
value = value.expand(*value.shape[:2], n_heads, value.size(-1))
reset_is_causal = _reset_is_causal(query.size(1), key.size(1), is_causal)
attn_output = flash_attn_triton.flash_attn_func(query, key, value, attn_bias, reset_is_causal, softmax_scale)
output = attn_output.view(*attn_output.shape[:2], -1)
return (output, None) | null |
3,016 | import math
import warnings
from typing import Optional
import torch
import torch.nn as nn
from einops import rearrange
from torch import nn
from .norm import LPLayerNorm
def attn_bias_shape(attn_impl, n_heads, seq_len, alibi, prefix_lm, causal, use_sequence_id):
if attn_impl == 'flash':
return None
elif attn_impl in ['torch', 'triton']:
if alibi:
if (prefix_lm or not causal) or use_sequence_id:
return (1, n_heads, seq_len, seq_len)
return (1, n_heads, 1, seq_len)
elif prefix_lm or use_sequence_id:
return (1, 1, seq_len, seq_len)
return None
else:
raise ValueError(f'attn_impl={attn_impl!r} is an invalid setting.') | null |
3,017 | import math
import warnings
from typing import Optional
import torch
import torch.nn as nn
from einops import rearrange
from torch import nn
from .norm import LPLayerNorm
def build_alibi_bias(n_heads, seq_len, full=False, alibi_bias_max=8, device=None, dtype=None):
def build_attn_bias(attn_impl, attn_bias, n_heads, seq_len, causal=False, alibi=False, alibi_bias_max=8):
if attn_impl == 'flash':
return None
elif attn_impl in ['torch', 'triton']:
if alibi:
(device, dtype) = (attn_bias.device, attn_bias.dtype)
attn_bias = attn_bias.add(build_alibi_bias(n_heads, seq_len, full=not causal, alibi_bias_max=alibi_bias_max, device=device, dtype=dtype))
return attn_bias
else:
raise ValueError(f'attn_impl={attn_impl!r} is an invalid setting.') | null |
3,018 | import torch
def _cast_if_autocast_enabled(tensor):
if torch.is_autocast_enabled():
if tensor.device.type == 'cuda':
dtype = torch.get_autocast_gpu_dtype()
elif tensor.device.type == 'cpu':
dtype = torch.get_autocast_cpu_dtype()
else:
raise NotImplementedError()
return tensor.to(dtype=dtype)
return tensor | null |
3,019 | import torch
def rms_norm(x, weight=None, eps=1e-05):
output = x / torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps)
if weight is not None:
return output * weight
return output | null |
3,020 | from contextlib import contextmanager
import torch
import torch.nn as nn
def init_on_device(device: torch.device, include_buffers: bool=False):
"""Device initialization context manager.
A context manager under which models are initialized with all parameters
on the specified device.
Args:
device (`torch.device`): Device to initialize all parameters on.
include_buffers (`bool`, *optional*, defaults to `False`): Whether or
not to also put all buffers on the meta device while initializing.
Example:
```python
import torch.nn as nn
with init_on_device(device=torch.device("cuda")):
tst = nn.Liner(100, 100) # on `cuda` device
```
"""
old_register_parameter = nn.Module.register_parameter
if include_buffers:
old_register_buffer = nn.Module.register_buffer
def register_empty_parameter(module, name, param):
old_register_parameter(module, name, param)
if param is not None:
param_cls = type(module._parameters[name])
kwargs = module._parameters[name].__dict__
module._parameters[name] = param_cls(module._parameters[name].to(device), **kwargs)
def register_empty_buffer(module, name, buffer):
old_register_buffer(module, name, buffer)
if buffer is not None:
module._buffers[name] = module._buffers[name].to(device)
if include_buffers:
tensor_constructors_to_patch = {torch_function_name: getattr(torch, torch_function_name) for torch_function_name in ['empty', 'zeros', 'ones', 'full']}
else:
tensor_constructors_to_patch = {}
def patch_tensor_constructor(fn):
def wrapper(*args, **kwargs):
kwargs['device'] = device
return fn(*args, **kwargs)
return wrapper
try:
nn.Module.register_parameter = register_empty_parameter
if include_buffers:
nn.Module.register_buffer = register_empty_buffer
for torch_function_name in tensor_constructors_to_patch.keys():
setattr(torch, torch_function_name, patch_tensor_constructor(getattr(torch, torch_function_name)))
yield
finally:
nn.Module.register_parameter = old_register_parameter
if include_buffers:
nn.Module.register_buffer = old_register_buffer
for (torch_function_name, old_torch_function) in tensor_constructors_to_patch.items():
setattr(torch, torch_function_name, old_torch_function)
The provided code snippet includes necessary dependencies for implementing the `init_empty_weights` function. Write a Python function `def init_empty_weights(include_buffers: bool=False)` to solve the following problem:
Meta initialization context manager. A context manager under which models are initialized with all parameters on the meta device, therefore creating an empty model. Useful when just initializing the model would blow the available RAM. Args: include_buffers (`bool`, *optional*, defaults to `False`): Whether or not to also put all buffers on the meta device while initializing. Example: ```python import torch.nn as nn # Initialize a model with 100 billions parameters in no time and without using any RAM. with init_empty_weights(): tst = nn.Sequential(*[nn.Linear(10000, 10000) for _ in range(1000)]) ``` <Tip warning={true}> Any model created under this context manager has no weights. As such you can't do something like `model.to(some_device)` with it. To load weights inside your empty model, see [`load_checkpoint_and_dispatch`]. </Tip>
Here is the function:
def init_empty_weights(include_buffers: bool=False):
"""Meta initialization context manager.
A context manager under which models are initialized with all parameters
on the meta device, therefore creating an empty model. Useful when just
initializing the model would blow the available RAM.
Args:
include_buffers (`bool`, *optional*, defaults to `False`): Whether or
not to also put all buffers on the meta device while initializing.
Example:
```python
import torch.nn as nn
# Initialize a model with 100 billions parameters in no time and without using any RAM.
with init_empty_weights():
tst = nn.Sequential(*[nn.Linear(10000, 10000) for _ in range(1000)])
```
<Tip warning={true}>
Any model created under this context manager has no weights. As such you can't do something like
`model.to(some_device)` with it. To load weights inside your empty model, see [`load_checkpoint_and_dispatch`].
</Tip>
"""
with init_on_device(torch.device('meta'), include_buffers=include_buffers) as f:
yield f | Meta initialization context manager. A context manager under which models are initialized with all parameters on the meta device, therefore creating an empty model. Useful when just initializing the model would blow the available RAM. Args: include_buffers (`bool`, *optional*, defaults to `False`): Whether or not to also put all buffers on the meta device while initializing. Example: ```python import torch.nn as nn # Initialize a model with 100 billions parameters in no time and without using any RAM. with init_empty_weights(): tst = nn.Sequential(*[nn.Linear(10000, 10000) for _ in range(1000)]) ``` <Tip warning={true}> Any model created under this context manager has no weights. As such you can't do something like `model.to(some_device)` with it. To load weights inside your empty model, see [`load_checkpoint_and_dispatch`]. </Tip> |
3,021 | import math
import warnings
from collections.abc import Sequence
from functools import partial
from typing import Optional, Tuple, Union
import torch
from torch import nn
from .norm import NORM_CLASS_REGISTRY
def torch_default_param_init_fn_(module: nn.Module, verbose: int=0, **kwargs):
del kwargs
if verbose > 1:
warnings.warn(f"Initializing network using module's reset_parameters attribute")
if hasattr(module, 'reset_parameters'):
module.reset_parameters() | null |
3,022 | import math
import warnings
from collections.abc import Sequence
from functools import partial
from typing import Optional, Tuple, Union
import torch
from torch import nn
from .norm import NORM_CLASS_REGISTRY
def _normal_param_init_fn_(module: nn.Module, std: float, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
del kwargs
init_fn_ = _normal_init_(std=std)
if verbose > 1:
warnings.warn(f'Using torch.nn.init.normal_ init fn mean=0.0, std={std}')
generic_param_init_fn_(module=module, init_fn_=init_fn_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
def baseline_param_init_fn_(module: nn.Module, init_std: float, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
del kwargs
if init_std is None:
raise ValueError("You must set model.init_config['init_std'] to a float value to use the default initialization scheme.")
_normal_param_init_fn_(module=module, std=init_std, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose) | null |
3,023 | import math
import warnings
from collections.abc import Sequence
from functools import partial
from typing import Optional, Tuple, Union
import torch
from torch import nn
from .norm import NORM_CLASS_REGISTRY
def small_param_init_fn_(module: nn.Module, n_layers: int, d_model: int, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
del kwargs
std = math.sqrt(2 / (5 * d_model))
_normal_param_init_fn_(module=module, std=std, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
The provided code snippet includes necessary dependencies for implementing the `neox_param_init_fn_` function. Write a Python function `def neox_param_init_fn_(module: nn.Module, n_layers: int, d_model: int, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs)` to solve the following problem:
From section 2.3.1 of GPT-NeoX-20B: An Open-Source AutoregressiveLanguage Model — Black et. al. (2022) see https://github.com/EleutherAI/gpt-neox/blob/9610391ab319403cef079b438edd016a2443af54/megatron/model/init_functions.py#L151 and https://github.com/EleutherAI/gpt-neox/blob/main/megatron/model/transformer.py
Here is the function:
def neox_param_init_fn_(module: nn.Module, n_layers: int, d_model: int, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
"""From section 2.3.1 of GPT-NeoX-20B:
An Open-Source AutoregressiveLanguage Model — Black et. al. (2022)
see https://github.com/EleutherAI/gpt-neox/blob/9610391ab319403cef079b438edd016a2443af54/megatron/model/init_functions.py#L151
and https://github.com/EleutherAI/gpt-neox/blob/main/megatron/model/transformer.py
"""
del kwargs
residual_div = n_layers / math.sqrt(10)
if verbose > 1:
warnings.warn(f'setting init_div_is_residual to {residual_div}')
small_param_init_fn_(module=module, d_model=d_model, n_layers=n_layers, init_div_is_residual=residual_div, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose) | From section 2.3.1 of GPT-NeoX-20B: An Open-Source AutoregressiveLanguage Model — Black et. al. (2022) see https://github.com/EleutherAI/gpt-neox/blob/9610391ab319403cef079b438edd016a2443af54/megatron/model/init_functions.py#L151 and https://github.com/EleutherAI/gpt-neox/blob/main/megatron/model/transformer.py |
3,024 | import math
import warnings
from collections.abc import Sequence
from functools import partial
from typing import Optional, Tuple, Union
import torch
from torch import nn
from .norm import NORM_CLASS_REGISTRY
def generic_param_init_fn_(module: nn.Module, init_fn_, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
def kaiming_uniform_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, init_gain: float=0, fan_mode: str='fan_in', init_nonlinearity: str='leaky_relu', verbose: int=0, **kwargs):
del kwargs
if verbose > 1:
warnings.warn(f'Using nn.init.kaiming_uniform_ init fn with parameters: ' + f'a={init_gain}, mode={fan_mode}, nonlinearity={init_nonlinearity}')
kaiming_uniform_ = partial(nn.init.kaiming_uniform_, a=init_gain, mode=fan_mode, nonlinearity=init_nonlinearity)
generic_param_init_fn_(module=module, init_fn_=kaiming_uniform_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose) | null |
3,025 | import math
import warnings
from collections.abc import Sequence
from functools import partial
from typing import Optional, Tuple, Union
import torch
from torch import nn
from .norm import NORM_CLASS_REGISTRY
def generic_param_init_fn_(module: nn.Module, init_fn_, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
del kwargs
if verbose > 1:
warnings.warn(f'If model has bias parameters they are initialized to 0.')
init_div_is_residual = init_div_is_residual
if init_div_is_residual is False:
div_is_residual = 1.0
elif init_div_is_residual is True:
div_is_residual = math.sqrt(2 * n_layers)
elif isinstance(init_div_is_residual, float) or isinstance(init_div_is_residual, int):
div_is_residual = init_div_is_residual
elif isinstance(init_div_is_residual, str) and init_div_is_residual.isnumeric():
div_is_residual = float(init_div_is_residual)
else:
div_is_residual = 1.0
raise ValueError(f'Expected init_div_is_residual to be boolean or numeric, got {init_div_is_residual}')
if init_div_is_residual is not False:
if verbose > 1:
warnings.warn(f'Initializing _is_residual layers then dividing them by {div_is_residual:.3f}. ' + f'Set `init_div_is_residual: false` in init config to disable this.')
if isinstance(module, nn.Linear):
if hasattr(module, '_fused'):
fused_init_helper_(module, init_fn_)
else:
init_fn_(module.weight)
if module.bias is not None:
torch.nn.init.zeros_(module.bias)
if init_div_is_residual is not False and getattr(module, '_is_residual', False):
with torch.no_grad():
module.weight.div_(div_is_residual)
elif isinstance(module, nn.Embedding):
if emb_init_std is not None:
std = emb_init_std
if std == 0:
warnings.warn(f'Embedding layer initialized to 0.')
emb_init_fn_ = partial(torch.nn.init.normal_, mean=0.0, std=std)
if verbose > 1:
warnings.warn(f'Embedding layer initialized using normal distribution with mean=0 and std={std!r}.')
elif emb_init_uniform_lim is not None:
lim = emb_init_uniform_lim
if isinstance(lim, Sequence):
if len(lim) > 2:
raise ValueError(f'Uniform init requires a min and a max limit. User input: {lim}.')
if lim[0] == lim[1]:
warnings.warn(f'Embedding layer initialized to {lim[0]}.')
else:
if lim == 0:
warnings.warn(f'Embedding layer initialized to 0.')
lim = [-lim, lim]
(a, b) = lim
emb_init_fn_ = partial(torch.nn.init.uniform_, a=a, b=b)
if verbose > 1:
warnings.warn(f'Embedding layer initialized using uniform distribution in range {lim}.')
else:
emb_init_fn_ = init_fn_
emb_init_fn_(module.weight)
elif isinstance(module, tuple(set(NORM_CLASS_REGISTRY.values()))):
if verbose > 1:
warnings.warn(f'Norm weights are set to 1. If norm layer has a bias it is initialized to 0.')
if hasattr(module, 'weight') and module.weight is not None:
torch.nn.init.ones_(module.weight)
if hasattr(module, 'bias') and module.bias is not None:
torch.nn.init.zeros_(module.bias)
elif isinstance(module, nn.MultiheadAttention):
if module._qkv_same_embed_dim:
assert module.in_proj_weight is not None
assert module.q_proj_weight is None and module.k_proj_weight is None and (module.v_proj_weight is None)
assert d_model is not None
_d = d_model
splits = (0, _d, 2 * _d, 3 * _d)
for (s, e) in zip(splits[:-1], splits[1:]):
init_fn_(module.in_proj_weight[s:e])
else:
assert module.q_proj_weight is not None and module.k_proj_weight is not None and (module.v_proj_weight is not None)
assert module.in_proj_weight is None
init_fn_(module.q_proj_weight)
init_fn_(module.k_proj_weight)
init_fn_(module.v_proj_weight)
if module.in_proj_bias is not None:
torch.nn.init.zeros_(module.in_proj_bias)
if module.bias_k is not None:
torch.nn.init.zeros_(module.bias_k)
if module.bias_v is not None:
torch.nn.init.zeros_(module.bias_v)
init_fn_(module.out_proj.weight)
if init_div_is_residual is not False and getattr(module.out_proj, '_is_residual', False):
with torch.no_grad():
module.out_proj.weight.div_(div_is_residual)
if module.out_proj.bias is not None:
torch.nn.init.zeros_(module.out_proj.bias)
else:
for _ in module.parameters(recurse=False):
raise NotImplementedError(f'{module.__class__.__name__} parameters are not initialized by param_init_fn.')
def kaiming_normal_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, init_gain: float=0, fan_mode: str='fan_in', init_nonlinearity: str='leaky_relu', verbose: int=0, **kwargs):
del kwargs
if verbose > 1:
warnings.warn(f'Using nn.init.kaiming_normal_ init fn with parameters: ' + f'a={init_gain}, mode={fan_mode}, nonlinearity={init_nonlinearity}')
kaiming_normal_ = partial(torch.nn.init.kaiming_normal_, a=init_gain, mode=fan_mode, nonlinearity=init_nonlinearity)
generic_param_init_fn_(module=module, init_fn_=kaiming_normal_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose) | null |
3,026 | import math
import warnings
from collections.abc import Sequence
from functools import partial
from typing import Optional, Tuple, Union
import torch
from torch import nn
from .norm import NORM_CLASS_REGISTRY
def generic_param_init_fn_(module: nn.Module, init_fn_, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
def xavier_uniform_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, init_gain: float=0, verbose: int=0, **kwargs):
del kwargs
xavier_uniform_ = partial(torch.nn.init.xavier_uniform_, gain=init_gain)
if verbose > 1:
warnings.warn(f'Using torch.nn.init.xavier_uniform_ init fn with parameters: ' + f'gain={init_gain}')
generic_param_init_fn_(module=module, init_fn_=xavier_uniform_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose) | null |
3,027 | import math
import warnings
from collections.abc import Sequence
from functools import partial
from typing import Optional, Tuple, Union
import torch
from torch import nn
from .norm import NORM_CLASS_REGISTRY
def generic_param_init_fn_(module: nn.Module, init_fn_, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
del kwargs
if verbose > 1:
warnings.warn(f'If model has bias parameters they are initialized to 0.')
init_div_is_residual = init_div_is_residual
if init_div_is_residual is False:
div_is_residual = 1.0
elif init_div_is_residual is True:
div_is_residual = math.sqrt(2 * n_layers)
elif isinstance(init_div_is_residual, float) or isinstance(init_div_is_residual, int):
div_is_residual = init_div_is_residual
elif isinstance(init_div_is_residual, str) and init_div_is_residual.isnumeric():
div_is_residual = float(init_div_is_residual)
else:
div_is_residual = 1.0
raise ValueError(f'Expected init_div_is_residual to be boolean or numeric, got {init_div_is_residual}')
if init_div_is_residual is not False:
if verbose > 1:
warnings.warn(f'Initializing _is_residual layers then dividing them by {div_is_residual:.3f}. ' + f'Set `init_div_is_residual: false` in init config to disable this.')
if isinstance(module, nn.Linear):
if hasattr(module, '_fused'):
fused_init_helper_(module, init_fn_)
else:
init_fn_(module.weight)
if module.bias is not None:
torch.nn.init.zeros_(module.bias)
if init_div_is_residual is not False and getattr(module, '_is_residual', False):
with torch.no_grad():
module.weight.div_(div_is_residual)
elif isinstance(module, nn.Embedding):
if emb_init_std is not None:
std = emb_init_std
if std == 0:
warnings.warn(f'Embedding layer initialized to 0.')
emb_init_fn_ = partial(torch.nn.init.normal_, mean=0.0, std=std)
if verbose > 1:
warnings.warn(f'Embedding layer initialized using normal distribution with mean=0 and std={std!r}.')
elif emb_init_uniform_lim is not None:
lim = emb_init_uniform_lim
if isinstance(lim, Sequence):
if len(lim) > 2:
raise ValueError(f'Uniform init requires a min and a max limit. User input: {lim}.')
if lim[0] == lim[1]:
warnings.warn(f'Embedding layer initialized to {lim[0]}.')
else:
if lim == 0:
warnings.warn(f'Embedding layer initialized to 0.')
lim = [-lim, lim]
(a, b) = lim
emb_init_fn_ = partial(torch.nn.init.uniform_, a=a, b=b)
if verbose > 1:
warnings.warn(f'Embedding layer initialized using uniform distribution in range {lim}.')
else:
emb_init_fn_ = init_fn_
emb_init_fn_(module.weight)
elif isinstance(module, tuple(set(NORM_CLASS_REGISTRY.values()))):
if verbose > 1:
warnings.warn(f'Norm weights are set to 1. If norm layer has a bias it is initialized to 0.')
if hasattr(module, 'weight') and module.weight is not None:
torch.nn.init.ones_(module.weight)
if hasattr(module, 'bias') and module.bias is not None:
torch.nn.init.zeros_(module.bias)
elif isinstance(module, nn.MultiheadAttention):
if module._qkv_same_embed_dim:
assert module.in_proj_weight is not None
assert module.q_proj_weight is None and module.k_proj_weight is None and (module.v_proj_weight is None)
assert d_model is not None
_d = d_model
splits = (0, _d, 2 * _d, 3 * _d)
for (s, e) in zip(splits[:-1], splits[1:]):
init_fn_(module.in_proj_weight[s:e])
else:
assert module.q_proj_weight is not None and module.k_proj_weight is not None and (module.v_proj_weight is not None)
assert module.in_proj_weight is None
init_fn_(module.q_proj_weight)
init_fn_(module.k_proj_weight)
init_fn_(module.v_proj_weight)
if module.in_proj_bias is not None:
torch.nn.init.zeros_(module.in_proj_bias)
if module.bias_k is not None:
torch.nn.init.zeros_(module.bias_k)
if module.bias_v is not None:
torch.nn.init.zeros_(module.bias_v)
init_fn_(module.out_proj.weight)
if init_div_is_residual is not False and getattr(module.out_proj, '_is_residual', False):
with torch.no_grad():
module.out_proj.weight.div_(div_is_residual)
if module.out_proj.bias is not None:
torch.nn.init.zeros_(module.out_proj.bias)
else:
for _ in module.parameters(recurse=False):
raise NotImplementedError(f'{module.__class__.__name__} parameters are not initialized by param_init_fn.')
def xavier_normal_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, init_gain: float=0, verbose: int=0, **kwargs):
xavier_normal_ = partial(torch.nn.init.xavier_normal_, gain=init_gain)
if verbose > 1:
warnings.warn(f'Using torch.nn.init.xavier_normal_ init fn with parameters: ' + f'gain={init_gain}')
generic_param_init_fn_(module=module, init_fn_=xavier_normal_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose) | null |
3,028 | import math
import warnings
from types import MethodType
from typing import Any, Dict, List, Optional, Tuple, Union
import torch
from transformers.models.bloom.modeling_bloom import BaseModelOutputWithPastAndCrossAttentions, BloomForCausalLM, BloomModel, CausalLMOutputWithCrossAttentions, CrossEntropyLoss
from transformers.models.bloom.modeling_bloom import _expand_mask as _expand_mask_bloom
from transformers.models.bloom.modeling_bloom import _make_causal_mask as _make_causal_mask_bloom
from transformers.models.bloom.modeling_bloom import logging
from transformers.models.gpt2.modeling_gpt2 import GPT2LMHeadModel
from transformers.models.gpt_neo.modeling_gpt_neo import GPTNeoForCausalLM
from transformers.models.gpt_neox.modeling_gpt_neox import GPTNeoXForCausalLM
from transformers.models.gptj.modeling_gptj import GPTJForCausalLM
from transformers.models.opt.modeling_opt import OPTForCausalLM
from transformers.models.opt.modeling_opt import _expand_mask as _expand_mask_opt
from transformers.models.opt.modeling_opt import _make_causal_mask as _make_causal_mask_opt
_SUPPORTED_GPT_MODELS = (GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM)
def _convert_gpt_causal_lm_to_prefix_lm(model: CAUSAL_GPT_TYPES) -> CAUSAL_GPT_TYPES:
"""Converts a GPT-style Causal LM to a Prefix LM.
Supported HuggingFace model classes:
- `GPT2LMHeadModel`
- `GPTNeoForCausalLM`
- `GPTNeoXForCausalLM`
- `GPTJForCausalLM`
See `convert_hf_causal_lm_to_prefix_lm` for more details.
"""
if hasattr(model, '_prefix_lm_converted'):
return model
assert isinstance(model, _SUPPORTED_GPT_MODELS)
assert model.config.add_cross_attention == False, 'Only supports GPT-style decoder-only models'
def _get_attn_modules(model: CAUSAL_GPT_TYPES) -> List[torch.nn.Module]:
"""Helper that gets a list of the model's attention modules.
Each module has a `bias` buffer used for causal masking. The Prefix LM
conversion adds logic to dynamically manipulate these biases to support
Prefix LM attention masking.
"""
attn_modules = []
if isinstance(model, GPTNeoXForCausalLM):
blocks = model.gpt_neox.layers
else:
blocks = model.transformer.h
for block in blocks:
if isinstance(model, GPTNeoForCausalLM):
if block.attn.attention_type != 'global':
continue
attn_module = block.attn.attention
elif isinstance(model, GPTNeoXForCausalLM):
attn_module = block.attention
else:
attn_module = block.attn
attn_modules.append(attn_module)
return attn_modules
setattr(model, '_original_forward', getattr(model, 'forward'))
setattr(model, '_original_generate', getattr(model, 'generate'))
def forward(self: CAUSAL_GPT_TYPES, input_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[Tuple[Tuple[torch.Tensor]]]=None, attention_mask: Optional[torch.FloatTensor]=None, bidirectional_mask: Optional[torch.Tensor]=None, token_type_ids: Optional[torch.LongTensor]=None, position_ids: Optional[torch.LongTensor]=None, head_mask: Optional[torch.FloatTensor]=None, inputs_embeds: Optional[torch.FloatTensor]=None, labels: Optional[torch.LongTensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None):
"""Wraps original forward to enable PrefixLM attention."""
def call_og_forward():
if isinstance(self, GPTNeoXForCausalLM):
return self._original_forward(input_ids=input_ids, past_key_values=past_key_values, attention_mask=attention_mask, head_mask=head_mask, inputs_embeds=inputs_embeds, labels=labels, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
else:
return self._original_forward(input_ids=input_ids, past_key_values=past_key_values, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, labels=labels, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
if bidirectional_mask is None:
return call_og_forward()
assert isinstance(bidirectional_mask, torch.Tensor)
attn_modules = _get_attn_modules(model)
(b, s) = bidirectional_mask.shape
max_length = attn_modules[0].bias.shape[-1]
if s > max_length:
raise ValueError(f'bidirectional_mask sequence length (={s}) exceeds the ' + f'max length allowed by the model ({max_length}).')
assert s <= max_length
if s < max_length:
pad = torch.zeros((int(b), int(max_length - s)), dtype=bidirectional_mask.dtype, device=bidirectional_mask.device)
bidirectional_mask = torch.cat([bidirectional_mask, pad], dim=1)
bidirectional = bidirectional_mask.unsqueeze(1).unsqueeze(1)
for attn_module in attn_modules:
attn_module.bias.data = torch.logical_or(attn_module.bias.data, bidirectional)
output = call_og_forward()
for attn_module in attn_modules:
attn_module.bias.data = torch.tril(attn_module.bias.data[0, 0])[None, None]
return output
def generate(self: CAUSAL_GPT_TYPES, *args: tuple, **kwargs: Dict[str, Any]):
"""Wraps original generate to enable PrefixLM attention."""
attn_modules = _get_attn_modules(model)
for attn_module in attn_modules:
attn_module.bias.data[:] = 1
output = self._original_generate(*args, **kwargs)
for attn_module in attn_modules:
attn_module.bias.data = torch.tril(attn_module.bias.data[0, 0])[None, None]
return output
setattr(model, 'forward', MethodType(forward, model))
setattr(model, 'generate', MethodType(generate, model))
setattr(model, '_prefix_lm_converted', True)
return model
def _convert_bloom_causal_lm_to_prefix_lm(model: BloomForCausalLM) -> BloomForCausalLM:
"""Converts a BLOOM Causal LM to a Prefix LM.
Supported HuggingFace model classes:
- `BloomForCausalLM`
See `convert_hf_causal_lm_to_prefix_lm` for more details.
"""
if hasattr(model, '_prefix_lm_converted'):
return model
assert isinstance(model, BloomForCausalLM)
assert model.config.add_cross_attention == False, 'Only supports BLOOM decoder-only models'
def _prepare_attn_mask(self: BloomModel, attention_mask: torch.Tensor, bidirectional_mask: Optional[torch.Tensor], input_shape: Tuple[int, int], past_key_values_length: int) -> torch.BoolTensor:
combined_attention_mask = None
device = attention_mask.device
(_, src_length) = input_shape
if src_length > 1:
combined_attention_mask = _make_causal_mask_bloom(input_shape, device=device, past_key_values_length=past_key_values_length)
if bidirectional_mask is not None:
assert attention_mask.shape == bidirectional_mask.shape
expanded_bidirectional_mask = _expand_mask_bloom(bidirectional_mask, tgt_length=src_length)
combined_attention_mask = torch.logical_and(combined_attention_mask, expanded_bidirectional_mask)
expanded_attn_mask = _expand_mask_bloom(attention_mask, tgt_length=src_length)
combined_attention_mask = expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask | combined_attention_mask
return combined_attention_mask
def _build_alibi_tensor(self: BloomModel, batch_size: int, query_length: int, key_length: int, dtype: torch.dtype, device: torch.device) -> torch.Tensor:
num_heads = self.config.n_head
closest_power_of_2 = 2 ** math.floor(math.log2(num_heads))
base = torch.tensor(2 ** (-2 ** (-(math.log2(closest_power_of_2) - 3))), device=device, dtype=torch.float32)
powers = torch.arange(1, 1 + closest_power_of_2, device=device, dtype=torch.int32)
slopes = torch.pow(base, powers)
if closest_power_of_2 != num_heads:
extra_base = torch.tensor(2 ** (-2 ** (-(math.log2(2 * closest_power_of_2) - 3))), device=device, dtype=torch.float32)
num_remaining_heads = min(closest_power_of_2, num_heads - closest_power_of_2)
extra_powers = torch.arange(1, 1 + 2 * num_remaining_heads, 2, device=device, dtype=torch.int32)
slopes = torch.cat([slopes, torch.pow(extra_base, extra_powers)], dim=0)
qa = torch.arange(query_length, device=device, dtype=torch.int32).view(-1, 1)
ka = torch.arange(key_length, device=device, dtype=torch.int32).view(1, -1)
diffs = qa - ka + key_length - query_length
diffs = -diffs.abs()
alibi = slopes.view(1, num_heads, 1, 1) * diffs.view(1, 1, query_length, key_length)
alibi = alibi.expand(batch_size, -1, -1, -1).reshape(-1, query_length, key_length)
return alibi.to(dtype)
KeyValueT = Tuple[torch.Tensor, torch.Tensor]
def forward(self: BloomModel, input_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[Tuple[KeyValueT, ...]]=None, attention_mask: Optional[torch.Tensor]=None, bidirectional_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.LongTensor]=None, inputs_embeds: Optional[torch.LongTensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, **deprecated_arguments) -> Union[Tuple[torch.Tensor, ...], BaseModelOutputWithPastAndCrossAttentions]:
if deprecated_arguments.pop('position_ids', False) is not False:
warnings.warn('`position_ids` have no functionality in BLOOM and will be removed in v5.0.0. ' + 'You can safely ignore passing `position_ids`.', FutureWarning)
if len(deprecated_arguments) > 0:
raise ValueError(f'Got unexpected arguments: {deprecated_arguments}')
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
use_cache = use_cache if use_cache is not None else self.config.use_cache
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if input_ids is not None and inputs_embeds is not None:
raise ValueError('You cannot specify both input_ids and inputs_embeds at the same time')
elif input_ids is not None:
(batch_size, seq_length) = input_ids.shape
elif inputs_embeds is not None:
(batch_size, seq_length, _) = inputs_embeds.shape
else:
raise ValueError('You have to specify either input_ids or inputs_embeds')
if past_key_values is None:
past_key_values = tuple([None] * len(self.h))
head_mask = self.get_head_mask(head_mask, self.config.n_layer)
if inputs_embeds is None:
inputs_embeds = self.word_embeddings(input_ids)
hidden_states = self.word_embeddings_layernorm(inputs_embeds)
presents = () if use_cache else None
all_self_attentions = () if output_attentions else None
all_hidden_states = () if output_hidden_states else None
seq_length_with_past = seq_length
past_key_values_length = 0
if past_key_values[0] is not None:
tmp = past_key_values[0][0]
past_key_values_length = tmp.shape[2]
seq_length_with_past = seq_length_with_past + past_key_values_length
if attention_mask is None:
attention_mask = torch.ones((batch_size, seq_length_with_past), device=hidden_states.device)
else:
attention_mask = attention_mask.to(hidden_states.device)
alibi = self._build_alibi_tensor(batch_size=batch_size, query_length=seq_length, key_length=seq_length_with_past, dtype=hidden_states.dtype, device=hidden_states.device)
causal_mask = self._prepare_attn_mask(attention_mask, bidirectional_mask, input_shape=(batch_size, seq_length), past_key_values_length=past_key_values_length)
for (i, (block, layer_past)) in enumerate(zip(self.h, past_key_values)):
if output_hidden_states:
hst = (hidden_states,)
all_hidden_states = all_hidden_states + hst
if self.gradient_checkpointing and self.training:
if use_cache:
logger.warning('`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...')
use_cache = False
def create_custom_forward(module):
def custom_forward(*inputs):
return module(*inputs, use_cache=use_cache, output_attentions=output_attentions)
return custom_forward
outputs = torch.utils.checkpoint.checkpoint(create_custom_forward(block), hidden_states, alibi, causal_mask, head_mask[i])
else:
outputs = block(hidden_states, layer_past=layer_past, attention_mask=causal_mask, head_mask=head_mask[i], use_cache=use_cache, output_attentions=output_attentions, alibi=alibi)
hidden_states = outputs[0]
if use_cache is True:
presents = presents + (outputs[1],)
if output_attentions:
oa = (outputs[2 if use_cache else 1],)
all_self_attentions = all_self_attentions + oa
hidden_states = self.ln_f(hidden_states)
if output_hidden_states:
hst = (hidden_states,)
all_hidden_states = all_hidden_states + hst
if not return_dict:
return tuple((v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None))
return BaseModelOutputWithPastAndCrossAttentions(last_hidden_state=hidden_states, past_key_values=presents, hidden_states=all_hidden_states, attentions=all_self_attentions)
setattr(model.transformer, '_prepare_attn_mask', MethodType(_prepare_attn_mask, model.transformer))
setattr(model.transformer, '_build_alibi_tensor', MethodType(_build_alibi_tensor, model.transformer))
setattr(model.transformer, 'forward', MethodType(forward, model.transformer))
KeyValueT = Tuple[torch.Tensor, torch.Tensor]
def forward(self: BloomForCausalLM, input_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[Tuple[KeyValueT, ...]]=None, attention_mask: Optional[torch.Tensor]=None, bidirectional_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.Tensor]=None, inputs_embeds: Optional[torch.Tensor]=None, labels: Optional[torch.Tensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, **deprecated_arguments) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
"""Replacement forward method for BloomCausalLM."""
if deprecated_arguments.pop('position_ids', False) is not False:
warnings.warn('`position_ids` have no functionality in BLOOM and will be removed ' + 'in v5.0.0. You can safely ignore passing `position_ids`.', FutureWarning)
if len(deprecated_arguments) > 0:
raise ValueError(f'Got unexpected arguments: {deprecated_arguments}')
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
transformer_outputs = self.transformer(input_ids, past_key_values=past_key_values, attention_mask=attention_mask, bidirectional_mask=bidirectional_mask, head_mask=head_mask, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
hidden_states = transformer_outputs[0]
lm_logits = self.lm_head(hidden_states)
loss = None
if labels is not None:
shift_logits = lm_logits[..., :-1, :].contiguous()
shift_labels = labels[..., 1:].contiguous()
(batch_size, seq_length, vocab_size) = shift_logits.shape
loss_fct = CrossEntropyLoss()
loss = loss_fct(shift_logits.view(batch_size * seq_length, vocab_size), shift_labels.view(batch_size * seq_length))
if not return_dict:
output = (lm_logits,) + transformer_outputs[1:]
return (loss,) + output if loss is not None else output
return CausalLMOutputWithCrossAttentions(loss=loss, logits=lm_logits, past_key_values=transformer_outputs.past_key_values, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions)
def prepare_inputs_for_generation(self: BloomForCausalLM, input_ids: torch.LongTensor, past: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, **kwargs) -> dict:
if past:
input_ids = input_ids[:, -1].unsqueeze(-1)
bidirectional_mask = None
if past[0][0].shape[0] == input_ids.shape[0]:
past = self._convert_to_bloom_cache(past)
else:
bidirectional_mask = torch.ones_like(input_ids)
return {'input_ids': input_ids, 'past_key_values': past, 'use_cache': True, 'attention_mask': attention_mask, 'bidirectional_mask': bidirectional_mask}
setattr(model, 'forward', MethodType(forward, model))
setattr(model, 'prepare_inputs_for_generation', MethodType(prepare_inputs_for_generation, model))
setattr(model, '_prefix_lm_converted', True)
return model
def _convert_opt_causal_lm_to_prefix_lm(model: OPTForCausalLM) -> OPTForCausalLM:
"""Converts an OPT Causal LM to a Prefix LM.
Supported HuggingFace model classes:
- `OPTForCausalLM`
See `convert_hf_causal_lm_to_prefix_lm` for more details.
"""
if hasattr(model, '_prefix_lm_converted'):
return model
assert isinstance(model, OPTForCausalLM)
assert model.config.add_cross_attention == False, 'Only supports OPT decoder-only models'
setattr(model, '_original_forward', getattr(model, 'forward'))
setattr(model, '_original_generate', getattr(model, 'generate'))
model.model.decoder.bidirectional_mask = None
def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
combined_attention_mask = None
if input_shape[-1] > 1:
if self.bidirectional_mask == 'g':
(bsz, src_length) = input_shape
combined_attention_mask = torch.zeros((bsz, 1, src_length, src_length + past_key_values_length), dtype=inputs_embeds.dtype, device=inputs_embeds.device)
else:
combined_attention_mask = _make_causal_mask_opt(input_shape, inputs_embeds.dtype, past_key_values_length=past_key_values_length).to(inputs_embeds.device)
if self.bidirectional_mask is not None:
assert attention_mask.shape == self.bidirectional_mask.shape
expanded_bidirectional_mask = _expand_mask_opt(self.bidirectional_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(inputs_embeds.device)
combined_attention_mask = torch.maximum(expanded_bidirectional_mask, combined_attention_mask)
if attention_mask is not None:
expanded_attn_mask = _expand_mask_opt(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(inputs_embeds.device)
combined_attention_mask = expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
return combined_attention_mask
setattr(model.model.decoder, '_prepare_decoder_attention_mask', MethodType(_prepare_decoder_attention_mask, model.model.decoder))
def forward(self: OPTForCausalLM, input_ids: Optional[torch.LongTensor]=None, attention_mask: Optional[torch.Tensor]=None, bidirectional_mask: Optional[torch.ByteTensor]=None, head_mask: Optional[torch.Tensor]=None, past_key_values: Optional[List[torch.FloatTensor]]=None, inputs_embeds: Optional[torch.FloatTensor]=None, labels: Optional[torch.LongTensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None):
def call_og_forward():
return self._original_forward(input_ids=input_ids, attention_mask=attention_mask, head_mask=head_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, labels=labels, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
if bidirectional_mask is None:
return call_og_forward()
self.model.decoder.bidirectional_mask = bidirectional_mask
try:
outputs = call_og_forward()
except:
self.model.decoder.bidirectional_mask = None
raise
self.model.decoder.bidirectional_mask = None
return outputs
def generate(self: OPTForCausalLM, *args: tuple, **kwargs: Dict[str, Any]):
"""Wraps original generate to enable PrefixLM-style attention."""
self.model.decoder.bidirectional_mask = 'g'
try:
output = self._original_generate(*args, **kwargs)
except:
self.model.decoder.bidirectional_mask = None
raise
self.model.decoder.bidirectional_mask = None
return output
setattr(model, 'forward', MethodType(forward, model))
setattr(model, 'generate', MethodType(generate, model))
setattr(model, '_prefix_lm_converted', True)
return model
_SUPPORTED_HF_MODELS = _SUPPORTED_GPT_MODELS + (BloomForCausalLM, OPTForCausalLM)
CAUSAL_LM_TYPES = Union[GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM, BloomForCausalLM, OPTForCausalLM]
The provided code snippet includes necessary dependencies for implementing the `convert_hf_causal_lm_to_prefix_lm` function. Write a Python function `def convert_hf_causal_lm_to_prefix_lm(model: CAUSAL_LM_TYPES) -> CAUSAL_LM_TYPES` to solve the following problem:
Converts a HuggingFace Causal LM to a Prefix LM. Supported HuggingFace model classes: - `GPT2LMHeadModel` - `GPTNeoForCausalLM` - `GPTNeoXForCausalLM` - `GPTJForCausalLM` - `BloomForCausalLM` - `OPTForCausalLM` Conversion to a Prefix LM is done by modifying the `forward` method, and possibly also the `generate` method and/or select underlying methods depending on the model class. These changes preserve the model API, but add a new input to `forward`: "bidirectional_mask". Notes on training: To actually train the converted model as a Prefix LM, training batches will need to indicate the prefix/target structure by including `bidirectional_mask` as part of the batch inputs. **This is not a standard input and requires custom layers either within or after your dataloader.** In addition to adding `bidirectional_mask` to the batch, this custom code should modify `labels` such that `batch['labels'][batch['bidirectional_mask'] == 1] == -100`. That is, the prefix portion of the sequence should not generate any loss. Loss should only be generated by the target portion of the sequence. Notes on `GPTNeoForCausalLM`: To simplify the implementation, "global" and "local" attention layers are handled differently. For "global" layers, we handle conversion as described above. For "local" layers, which use a causal attention mask within a restricted local window, we do not alter the masking. Notes on `forward` method conversion: After conversion, the `forward` method will handle a new input, `bidirectional_mask`, which should be a [batch_size, seq_length] byte tensor, where 1 indicates token positions belonging to the prefix (prefix tokens can attend to one another bidirectionally), and 0 indicates token positions belonging to the target. The new `forward` method will incorporate `bidirectional_mask` (if supplied) into the existing causal mask, call the original `forward` method, and (if the causal mask is a buffer) reset the causal masks before returning the result. Notes on `generate` method conversion: After conversion, the `generate` method will have the same signature but will internally convert all causal masks to be purely bidirectional, call the original `generate` method, and (where appropriate) reset the causal masks before returning the result. This works thanks to the logic of the HuggingFace `generate` API, which first encodes the token "prompt" passed to `generate` (which is treated as the prefix) and then sequentially generates each new token. Encodings are cached as generation happens, so all prefix tokens can attend to one another (as expected in a Prefix LM) and generated tokens can only attend to prefix tokens and previously-generated tokens (also as expected in a Prefix LM). To preserve the API, the original methods are renamed to `_original_forward` and `_original_generate`, and replaced with new `forward` and `generate` methods that wrap them, respectively. Although implementation details vary by model class.
Here is the function:
def convert_hf_causal_lm_to_prefix_lm(model: CAUSAL_LM_TYPES) -> CAUSAL_LM_TYPES:
"""Converts a HuggingFace Causal LM to a Prefix LM.
Supported HuggingFace model classes:
- `GPT2LMHeadModel`
- `GPTNeoForCausalLM`
- `GPTNeoXForCausalLM`
- `GPTJForCausalLM`
- `BloomForCausalLM`
- `OPTForCausalLM`
Conversion to a Prefix LM is done by modifying the `forward` method, and possibly also the
`generate` method and/or select underlying methods depending on the model class.
These changes preserve the model API, but add a new input to `forward`: "bidirectional_mask".
Notes on training:
To actually train the converted model as a Prefix LM, training batches will need to indicate
the prefix/target structure by including `bidirectional_mask` as part of the batch inputs.
**This is not a standard input and requires custom layers either within or after your dataloader.**
In addition to adding `bidirectional_mask` to the batch, this custom code should modify `labels`
such that `batch['labels'][batch['bidirectional_mask'] == 1] == -100`.
That is, the prefix portion of the sequence should not generate any loss. Loss should only be
generated by the target portion of the sequence.
Notes on `GPTNeoForCausalLM`:
To simplify the implementation, "global" and "local" attention layers are handled differently.
For "global" layers, we handle conversion as described above. For "local" layers, which use a
causal attention mask within a restricted local window, we do not alter the masking.
Notes on `forward` method conversion:
After conversion, the `forward` method will handle a new input, `bidirectional_mask`,
which should be a [batch_size, seq_length] byte tensor, where 1 indicates token positions
belonging to the prefix (prefix tokens can attend to one another bidirectionally), and
0 indicates token positions belonging to the target.
The new `forward` method will incorporate `bidirectional_mask` (if supplied) into the existing
causal mask, call the original `forward` method, and (if the causal mask is a buffer) reset
the causal masks before returning the result.
Notes on `generate` method conversion:
After conversion, the `generate` method will have the same signature but will internally
convert all causal masks to be purely bidirectional, call the original `generate` method, and
(where appropriate) reset the causal masks before returning the result.
This works thanks to the logic of the HuggingFace `generate` API, which first encodes the token
"prompt" passed to `generate` (which is treated as the prefix) and then sequentially generates
each new token. Encodings are cached as generation happens, so all prefix tokens can attend to one
another (as expected in a Prefix LM) and generated tokens can only attend to prefix tokens and
previously-generated tokens (also as expected in a Prefix LM).
To preserve the API, the original methods are renamed to `_original_forward` and
`_original_generate`, and replaced with new `forward` and `generate` methods that wrap
them, respectively. Although implementation details vary by model class.
"""
if isinstance(model, _SUPPORTED_GPT_MODELS):
return _convert_gpt_causal_lm_to_prefix_lm(model)
elif isinstance(model, BloomForCausalLM):
return _convert_bloom_causal_lm_to_prefix_lm(model)
elif isinstance(model, OPTForCausalLM):
return _convert_opt_causal_lm_to_prefix_lm(model)
else:
raise TypeError(f'Cannot convert model to Prefix LM. ' + f'Model does not belong to set of supported HF models:' + f'\n{_SUPPORTED_HF_MODELS}') | Converts a HuggingFace Causal LM to a Prefix LM. Supported HuggingFace model classes: - `GPT2LMHeadModel` - `GPTNeoForCausalLM` - `GPTNeoXForCausalLM` - `GPTJForCausalLM` - `BloomForCausalLM` - `OPTForCausalLM` Conversion to a Prefix LM is done by modifying the `forward` method, and possibly also the `generate` method and/or select underlying methods depending on the model class. These changes preserve the model API, but add a new input to `forward`: "bidirectional_mask". Notes on training: To actually train the converted model as a Prefix LM, training batches will need to indicate the prefix/target structure by including `bidirectional_mask` as part of the batch inputs. **This is not a standard input and requires custom layers either within or after your dataloader.** In addition to adding `bidirectional_mask` to the batch, this custom code should modify `labels` such that `batch['labels'][batch['bidirectional_mask'] == 1] == -100`. That is, the prefix portion of the sequence should not generate any loss. Loss should only be generated by the target portion of the sequence. Notes on `GPTNeoForCausalLM`: To simplify the implementation, "global" and "local" attention layers are handled differently. For "global" layers, we handle conversion as described above. For "local" layers, which use a causal attention mask within a restricted local window, we do not alter the masking. Notes on `forward` method conversion: After conversion, the `forward` method will handle a new input, `bidirectional_mask`, which should be a [batch_size, seq_length] byte tensor, where 1 indicates token positions belonging to the prefix (prefix tokens can attend to one another bidirectionally), and 0 indicates token positions belonging to the target. The new `forward` method will incorporate `bidirectional_mask` (if supplied) into the existing causal mask, call the original `forward` method, and (if the causal mask is a buffer) reset the causal masks before returning the result. Notes on `generate` method conversion: After conversion, the `generate` method will have the same signature but will internally convert all causal masks to be purely bidirectional, call the original `generate` method, and (where appropriate) reset the causal masks before returning the result. This works thanks to the logic of the HuggingFace `generate` API, which first encodes the token "prompt" passed to `generate` (which is treated as the prefix) and then sequentially generates each new token. Encodings are cached as generation happens, so all prefix tokens can attend to one another (as expected in a Prefix LM) and generated tokens can only attend to prefix tokens and previously-generated tokens (also as expected in a Prefix LM). To preserve the API, the original methods are renamed to `_original_forward` and `_original_generate`, and replaced with new `forward` and `generate` methods that wrap them, respectively. Although implementation details vary by model class. |
3,029 | import math
import warnings
from types import MethodType
from typing import Any, Dict, List, Optional, Tuple, Union
import torch
from transformers.models.bloom.modeling_bloom import BaseModelOutputWithPastAndCrossAttentions, BloomForCausalLM, BloomModel, CausalLMOutputWithCrossAttentions, CrossEntropyLoss
from transformers.models.bloom.modeling_bloom import _expand_mask as _expand_mask_bloom
from transformers.models.bloom.modeling_bloom import _make_causal_mask as _make_causal_mask_bloom
from transformers.models.bloom.modeling_bloom import logging
from transformers.models.gpt2.modeling_gpt2 import GPT2LMHeadModel
from transformers.models.gpt_neo.modeling_gpt_neo import GPTNeoForCausalLM
from transformers.models.gpt_neox.modeling_gpt_neox import GPTNeoXForCausalLM
from transformers.models.gptj.modeling_gptj import GPTJForCausalLM
from transformers.models.opt.modeling_opt import OPTForCausalLM
from transformers.models.opt.modeling_opt import _expand_mask as _expand_mask_opt
from transformers.models.opt.modeling_opt import _make_causal_mask as _make_causal_mask_opt
The provided code snippet includes necessary dependencies for implementing the `add_bidirectional_mask_if_missing` function. Write a Python function `def add_bidirectional_mask_if_missing(batch: Dict[str, Any])` to solve the following problem:
Attempts to add bidirectional_mask to batch if missing. Raises: KeyError if bidirectional_mask is missing and can't be inferred
Here is the function:
def add_bidirectional_mask_if_missing(batch: Dict[str, Any]):
"""Attempts to add bidirectional_mask to batch if missing.
Raises:
KeyError if bidirectional_mask is missing and can't be inferred
"""
if 'bidirectional_mask' not in batch:
if batch.get('mode', None) == 'icl_task':
batch['bidirectional_mask'] = batch['attention_mask'].clone()
for (i, continuation_indices) in enumerate(batch['continuation_indices']):
batch['bidirectional_mask'][i, continuation_indices] = 0
elif 'labels' in batch and 'attention_mask' in batch:
batch['bidirectional_mask'] = torch.logical_and(torch.eq(batch['attention_mask'], 1), torch.eq(batch['labels'], -100)).type_as(batch['attention_mask'])
else:
raise KeyError('No bidirectional_mask in batch and not sure how to construct one.') | Attempts to add bidirectional_mask to batch if missing. Raises: KeyError if bidirectional_mask is missing and can't be inferred |
3,030 | from typing import Union
from transformers import AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast
Tokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast]
NUM_SENTINEL_TOKENS: int = 100
The provided code snippet includes necessary dependencies for implementing the `adapt_tokenizer_for_denoising` function. Write a Python function `def adapt_tokenizer_for_denoising(tokenizer: Tokenizer)` to solve the following problem:
Adds sentinel tokens and padding token (if missing). Expands the tokenizer vocabulary to include sentinel tokens used in mixture-of-denoiser tasks as well as a padding token. All added tokens are added as special tokens. No tokens are added if sentinel tokens and padding token already exist.
Here is the function:
def adapt_tokenizer_for_denoising(tokenizer: Tokenizer):
"""Adds sentinel tokens and padding token (if missing).
Expands the tokenizer vocabulary to include sentinel tokens
used in mixture-of-denoiser tasks as well as a padding token.
All added tokens are added as special tokens. No tokens are
added if sentinel tokens and padding token already exist.
"""
sentinels_to_add = [f'<extra_id_{i}>' for i in range(NUM_SENTINEL_TOKENS)]
tokenizer.add_tokens(sentinels_to_add, special_tokens=True)
if tokenizer.pad_token is None:
tokenizer.add_tokens('<pad>', special_tokens=True)
tokenizer.pad_token = '<pad>'
assert tokenizer.pad_token_id is not None
sentinels = ''.join([f'<extra_id_{i}>' for i in range(NUM_SENTINEL_TOKENS)])
_sentinel_token_ids = tokenizer(sentinels, add_special_tokens=False).input_ids
tokenizer.sentinel_token_ids = _sentinel_token_ids | Adds sentinel tokens and padding token (if missing). Expands the tokenizer vocabulary to include sentinel tokens used in mixture-of-denoiser tasks as well as a padding token. All added tokens are added as special tokens. No tokens are added if sentinel tokens and padding token already exist. |
3,031 | import fnmatch
import json
import datasets
import torch
import transformers
from accelerate import Accelerator
from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser
from lm_eval.arguments import EvalArguments
from lm_eval.evaluator import Evaluator
from lm_eval.tasks import ALL_TASKS
class MultiChoice:
def __init__(self, choices):
self.choices = choices
# Simple wildcard support (linux filename patterns)
def __contains__(self, values):
for value in values.split(","):
if len(fnmatch.filter(self.choices, value)) == 0:
return False
return True
def __iter__(self):
for choice in self.choices:
yield choice
def parse_args():
parser = HfArgumentParser(EvalArguments)
parser.add_argument(
"--model",
default="codeparrot/codeparrot-small",
help="Model to evaluate, provide a repo name in Hugging Face hub or a local path",
)
parser.add_argument(
"--revision",
default=None,
help="Model revision to use",
)
parser.add_argument(
"--use_auth_token",
action="store_true",
help="Use the token generated when running `huggingface-cli login` (necessary for private model).",
)
parser.add_argument(
"--trust_remote_code",
action="store_true",
help="Use a model with custom code, this requires executing code by the author of the model.",
)
parser.add_argument(
"--tasks",
default=None,
choices=MultiChoice(ALL_TASKS),
help=f"Evaluation tasks from {ALL_TASKS}",
)
parser.add_argument(
"--instruction_tokens",
default=None,
help="A series of instruction tokens used for instruction-tuning benchamrks separated by comma e.g. <user_message>,<end_user_message>,<assistant_message>",
)
parser.add_argument(
"--batch_size",
type=int,
default=1,
help="Batch size for evaluation on each worker, can be larger for HumanEval",
)
parser.add_argument(
"--max_length_generation",
type=int,
default=512,
help="Maximum length of generated sequence (prompt+generation)",
)
parser.add_argument(
"--precision",
type=str,
default="fp32",
help="Model precision, from: fp32, fp16 or bf16",
)
parser.add_argument(
"--load_in_8bit",
action="store_true",
help="Load model in 8bit",
)
parser.add_argument(
"--load_in_4bit",
action="store_true",
help="Load model in 4bit",
)
parser.add_argument(
"--limit",
type=int,
default=None,
help="Number of samples to solve and evaluate from the benchmark",
)
parser.add_argument(
"--postprocess",
action="store_false",
help="Postprocess model outputs before execution, always on except during generation tests",
)
parser.add_argument(
"--allow_code_execution",
action="store_true",
help="Allow code evaluation to execute external/untrusted Python code on your machine",
)
parser.add_argument(
"--generation_only",
action="store_true",
help="Do code generation but no evaluation",
)
parser.add_argument(
"--load_generations_path",
type=str,
default=None,
help="Path of file with previously generated solutions, if provided generation is skipped and only evaluation is done",
)
parser.add_argument(
"--metric_output_path",
type=str,
default="evaluation_results.json",
help="Path to save the results",
)
parser.add_argument(
"--save_generations",
action="store_true",
help="Whether to save code generations",
)
parser.add_argument(
"--save_generations_path",
type=str,
default="generations.json",
help="Path for saving the code generations",
)
parser.add_argument(
"--save_references",
action="store_true",
help="Whether to save reference solutions/tests",
)
return parser.parse_args() | null |
3,032 | import fnmatch
import json
import datasets
import torch
import transformers
from accelerate import Accelerator
from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser
from lm_eval.arguments import EvalArguments
from lm_eval.evaluator import Evaluator
from lm_eval.tasks import ALL_TASKS
The provided code snippet includes necessary dependencies for implementing the `pattern_match` function. Write a Python function `def pattern_match(patterns, source_list)` to solve the following problem:
Returns a list containing all values of the source_list that match at least one of the patterns
Here is the function:
def pattern_match(patterns, source_list):
"""Returns a list containing all values of the source_list that
match at least one of the patterns"""
task_names = set()
for pattern in patterns:
for matching in fnmatch.filter(source_list, pattern):
task_names.add(matching)
return list(task_names) | Returns a list containing all values of the source_list that match at least one of the patterns |
3,033 | from os import path
import datetime
import os
import platform
import re
import runpy
import subprocess
import sys
from setuptools import setup, find_packages, Extension
The provided code snippet includes necessary dependencies for implementing the `get_cflags` function. Write a Python function `def get_cflags()` to solve the following problem:
Returns suitable CFLAGS for the platform.
Here is the function:
def get_cflags():
"Returns suitable CFLAGS for the platform."
if platform.system() == "Windows":
# unistd.h is not available with MSDEV.
# See https://bitbucket.org/blais/beancount/issues/173/
return ["-DYY_NO_UNISTD_H"]
else:
return ["-std=gnu99"] | Returns suitable CFLAGS for the platform. |
3,034 | from os import path
import datetime
import os
import platform
import re
import runpy
import subprocess
import sys
from setuptools import setup, find_packages, Extension
The provided code snippet includes necessary dependencies for implementing the `get_hg_changeset` function. Write a Python function `def get_hg_changeset()` to solve the following problem:
Get the Mercurial changeset id.
Here is the function:
def get_hg_changeset():
"""Get the Mercurial changeset id."""
try:
output = subprocess.check_output(
["hg", "parent", "--template", "{node} {date|hgdate}"], shell=False
)
vc_changeset, vc_timestamp = output.decode("utf-8").split()[:2]
vc_changeset = "hg:{}".format(vc_changeset)
return vc_changeset, vc_timestamp
except (subprocess.CalledProcessError, FileNotFoundError, PermissionError):
return None | Get the Mercurial changeset id. |
3,035 | from os import path
import datetime
import os
import platform
import re
import runpy
import subprocess
import sys
from setuptools import setup, find_packages, Extension
The provided code snippet includes necessary dependencies for implementing the `get_git_changeset` function. Write a Python function `def get_git_changeset()` to solve the following problem:
Get the Git changeset id.
Here is the function:
def get_git_changeset():
"""Get the Git changeset id."""
try:
output = subprocess.check_output(
["git", "log", "--pretty=%H %ct", "-1"], shell=False
)
match = re.match(r"([0-9a-f]+) ([0-9]+)$", output.decode("utf-8").strip())
if match:
vc_changeset = "git:{}".format(match.group(1))
vc_timestamp = match.group(2)
return vc_changeset, vc_timestamp
else:
return None
except (subprocess.CalledProcessError, FileNotFoundError, PermissionError):
return None | Get the Git changeset id. |
3,036 | from os import path
from typing import Any, Optional
import collections
import copy
import functools
import glob
import hashlib
import importlib
import io
import itertools
import logging
import os
import pickle
import struct
import sys
import textwrap
import time
import traceback
import warnings
from beancount.utils import misc_utils
from beancount.core import data
from beancount.parser import parser
from beancount.parser import booking
from beancount.parser import options
from beancount.parser import printer
from beancount.ops import validation
from beancount.utils import encryption
from beancount.utils import file_utils
The provided code snippet includes necessary dependencies for implementing the `combine_plugins` function. Write a Python function `def combine_plugins(*plugin_modules)` to solve the following problem:
Combine the plugins from the given plugin modules. This is used to create plugins of plugins. Args: *plugins_modules: A sequence of module objects. Returns: A list that can be assigned to the new module's __plugins__ attribute.
Here is the function:
def combine_plugins(*plugin_modules):
"""Combine the plugins from the given plugin modules.
This is used to create plugins of plugins.
Args:
*plugins_modules: A sequence of module objects.
Returns:
A list that can be assigned to the new module's __plugins__ attribute.
"""
modules = []
for module in plugin_modules:
modules.extend([getattr(module, name)
for name in module.__plugins__])
return modules | Combine the plugins from the given plugin modules. This is used to create plugins of plugins. Args: *plugins_modules: A sequence of module objects. Returns: A list that can be assigned to the new module's __plugins__ attribute. |
3,037 | from os import path
from typing import Any, Optional
import collections
import copy
import functools
import glob
import hashlib
import importlib
import io
import itertools
import logging
import os
import pickle
import struct
import sys
import textwrap
import time
import traceback
import warnings
from beancount.utils import misc_utils
from beancount.core import data
from beancount.parser import parser
from beancount.parser import booking
from beancount.parser import options
from beancount.parser import printer
from beancount.ops import validation
from beancount.utils import encryption
from beancount.utils import file_utils
def load_string(string, log_timings=None, log_errors=None, extra_validations=None,
dedent=False, encoding=None):
"""Open a Beancount input string, parse it, run transformations and validate.
Args:
string: A Beancount input string.
log_timings: A file object or function to write timings to,
or None, if it should remain quiet.
log_errors: A file object or function to write errors to,
or None, if it should remain quiet.
extra_validations: A list of extra validation functions to run after loading
this list of entries.
dedent: A boolean, if set, remove the whitespace in front of the lines.
encoding: A string or None, the encoding to decode the input string with.
Returns:
A triple of (entries, errors, option_map) where "entries" is a date-sorted
list of entries from the string, "errors" a list of error objects
generated while parsing and validating the string, and "options_map", a
dict of the options parsed from the string.
"""
if dedent:
string = textwrap.dedent(string)
entries, errors, options_map = _load([(string, False)], log_timings,
extra_validations, encoding)
_log_errors(errors, log_errors)
return entries, errors, options_map
The provided code snippet includes necessary dependencies for implementing the `load_doc` function. Write a Python function `def load_doc(expect_errors=False)` to solve the following problem:
A factory of decorators that loads the docstring and calls the function with entries. This is an incredibly convenient tool to write lots of tests. Write a unittest using the standard TestCase class and put the input entries in the function's docstring. Args: expect_errors: A boolean or None, with the following semantics, True: Expect errors and fail if there are none. False: Expect no errors and fail if there are some. None: Do nothing, no check. Returns: A wrapped method that accepts a single 'self' argument.
Here is the function:
def load_doc(expect_errors=False):
"""A factory of decorators that loads the docstring and calls the function with entries.
This is an incredibly convenient tool to write lots of tests. Write a
unittest using the standard TestCase class and put the input entries in the
function's docstring.
Args:
expect_errors: A boolean or None, with the following semantics,
True: Expect errors and fail if there are none.
False: Expect no errors and fail if there are some.
None: Do nothing, no check.
Returns:
A wrapped method that accepts a single 'self' argument.
"""
def decorator(fun):
"""A decorator that parses the function's docstring as an argument.
Args:
fun: A callable method, that accepts the three return arguments that
load() returns.
Returns:
A decorated test function.
"""
@functools.wraps(fun)
def wrapper(self):
entries, errors, options_map = load_string(fun.__doc__, dedent=True)
if expect_errors is not None:
if expect_errors is False and errors:
oss = io.StringIO()
printer.print_errors(errors, file=oss)
self.fail("Unexpected errors found:\n{}".format(oss.getvalue()))
elif expect_errors is True and not errors:
self.fail("Expected errors, none found:")
# Note: Even if we expected no errors, we call this function with an
# empty 'errors' list. This is so that the interface does not change
# based on the arguments to the decorator, which would be somewhat
# ugly and which would require explanation.
return fun(self, entries, errors, options_map)
wrapper.__input__ = wrapper.__doc__
wrapper.__doc__ = None
return wrapper
return decorator | A factory of decorators that loads the docstring and calls the function with entries. This is an incredibly convenient tool to write lots of tests. Write a unittest using the standard TestCase class and put the input entries in the function's docstring. Args: expect_errors: A boolean or None, with the following semantics, True: Expect errors and fail if there are none. False: Expect no errors and fail if there are some. None: Do nothing, no check. Returns: A wrapped method that accepts a single 'self' argument. |
3,038 | from os import path
from typing import Any, Optional
import collections
import copy
import functools
import glob
import hashlib
import importlib
import io
import itertools
import logging
import os
import pickle
import struct
import sys
import textwrap
import time
import traceback
import warnings
from beancount.utils import misc_utils
from beancount.core import data
from beancount.parser import parser
from beancount.parser import booking
from beancount.parser import options
from beancount.parser import printer
from beancount.ops import validation
from beancount.utils import encryption
from beancount.utils import file_utils
PICKLE_CACHE_FILENAME = '.{filename}.picklecache'
PICKLE_CACHE_THRESHOLD = 1.0
def get_cache_filename(pattern: str, filename: str) -> str:
"""Compute the cache filename from a given pattern and the top-level filename.
Args:
pattern: A cache filename or pattern. If the pattern contains '{filename}' this
will get replaced by the top-level filename. This may be absolute or relative.
filename: The top-level filename.
Returns:
The resolved cache filename.
"""
abs_filename = path.abspath(filename)
if path.isabs(pattern):
abs_pattern = pattern
else:
abs_pattern = path.join(path.dirname(abs_filename), pattern)
return abs_pattern.format(filename=path.basename(filename))
def pickle_cache_function(cache_getter, time_threshold, function):
"""Decorate a loader function to make it loads its result from a pickle cache.
This considers the first argument as a top-level filename and assumes the
function to be cached returns an (entries, errors, options_map) triple. We
use the 'include' option value in order to check whether any of the included
files has changed. It's essentially a special case for an on-disk memoizer.
If any of the included files are more recent than the cache, the function is
recomputed and the cache refreshed.
Args:
cache_getter: A function of one argument, the top-level filename, which
will return the name of the corresponding cache file.
time_threshold: A float, the number of seconds below which we don't bother
caching.
function: A function object to decorate for caching.
Returns:
A decorated function which will pull its result from a cache file if
it is available.
"""
def wrapped(toplevel_filename, *args, **kw):
cache_filename = cache_getter(toplevel_filename)
# Read the cache if it exists in order to get the list of files whose
# timestamps to check.
exists = path.exists(cache_filename)
if exists:
with open(cache_filename, 'rb') as file:
try:
result = pickle.load(file)
except Exception as exc:
# Note: Not a big fan of doing this, but here we handle all
# possible exceptions because unpickling of an old or
# corrupted pickle file manifests as a variety of different
# exception types.
# The cache file is corrupted; ignore it and recompute.
logging.error("Cache file is corrupted: %s; recomputing.", exc)
result = None
else:
# Check that the latest timestamp has not been written after the
# cache file.
entries, errors, options_map = result
if not needs_refresh(options_map):
# All timestamps are legit; cache hit.
return result
# We failed; recompute the value.
if exists:
try:
os.remove(cache_filename)
except OSError as exc:
# Warn for errors on read-only filesystems.
logging.warning("Could not remove picklecache file %s: %s",
cache_filename, exc)
time_before = time.time()
result = function(toplevel_filename, *args, **kw)
time_after = time.time()
# Overwrite the cache file if the time it takes to compute it
# justifies it.
if time_after - time_before > time_threshold:
try:
with open(cache_filename, 'wb') as file:
pickle.dump(result, file)
except Exception as exc:
logging.warning("Could not write to picklecache file %s: %s",
cache_filename, exc)
return result
return wrapped
def delete_cache_function(cache_getter, function):
"""A wrapper that removes the cached filename.
Args:
cache_getter: A function of one argument, the top-level filename, which
will return the name of the corresponding cache file.
function: A function object to decorate for caching.
Returns:
A decorated function which will delete the cached filename, if it exists.
"""
def wrapped(toplevel_filename, *args, **kw):
# Delete the cache.
cache_filename = cache_getter(toplevel_filename)
if path.exists(cache_filename):
os.remove(cache_filename)
# Invoke the original function.
return function(toplevel_filename, *args, **kw)
return wrapped
def _uncached_load_file(filename, *args, **kw):
"""Delegate to _load. Note: This gets conditionally advised by caching below."""
return _load([(filename, True)], *args, **kw)
The provided code snippet includes necessary dependencies for implementing the `initialize` function. Write a Python function `def initialize(use_cache: bool, cache_filename: Optional[str] = None)` to solve the following problem:
Initialize the loader.
Here is the function:
def initialize(use_cache: bool, cache_filename: Optional[str] = None):
"""Initialize the loader."""
# Unless an environment variable disables it, use the pickle load cache
# automatically. Note that this works across all Python programs running the
# loader which is why it's located here.
# pylint: disable=invalid-name
global _load_file
# Make a function to compute the cache filename.
cache_pattern = (cache_filename or
os.getenv('BEANCOUNT_LOAD_CACHE_FILENAME') or
PICKLE_CACHE_FILENAME)
cache_getter = functools.partial(get_cache_filename, cache_pattern)
if use_cache:
_load_file = pickle_cache_function(cache_getter, PICKLE_CACHE_THRESHOLD,
_uncached_load_file)
else:
if cache_filename is not None:
logging.warning("Cache disabled; "
"Explicitly overridden cache filename %s will be ignored.",
cache_filename)
_load_file = delete_cache_function(cache_getter,
_uncached_load_file) | Initialize the loader. |
3,039 | import collections
import copy
import functools
import io
import operator
from beancount.core.data import Transaction
from beancount.core.data import Posting
from beancount.core.data import TxnPosting
from beancount.core.data import Balance
from beancount.core.data import Open
from beancount.core.data import Close
from beancount.core.data import Pad
from beancount.core.data import Note
from beancount.core.data import Document
from beancount.core.data import Custom
from beancount.core import inventory
from beancount.core import amount
from beancount.core import data
from beancount.core import account
from beancount.core import convert
def get(real_account, account_name, default=None):
"""Fetch the subaccount name from the real_account node.
Args:
real_account: An instance of RealAccount, the parent node to look for
children of.
account_name: A string, the name of a possibly indirect child leaf
found down the tree of 'real_account' nodes.
default: The default value that should be returned if the child
subaccount is not found.
Returns:
A RealAccount instance for the child, or the default value, if the child
is not found.
"""
if not isinstance(account_name, str):
raise ValueError
components = account.split(account_name)
for component in components:
real_child = real_account.get(component, default)
if real_child is default:
return default
real_account = real_child
return real_account
The provided code snippet includes necessary dependencies for implementing the `contains` function. Write a Python function `def contains(real_account, account_name)` to solve the following problem:
True if the given account node contains the subaccount name. Args: account_name: A string, the name of a direct or indirect subaccount of this node. Returns: A boolean, true the name is a child of this node.
Here is the function:
def contains(real_account, account_name):
"""True if the given account node contains the subaccount name.
Args:
account_name: A string, the name of a direct or indirect subaccount of
this node.
Returns:
A boolean, true the name is a child of this node.
"""
return get(real_account, account_name) is not None | True if the given account node contains the subaccount name. Args: account_name: A string, the name of a direct or indirect subaccount of this node. Returns: A boolean, true the name is a child of this node. |
3,040 | import collections
import copy
import functools
import io
import operator
from beancount.core.data import Transaction
from beancount.core.data import Posting
from beancount.core.data import TxnPosting
from beancount.core.data import Balance
from beancount.core.data import Open
from beancount.core.data import Close
from beancount.core.data import Pad
from beancount.core.data import Note
from beancount.core.data import Document
from beancount.core.data import Custom
from beancount.core import inventory
from beancount.core import amount
from beancount.core import data
from beancount.core import account
from beancount.core import convert
class RealAccount(dict):
"""A realized account, inserted in a tree, that contains the list of realized entries.
Attributes:
account: A string, the full name of the corresponding account.
postings: A list of postings associated with this accounting (does not
include the postings of children accounts).
balance: The final balance of the list of postings associated with this account.
"""
__slots__ = ('account', 'txn_postings', 'balance')
def __init__(self, account_name, *args, **kwargs):
"""Create a RealAccount instance.
Args:
account_name: a string, the name of the account. Maybe not be None.
"""
super().__init__(*args, **kwargs)
assert isinstance(account_name, str)
self.account = account_name
self.txn_postings = []
self.balance = inventory.Inventory()
def __setitem__(self, key, value):
"""Prevent the setting of non-string or non-empty keys on this dict.
Args:
key: The dictionary key. Must be a string.
value: The value, must be a RealAccount instance.
Raises:
KeyError: If the key is not a string, or is invalid.
ValueError: If the value is not a RealAccount instance.
"""
if not isinstance(key, str) or not key:
raise KeyError("Invalid RealAccount key: '{}'".format(key))
if not isinstance(value, RealAccount):
raise ValueError("Invalid RealAccount value: '{}'".format(value))
if not value.account.endswith(key):
raise ValueError("RealAccount name '{}' inconsistent with key: '{}'".format(
value.account, key))
return super().__setitem__(key, value)
def copy(self):
"""Override dict.copy() to clone a RealAccount.
This is only necessary to correctly implement the copy method.
Otherwise, calling .copy() on a RealAccount instance invokes the base
class' method, which return just a dict.
Returns:
A cloned instance of RealAccount, with all members shallow-copied.
"""
return copy.copy(self)
def __eq__(self, other):
"""Equality predicate. All attributes are compared.
Args:
other: Another instance of RealAccount.
Returns:
A boolean, True if the two real accounts are equal.
"""
return (dict.__eq__(self, other) and
self.account == other.account and
self.balance == other.balance and
self.txn_postings == other.txn_postings)
def __ne__(self, other):
"""Not-equality predicate. See __eq__.
Args:
other: Another instance of RealAccount.
Returns:
A boolean, True if the two real accounts are not equal.
"""
return not self.__eq__(other)
The provided code snippet includes necessary dependencies for implementing the `filter` function. Write a Python function `def filter(real_account, predicate)` to solve the following problem:
Filter a RealAccount tree of nodes by the predicate. This function visits the tree and applies the predicate on each node. It returns a partial clone of RealAccount whereby on each node - either the predicate is true, or - for at least one child of the node the predicate is true. All the leaves have the predicate be true. Args: real_account: An instance of RealAccount. predicate: A callable/function which accepts a RealAccount and returns a boolean. If the function returns True, the node is kept. Returns: A shallow clone of RealAccount is always returned.
Here is the function:
def filter(real_account, predicate):
"""Filter a RealAccount tree of nodes by the predicate.
This function visits the tree and applies the predicate on each node. It
returns a partial clone of RealAccount whereby on each node
- either the predicate is true, or
- for at least one child of the node the predicate is true.
All the leaves have the predicate be true.
Args:
real_account: An instance of RealAccount.
predicate: A callable/function which accepts a RealAccount and returns
a boolean. If the function returns True, the node is kept.
Returns:
A shallow clone of RealAccount is always returned.
"""
assert isinstance(real_account, RealAccount)
real_copy = RealAccount(real_account.account)
real_copy.balance = real_account.balance
real_copy.txn_postings = real_account.txn_postings
for child_name, real_child in real_account.items():
real_child_copy = filter(real_child, predicate)
if real_child_copy is not None:
real_copy[child_name] = real_child_copy
if len(real_copy) > 0 or predicate(real_account):
return real_copy | Filter a RealAccount tree of nodes by the predicate. This function visits the tree and applies the predicate on each node. It returns a partial clone of RealAccount whereby on each node - either the predicate is true, or - for at least one child of the node the predicate is true. All the leaves have the predicate be true. Args: real_account: An instance of RealAccount. predicate: A callable/function which accepts a RealAccount and returns a boolean. If the function returns True, the node is kept. Returns: A shallow clone of RealAccount is always returned. |
3,041 | import collections
import copy
import functools
import io
import operator
from beancount.core.data import Transaction
from beancount.core.data import Posting
from beancount.core.data import TxnPosting
from beancount.core.data import Balance
from beancount.core.data import Open
from beancount.core.data import Close
from beancount.core.data import Pad
from beancount.core.data import Note
from beancount.core.data import Document
from beancount.core.data import Custom
from beancount.core import inventory
from beancount.core import amount
from beancount.core import data
from beancount.core import account
from beancount.core import convert
def iter_children(real_account, leaf_only=False):
"""Iterate this account node and all its children, depth-first.
Args:
real_account: An instance of RealAccount.
leaf_only: A boolean flag, true if we should yield only leaves.
Yields:
Instances of RealAccount, beginning with this account. The order is
undetermined.
"""
if leaf_only:
if len(real_account) == 0:
yield real_account
else:
for key, real_child in sorted(real_account.items()):
for real_subchild in iter_children(real_child, leaf_only):
yield real_subchild
else:
yield real_account
for key, real_child in sorted(real_account.items()):
for real_subchild in iter_children(real_child):
yield real_subchild
The provided code snippet includes necessary dependencies for implementing the `get_postings` function. Write a Python function `def get_postings(real_account)` to solve the following problem:
Return a sorted list a RealAccount's postings and children. Args: real_account: An instance of RealAccount. Returns: A list of Posting or directories.
Here is the function:
def get_postings(real_account):
"""Return a sorted list a RealAccount's postings and children.
Args:
real_account: An instance of RealAccount.
Returns:
A list of Posting or directories.
"""
# We accumulate all the postings at once here instead of incrementally
# because we need to return them sorted.
accumulator = []
for real_child in iter_children(real_account):
accumulator.extend(real_child.txn_postings)
accumulator.sort(key=data.posting_sortkey)
return accumulator | Return a sorted list a RealAccount's postings and children. Args: real_account: An instance of RealAccount. Returns: A list of Posting or directories. |
3,042 | import collections
import copy
import functools
import io
import operator
from beancount.core.data import Transaction
from beancount.core.data import Posting
from beancount.core.data import TxnPosting
from beancount.core.data import Balance
from beancount.core.data import Open
from beancount.core.data import Close
from beancount.core.data import Pad
from beancount.core.data import Note
from beancount.core.data import Document
from beancount.core.data import Custom
from beancount.core import inventory
from beancount.core import amount
from beancount.core import data
from beancount.core import account
from beancount.core import convert
def index_key(sequence, value, key, cmp):
"""Find the index of the first element in 'sequence' which is equal to 'value'.
If 'key' is specified, the value compared to the value returned by this
function. If the value is not found, return None.
Args:
sequence: The sequence to search.
value: The value to search for.
key: A predicate to call to obtain the value to compare against.
cmp: A comparison predicate.
Returns:
The index of the first element found, or None, if the element was not found.
"""
for index, element in enumerate(sequence):
if cmp(key(element), value):
return index
return
class Posting(NamedTuple):
"""
Postings are contained in Transaction entries. These represent the individual
legs of a transaction. Note: a posting may only appear within a single entry
(multiple transactions may not share a Posting instance), and that's what the
entry field should be set to.
Attributes:
account: A string, the account that is modified by this posting.
units: An Amount, the units of the position.
cost: A Cost or CostSpec instances, the units of the position.
price: An Amount, the price at which the position took place, or
None, where not relevant. Providing a price member to a posting
automatically adds a price in the prices database at the date of the
transaction.
flag: An optional flag, a one-character string or None, which is to be
associated with the posting. Most postings don't have a flag, but it can
be convenient to mark a particular posting as problematic or pending to
be reconciled for a future import of its account.
meta: A dict of strings to values, the metadata that was attached
specifically to that posting, or None, if not provided. In practice, most
of the instances will be unlikely to have metadata.
"""
account: Account
units: Amount
cost: Optional[Union[Cost, CostSpec]]
price: Optional[Amount]
flag: Optional[Flag]
meta: Optional[Meta]
class TxnPosting(NamedTuple):
"""
A pair of a Posting and its parent Transaction. This is inserted as
temporaries in lists of postings-of-entries, which is the product of a
realization.
Attributes:
txn: The parent Transaction instance.
posting: The Posting instance.
"""
txn: Transaction
posting: Posting
The provided code snippet includes necessary dependencies for implementing the `iterate_with_balance` function. Write a Python function `def iterate_with_balance(txn_postings)` to solve the following problem:
Iterate over the entries, accumulating the running balance. For each entry, this yields tuples of the form: (entry, postings, change, balance) entry: This is the directive for this line. If the list contained Posting instance, this yields the corresponding Transaction object. postings: A list of postings on this entry that affect the balance. Only the postings encountered in the input list are included; only those affect the balance. If 'entry' is not a Transaction directive, this should always be an empty list. We preserve the original ordering of the postings as they appear in the input list. change: An Inventory object that reflects the total change due to the postings from this entry that appear in the list. For example, if a Transaction has three postings and two are in the input list, the sum of the two postings will be in the 'change' Inventory object. However, the position for the transactions' third posting--the one not included in the input list--will not be in this inventory. balance: An Inventory object that reflects the balance *after* adding the 'change' inventory due to this entry's transaction. The 'balance' yielded is never None, even for entries that do not affect the balance, that is, with an empty 'change' inventory. It's up to the caller, the one rendering the entry, to decide whether to render this entry's change for a particular entry type. Note that if the input list of postings-or-entries is not in sorted date order, two postings for the same entry appearing twice with a different date in between will cause the entry appear twice. This is correct behavior, and it is expected that in practice this should never happen anyway, because the list of postings or entries should always be sorted. This method attempts to detect this and raises an assertion if this is seen. Args: txn_postings: A list of postings or directive instances. Postings affect the balance; other entries do not. Yields: Tuples of (entry, postings, change, balance) as described above.
Here is the function:
def iterate_with_balance(txn_postings):
"""Iterate over the entries, accumulating the running balance.
For each entry, this yields tuples of the form:
(entry, postings, change, balance)
entry: This is the directive for this line. If the list contained Posting
instance, this yields the corresponding Transaction object.
postings: A list of postings on this entry that affect the balance. Only the
postings encountered in the input list are included; only those affect the
balance. If 'entry' is not a Transaction directive, this should always be
an empty list. We preserve the original ordering of the postings as they
appear in the input list.
change: An Inventory object that reflects the total change due to the
postings from this entry that appear in the list. For example, if a
Transaction has three postings and two are in the input list, the sum of
the two postings will be in the 'change' Inventory object. However, the
position for the transactions' third posting--the one not included in the
input list--will not be in this inventory.
balance: An Inventory object that reflects the balance *after* adding the
'change' inventory due to this entry's transaction. The 'balance' yielded
is never None, even for entries that do not affect the balance, that is,
with an empty 'change' inventory. It's up to the caller, the one rendering
the entry, to decide whether to render this entry's change for a
particular entry type.
Note that if the input list of postings-or-entries is not in sorted date
order, two postings for the same entry appearing twice with a different date
in between will cause the entry appear twice. This is correct behavior, and
it is expected that in practice this should never happen anyway, because the
list of postings or entries should always be sorted. This method attempts to
detect this and raises an assertion if this is seen.
Args:
txn_postings: A list of postings or directive instances.
Postings affect the balance; other entries do not.
Yields:
Tuples of (entry, postings, change, balance) as described above.
"""
# The running balance.
running_balance = inventory.Inventory()
# Previous date.
prev_date = None
# A list of entries at the current date.
date_entries = []
first = lambda pair: pair[0]
for txn_posting in txn_postings:
# Get the posting if we are dealing with one.
assert not isinstance(txn_posting, Posting)
if isinstance(txn_posting, TxnPosting):
posting = txn_posting.posting
entry = txn_posting.txn
else:
posting = None
entry = txn_posting
if entry.date != prev_date:
assert prev_date is None or entry.date > prev_date, (
"Invalid date order for postings: {} > {}".format(prev_date, entry.date))
prev_date = entry.date
# Flush the dated entries.
for date_entry, date_postings in date_entries:
change = inventory.Inventory()
if date_postings:
# Compute the change due to this transaction and update the
# total balance at the same time.
for date_posting in date_postings:
change.add_position(date_posting)
running_balance.add_position(date_posting)
yield date_entry, date_postings, change, running_balance
date_entries.clear()
assert not date_entries
if posting is not None:
# De-dup multiple postings on the same transaction entry by
# grouping their positions together.
index = index_key(date_entries, entry, first, operator.is_)
if index is None:
date_entries.append((entry, [posting]))
else:
# We are indeed de-duping!
postings = date_entries[index][1]
postings.append(posting)
else:
# This is a regular entry; nothing to add/remove.
date_entries.append((entry, []))
# Flush the final dated entries if any, same as above.
for date_entry, date_postings in date_entries:
change = inventory.Inventory()
if date_postings:
for date_posting in date_postings:
change.add_position(date_posting)
running_balance.add_position(date_posting)
yield date_entry, date_postings, change, running_balance
date_entries.clear() | Iterate over the entries, accumulating the running balance. For each entry, this yields tuples of the form: (entry, postings, change, balance) entry: This is the directive for this line. If the list contained Posting instance, this yields the corresponding Transaction object. postings: A list of postings on this entry that affect the balance. Only the postings encountered in the input list are included; only those affect the balance. If 'entry' is not a Transaction directive, this should always be an empty list. We preserve the original ordering of the postings as they appear in the input list. change: An Inventory object that reflects the total change due to the postings from this entry that appear in the list. For example, if a Transaction has three postings and two are in the input list, the sum of the two postings will be in the 'change' Inventory object. However, the position for the transactions' third posting--the one not included in the input list--will not be in this inventory. balance: An Inventory object that reflects the balance *after* adding the 'change' inventory due to this entry's transaction. The 'balance' yielded is never None, even for entries that do not affect the balance, that is, with an empty 'change' inventory. It's up to the caller, the one rendering the entry, to decide whether to render this entry's change for a particular entry type. Note that if the input list of postings-or-entries is not in sorted date order, two postings for the same entry appearing twice with a different date in between will cause the entry appear twice. This is correct behavior, and it is expected that in practice this should never happen anyway, because the list of postings or entries should always be sorted. This method attempts to detect this and raises an assertion if this is seen. Args: txn_postings: A list of postings or directive instances. Postings affect the balance; other entries do not. Yields: Tuples of (entry, postings, change, balance) as described above. |
3,043 | import collections
import copy
import functools
import io
import operator
from beancount.core.data import Transaction
from beancount.core.data import Posting
from beancount.core.data import TxnPosting
from beancount.core.data import Balance
from beancount.core.data import Open
from beancount.core.data import Close
from beancount.core.data import Pad
from beancount.core.data import Note
from beancount.core.data import Document
from beancount.core.data import Custom
from beancount.core import inventory
from beancount.core import amount
from beancount.core import data
from beancount.core import account
from beancount.core import convert
class Open(NamedTuple):
"""
An "open account" directive.
Attributes:
meta: See above.
date: See above.
account: A string, the name of the account that is being opened.
currencies: A list of strings, currencies that are allowed in this account.
May be None, in which case it means that there are no restrictions on which
currencies may be stored in this account.
booking: A Booking enum, the booking method to use to disambiguate
postings to this account (when zero or more than one postings match the
specification), or None if not specified. In practice, this attribute will
be should be left unspecified (None) in the vast majority of cases. See
Booking below for a selection of valid methods.
"""
meta: Meta
date: datetime.date
account: Account
currencies: List[Currency]
booking: Optional[Booking]
class Close(NamedTuple):
"""
A "close account" directive.
Attributes:
meta: See above.
date: See above.
account: A string, the name of the account that is being closed.
"""
meta: Meta
date: datetime.date
account: Account
class Pad(NamedTuple):
"""
A "pad this account with this other account" directive. This directive
automatically inserts transactions that will make the next chronological
balance directive succeeds. It can be used to fill in missing date ranges of
transactions, as a convenience. You don't have to use this, it's sugar coating
in case you need it, while you're entering past history into your Ledger.
Attributes:
meta: See above.
date: See above.
account: A string, the name of the account which needs to be filled.
source_account: A string, the name of the account which is used to debit from
in order to fill 'account'.
"""
meta: Meta
date: datetime.date
account: Account
source_account: Account
class Balance(NamedTuple):
"""
A "check the balance of this account" directive. This directive asserts that
the declared account should have a known number of units of a particular
currency at the beginning of its date. This is essentially an assertion, and
corresponds to the final "Statement Balance" line of a real-world statement.
These assertions act as checkpoints to help ensure that you have entered your
transactions correctly.
Attributes:
meta: See above.
date: See above.
account: A string, the account whose balance to check at the given date.
amount: An Amount, the number of units of the given currency you're
expecting 'account' to have at this date.
diff_amount: None if the balance check succeeds. This value is set to
an Amount instance if the balance fails, the amount of the difference.
tolerance: A Decimal object, the amount of tolerance to use in the
verification.
"""
meta: Meta
date: datetime.date
account: Account
amount: Amount
tolerance: Optional[Decimal]
diff_amount: Optional[Amount]
class Posting(NamedTuple):
"""
Postings are contained in Transaction entries. These represent the individual
legs of a transaction. Note: a posting may only appear within a single entry
(multiple transactions may not share a Posting instance), and that's what the
entry field should be set to.
Attributes:
account: A string, the account that is modified by this posting.
units: An Amount, the units of the position.
cost: A Cost or CostSpec instances, the units of the position.
price: An Amount, the price at which the position took place, or
None, where not relevant. Providing a price member to a posting
automatically adds a price in the prices database at the date of the
transaction.
flag: An optional flag, a one-character string or None, which is to be
associated with the posting. Most postings don't have a flag, but it can
be convenient to mark a particular posting as problematic or pending to
be reconciled for a future import of its account.
meta: A dict of strings to values, the metadata that was attached
specifically to that posting, or None, if not provided. In practice, most
of the instances will be unlikely to have metadata.
"""
account: Account
units: Amount
cost: Optional[Union[Cost, CostSpec]]
price: Optional[Amount]
flag: Optional[Flag]
meta: Optional[Meta]
class TxnPosting(NamedTuple):
"""
A pair of a Posting and its parent Transaction. This is inserted as
temporaries in lists of postings-of-entries, which is the product of a
realization.
Attributes:
txn: The parent Transaction instance.
posting: The Posting instance.
"""
txn: Transaction
posting: Posting
class Note(NamedTuple):
"""
A note directive, a general note that is attached to an account. These are
used to attach text at a particular date in a specific account. The notes can
be anything; a typical use would be to jot down an answer from a phone call to
the institution represented by the account. It should show up in an account's
journal. If you don't want this rendered, use the comment syntax in the input
file, which does not get parsed and stored.
Attributes:
meta: See above.
date: See above.
account: A string, the account which the note is to be attached to. This is
never None, notes always have an account they correspond to.
comment: A free-form string, the text of the note. This can be long if you
want it to.
"""
meta: Meta
date: datetime.date
account: Account
comment: str
tags: Optional[Set]
links: Optional[Set]
The provided code snippet includes necessary dependencies for implementing the `find_last_active_posting` function. Write a Python function `def find_last_active_posting(txn_postings)` to solve the following problem:
Look at the end of the list of postings, and find the last posting or entry that is not an automatically added directive. Note that if the account is closed, the last posting is assumed to be a Close directive (this is the case if the input is valid and checks without errors. Args: txn_postings: a list of postings or entries. Returns: An entry, or None, if the input list was empty.
Here is the function:
def find_last_active_posting(txn_postings):
"""Look at the end of the list of postings, and find the last
posting or entry that is not an automatically added directive.
Note that if the account is closed, the last posting is assumed
to be a Close directive (this is the case if the input is valid
and checks without errors.
Args:
txn_postings: a list of postings or entries.
Returns:
An entry, or None, if the input list was empty.
"""
for txn_posting in reversed(txn_postings):
assert not isinstance(txn_posting, Posting)
if not isinstance(txn_posting, (TxnPosting, Open, Close, Pad, Balance, Note)):
continue
return txn_posting | Look at the end of the list of postings, and find the last posting or entry that is not an automatically added directive. Note that if the account is closed, the last posting is assumed to be a Close directive (this is the case if the input is valid and checks without errors. Args: txn_postings: a list of postings or entries. Returns: An entry, or None, if the input list was empty. |
3,044 | import collections
import copy
from decimal import Decimal
from beancount.core.number import D
from beancount.core.number import ONE
from beancount.core.number import ZERO
from beancount.core.number import MISSING
from beancount.core.amount import Amount
from beancount.core.position import CostSpec
from beancount.core.position import Cost
from beancount.core.inventory import Inventory
from beancount.core import inventory
from beancount.core import convert
from beancount.core.data import Transaction
from beancount.core.data import Posting
from beancount.core import getters
from beancount.utils import defdict
The provided code snippet includes necessary dependencies for implementing the `has_nontrivial_balance` function. Write a Python function `def has_nontrivial_balance(posting)` to solve the following problem:
Return True if a Posting has a balance amount that would have to be calculated. Args: posting: A Posting instance. Returns: A boolean.
Here is the function:
def has_nontrivial_balance(posting):
"""Return True if a Posting has a balance amount that would have to be calculated.
Args:
posting: A Posting instance.
Returns:
A boolean.
"""
return posting.cost or posting.price | Return True if a Posting has a balance amount that would have to be calculated. Args: posting: A Posting instance. Returns: A boolean. |
3,045 | import collections
import copy
from decimal import Decimal
from beancount.core.number import D
from beancount.core.number import ONE
from beancount.core.number import ZERO
from beancount.core.number import MISSING
from beancount.core.amount import Amount
from beancount.core.position import CostSpec
from beancount.core.position import Cost
from beancount.core.inventory import Inventory
from beancount.core import inventory
from beancount.core import convert
from beancount.core.data import Transaction
from beancount.core.data import Posting
from beancount.core import getters
from beancount.utils import defdict
def compute_residual(postings):
"""Compute the residual of a set of complete postings, and the per-currency precision.
This is used to cross-check a balanced transaction.
The precision is the maximum fraction that is being used for each currency
(a dict). We use the currency of the weight amount in order to infer the
quantization precision for each currency. Integer amounts aren't
contributing to the determination of precision.
Args:
postings: A list of Posting instances.
Returns:
An instance of Inventory, with the residual of the given list of postings.
"""
inventory = Inventory()
for posting in postings:
# Skip auto-postings inserted to absorb the residual (rounding error).
if posting.meta and posting.meta.get(AUTOMATIC_RESIDUAL, False):
continue
# Add to total residual balance.
inventory.add_amount(convert.get_weight(posting))
return inventory
def get_residual_postings(residual, account_rounding):
"""Create postings to book the given residuals.
Args:
residual: An Inventory, the residual positions.
account_rounding: A string, the name of the rounding account that
absorbs residuals / rounding errors.
Returns:
A list of new postings to be inserted to reduce the given residual.
"""
meta = {AUTOMATIC_META: True,
AUTOMATIC_RESIDUAL: True}
return [Posting(account_rounding, -position.units, position.cost, None, None,
meta.copy())
for position in residual.get_positions()]
The provided code snippet includes necessary dependencies for implementing the `fill_residual_posting` function. Write a Python function `def fill_residual_posting(entry, account_rounding)` to solve the following problem:
If necessary, insert a posting to absorb the residual. This makes the transaction balance exactly. Note: This was developed in order to tweak transactions before exporting them to Ledger. A better method would be to enable the feature that automatically inserts these rounding postings on all transactions, and so maybe this method can be deprecated if we do so. Args: entry: An instance of a Transaction. account_rounding: A string, the name of the rounding account that absorbs residuals / rounding errors. Returns: A possibly new, modified entry with a new posting. If a residual was not needed - the transaction already balanced perfectly - no new leg is inserted.
Here is the function:
def fill_residual_posting(entry, account_rounding):
"""If necessary, insert a posting to absorb the residual.
This makes the transaction balance exactly.
Note: This was developed in order to tweak transactions before exporting
them to Ledger. A better method would be to enable the feature that
automatically inserts these rounding postings on all transactions, and so
maybe this method can be deprecated if we do so.
Args:
entry: An instance of a Transaction.
account_rounding: A string, the name of the rounding account that
absorbs residuals / rounding errors.
Returns:
A possibly new, modified entry with a new posting. If a residual
was not needed - the transaction already balanced perfectly - no new
leg is inserted.
"""
residual = compute_residual(entry.postings)
if not residual.is_empty():
new_postings = list(entry.postings)
new_postings.extend(get_residual_postings(residual, account_rounding))
entry = entry._replace(postings=new_postings)
return entry | If necessary, insert a posting to absorb the residual. This makes the transaction balance exactly. Note: This was developed in order to tweak transactions before exporting them to Ledger. A better method would be to enable the feature that automatically inserts these rounding postings on all transactions, and so maybe this method can be deprecated if we do so. Args: entry: An instance of a Transaction. account_rounding: A string, the name of the rounding account that absorbs residuals / rounding errors. Returns: A possibly new, modified entry with a new posting. If a residual was not needed - the transaction already balanced perfectly - no new leg is inserted. |
3,046 | from decimal import Decimal
from beancount.core.number import MISSING
from beancount.core.amount import Amount
from beancount.core.position import Cost
from beancount.core.position import Position
from beancount.core import prices
def convert_amount(amt, target_currency, price_map, date=None, via=None):
"""Return the market value of an Amount in a particular currency.
In addition, if a conversion rate isn't available, you can provide a list of
currencies to attempt to synthesize a rate for via implied rates.
Args:
amt: An instance of Amount.
target_currency: The target currency to convert to.
price_map: A dict of prices, as built by prices.build_price_map().
date: A datetime.date instance to evaluate the value at, or None.
via: A list of currencies to attempt to synthesize an implied rate if the
direct conversion fails.
Returns:
An Amount, either with a successful value currency conversion, or if we
could not convert the value, the amount itself, unmodified.
"""
# First, attempt to convert directly. This should be the most
# straightforward conversion.
base_quote = (amt.currency, target_currency)
_, rate = prices.get_price(price_map, base_quote, date)
if rate is not None:
# On success, just make the conversion directly.
return Amount(amt.number * rate, target_currency)
elif via:
assert isinstance(via, (tuple, list))
# A price is unavailable, attempt to convert via cost/price currency
# hop, if the value currency isn't the target currency.
for implied_currency in via:
if implied_currency == target_currency:
continue
base_quote1 = (amt.currency, implied_currency)
_, rate1 = prices.get_price(price_map, base_quote1, date)
if rate1 is not None:
base_quote2 = (implied_currency, target_currency)
_, rate2 = prices.get_price(price_map, base_quote2, date)
if rate2 is not None:
return Amount(amt.number * rate1 * rate2, target_currency)
# We failed to infer a conversion rate; return the amt.
return amt
Cost = NamedTuple('Cost', [
('number', Decimal),
('currency', str),
('date', datetime.date),
('label', Optional[str])])
The provided code snippet includes necessary dependencies for implementing the `convert_position` function. Write a Python function `def convert_position(pos, target_currency, price_map, date=None)` to solve the following problem:
Return the market value of a Position or Posting in a particular currency. In addition, if the rate from the position's currency to target_currency isn't available, an attempt is made to convert from its cost currency, if one is available. Args: pos: An instance of Position or Posting, equivalently. target_currency: The target currency to convert to. price_map: A dict of prices, as built by prices.build_price_map(). date: A datetime.date instance to evaluate the value at, or None. Returns: An Amount, either with a successful value currency conversion, or if we could not convert the value, just the units, unmodified. (See get_value() above for details.)
Here is the function:
def convert_position(pos, target_currency, price_map, date=None):
"""Return the market value of a Position or Posting in a particular currency.
In addition, if the rate from the position's currency to target_currency
isn't available, an attempt is made to convert from its cost currency, if
one is available.
Args:
pos: An instance of Position or Posting, equivalently.
target_currency: The target currency to convert to.
price_map: A dict of prices, as built by prices.build_price_map().
date: A datetime.date instance to evaluate the value at, or None.
Returns:
An Amount, either with a successful value currency conversion, or if we
could not convert the value, just the units, unmodified. (See get_value()
above for details.)
"""
cost = pos.cost
value_currency = (
(isinstance(cost, Cost) and cost.currency) or
(hasattr(pos, 'price') and pos.price and pos.price.currency) or
None)
return convert_amount(pos.units, target_currency, price_map,
date=date, via=(value_currency,)) | Return the market value of a Position or Posting in a particular currency. In addition, if the rate from the position's currency to target_currency isn't available, an attempt is made to convert from its cost currency, if one is available. Args: pos: An instance of Position or Posting, equivalently. target_currency: The target currency to convert to. price_map: A dict of prices, as built by prices.build_price_map(). date: A datetime.date instance to evaluate the value at, or None. Returns: An Amount, either with a successful value currency conversion, or if we could not convert the value, just the units, unmodified. (See get_value() above for details.) |
3,047 | import re
from decimal import Decimal
from typing import NamedTuple, Optional
from beancount.core.display_context import DEFAULT_FORMATTER
from beancount.core.number import ZERO
from beancount.core.number import MISSING
from beancount.core.number import D
class Amount(_Amount):
"""An 'Amount' represents a number of a particular unit of something.
It's essentially a typed number, with corresponding manipulation operations
defined on it.
"""
__slots__ = () # Prevent the creation of new attributes.
valid_types_number = (Decimal, type, type(None))
valid_types_currency = (str, type, type(None))
def __new__(cls, number, currency):
"""Constructor from a number and currency.
Args:
number: A Decimal instance.
currency: A string, the currency symbol to use.
"""
assert isinstance(number, Amount.valid_types_number), repr(number)
assert isinstance(currency, Amount.valid_types_currency), repr(currency)
return _Amount.__new__(cls, number, currency)
def to_string(self, dformat=DEFAULT_FORMATTER):
"""Convert an Amount instance to a printable string.
Args:
dformat: An instance of DisplayFormatter.
Returns:
A formatted string of the quantized amount and symbol.
"""
if isinstance(self.number, Decimal):
number_fmt = dformat.format(self.number, self.currency)
elif self.number is MISSING:
number_fmt = ''
else:
number_fmt = str(self.number)
return "{} {}".format(number_fmt, self.currency)
def __str__(self):
"""Convert an Amount instance to a printable string with the defaults.
Returns:
A formatted string of the quantized amount and symbol.
"""
return self.to_string()
__repr__ = __str__
def __bool__(self):
"""Boolean predicate returns true if the number is non-zero.
Returns:
A boolean, true if non-zero number.
"""
return self.number != ZERO
def __eq__(self, other):
"""Equality predicate. Returns true if both number and currency are equal.
Returns:
A boolean.
"""
if other is None:
return False
return (self.number, self.currency) == (other.number, other.currency)
def __lt__(self, other):
"""Ordering comparison. This is used in the sorting key of positions.
Args:
other: An instance of Amount.
Returns:
True if this is less than the other Amount.
"""
return sortkey(self) < sortkey(other)
def __hash__(self):
"""A hashing function for amounts. The hash includes the currency.
Returns:
An integer, the hash for this amount.
"""
return hash((self.number, self.currency))
def __neg__(self):
"""Return the negative of this amount.
Returns:
A new instance of Amount, with the negative number of units.
"""
return Amount(-self.number, self.currency)
def from_string(string):
"""Create an amount from a string.
This is a miniature parser used for building tests.
Args:
string: A string of <number> <currency>.
Returns:
A new instance of Amount.
"""
match = re.match(r'\s*([-+]?[0-9.]+)\s+({currency})'.format(currency=CURRENCY_RE),
string)
if not match:
raise ValueError("Invalid string for amount: '{}'".format(string))
number, currency = match.group(1, 2)
return Amount(D(number), currency)
The provided code snippet includes necessary dependencies for implementing the `div` function. Write a Python function `def div(amount, number)` to solve the following problem:
Divide the given amount by a number. Args: amount: An instance of Amount. number: A decimal number. Returns: An Amount, with the same currency, but with amount units divided by 'number'.
Here is the function:
def div(amount, number):
"""Divide the given amount by a number.
Args:
amount: An instance of Amount.
number: A decimal number.
Returns:
An Amount, with the same currency, but with amount units divided by 'number'.
"""
assert isinstance(amount.number, Decimal), (
"Amount's number is not a Decimal instance: {}".format(amount.number))
assert isinstance(number, Decimal), (
"Number is not a Decimal instance: {}".format(number))
return Amount(amount.number / number, amount.currency) | Divide the given amount by a number. Args: amount: An instance of Amount. number: A decimal number. Returns: An Amount, with the same currency, but with amount units divided by 'number'. |
3,048 | import builtins
import datetime
import enum
import sys
from decimal import Decimal
from typing import Any, Dict, List, NamedTuple, Optional, Set, Union
from beancount.core.amount import Amount
from beancount.core.number import D
from beancount.core.position import Cost
from beancount.core.position import CostSpec
from beancount.core.account import has_component
from beancount.utils.bisect_key import bisect_left_with_key
class Posting(NamedTuple):
"""
Postings are contained in Transaction entries. These represent the individual
legs of a transaction. Note: a posting may only appear within a single entry
(multiple transactions may not share a Posting instance), and that's what the
entry field should be set to.
Attributes:
account: A string, the account that is modified by this posting.
units: An Amount, the units of the position.
cost: A Cost or CostSpec instances, the units of the position.
price: An Amount, the price at which the position took place, or
None, where not relevant. Providing a price member to a posting
automatically adds a price in the prices database at the date of the
transaction.
flag: An optional flag, a one-character string or None, which is to be
associated with the posting. Most postings don't have a flag, but it can
be convenient to mark a particular posting as problematic or pending to
be reconciled for a future import of its account.
meta: A dict of strings to values, the metadata that was attached
specifically to that posting, or None, if not provided. In practice, most
of the instances will be unlikely to have metadata.
"""
account: Account
units: Amount
cost: Optional[Union[Cost, CostSpec]]
price: Optional[Amount]
flag: Optional[Flag]
meta: Optional[Meta]
class Amount(_Amount):
"""An 'Amount' represents a number of a particular unit of something.
It's essentially a typed number, with corresponding manipulation operations
defined on it.
"""
__slots__ = () # Prevent the creation of new attributes.
valid_types_number = (Decimal, type, type(None))
valid_types_currency = (str, type, type(None))
def __new__(cls, number, currency):
"""Constructor from a number and currency.
Args:
number: A Decimal instance.
currency: A string, the currency symbol to use.
"""
assert isinstance(number, Amount.valid_types_number), repr(number)
assert isinstance(currency, Amount.valid_types_currency), repr(currency)
return _Amount.__new__(cls, number, currency)
def to_string(self, dformat=DEFAULT_FORMATTER):
"""Convert an Amount instance to a printable string.
Args:
dformat: An instance of DisplayFormatter.
Returns:
A formatted string of the quantized amount and symbol.
"""
if isinstance(self.number, Decimal):
number_fmt = dformat.format(self.number, self.currency)
elif self.number is MISSING:
number_fmt = ''
else:
number_fmt = str(self.number)
return "{} {}".format(number_fmt, self.currency)
def __str__(self):
"""Convert an Amount instance to a printable string with the defaults.
Returns:
A formatted string of the quantized amount and symbol.
"""
return self.to_string()
__repr__ = __str__
def __bool__(self):
"""Boolean predicate returns true if the number is non-zero.
Returns:
A boolean, true if non-zero number.
"""
return self.number != ZERO
def __eq__(self, other):
"""Equality predicate. Returns true if both number and currency are equal.
Returns:
A boolean.
"""
if other is None:
return False
return (self.number, self.currency) == (other.number, other.currency)
def __lt__(self, other):
"""Ordering comparison. This is used in the sorting key of positions.
Args:
other: An instance of Amount.
Returns:
True if this is less than the other Amount.
"""
return sortkey(self) < sortkey(other)
def __hash__(self):
"""A hashing function for amounts. The hash includes the currency.
Returns:
An integer, the hash for this amount.
"""
return hash((self.number, self.currency))
def __neg__(self):
"""Return the negative of this amount.
Returns:
A new instance of Amount, with the negative number of units.
"""
return Amount(-self.number, self.currency)
def from_string(string):
"""Create an amount from a string.
This is a miniature parser used for building tests.
Args:
string: A string of <number> <currency>.
Returns:
A new instance of Amount.
"""
match = re.match(r'\s*([-+]?[0-9.]+)\s+({currency})'.format(currency=CURRENCY_RE),
string)
if not match:
raise ValueError("Invalid string for amount: '{}'".format(string))
number, currency = match.group(1, 2)
return Amount(D(number), currency)
def D(strord=None):
"""Convert a string into a Decimal object.
This is used in parsing amounts from files in the importers. This is the
main function you should use to build all numbers the system manipulates
(never use floating-point in an accounting system). Commas are stripped and
ignored, as they are assumed to be thousands separators (the French comma
separator as decimal is not supported). This function just returns the
argument if it is already a Decimal object, for convenience.
Args:
strord: A string or Decimal instance.
Returns:
A Decimal instance.
"""
try:
# Note: try a map lookup and optimize performance here.
if strord is None or strord == '':
return Decimal()
elif isinstance(strord, str):
return Decimal(_CLEAN_NUMBER_RE.sub('', strord))
elif isinstance(strord, Decimal):
return strord
elif isinstance(strord, (int, float)):
return Decimal(strord)
else:
assert strord is None, "Invalid value to convert: {}".format(strord)
except Exception as exc:
raise ValueError("Impossible to create Decimal instance from {!s}: {}".format(
strord, exc)) from exc
The provided code snippet includes necessary dependencies for implementing the `create_simple_posting` function. Write a Python function `def create_simple_posting(entry, account, number, currency)` to solve the following problem:
Create a simple posting on the entry, with just a number and currency (no cost). Args: entry: The entry instance to add the posting to. account: A string, the account to use on the posting. number: A Decimal number or string to use in the posting's Amount. currency: A string, the currency for the Amount. Returns: An instance of Posting, and as a side-effect the entry has had its list of postings modified with the new Posting instance.
Here is the function:
def create_simple_posting(entry, account, number, currency):
"""Create a simple posting on the entry, with just a number and currency (no cost).
Args:
entry: The entry instance to add the posting to.
account: A string, the account to use on the posting.
number: A Decimal number or string to use in the posting's Amount.
currency: A string, the currency for the Amount.
Returns:
An instance of Posting, and as a side-effect the entry has had its list of
postings modified with the new Posting instance.
"""
if isinstance(account, str):
pass
if number is None:
units = None
else:
if not isinstance(number, Decimal):
number = D(number)
units = Amount(number, currency)
posting = Posting(account, units, None, None, None, None)
if entry is not None:
entry.postings.append(posting)
return posting | Create a simple posting on the entry, with just a number and currency (no cost). Args: entry: The entry instance to add the posting to. account: A string, the account to use on the posting. number: A Decimal number or string to use in the posting's Amount. currency: A string, the currency for the Amount. Returns: An instance of Posting, and as a side-effect the entry has had its list of postings modified with the new Posting instance. |
3,049 | import builtins
import datetime
import enum
import sys
from decimal import Decimal
from typing import Any, Dict, List, NamedTuple, Optional, Set, Union
from beancount.core.amount import Amount
from beancount.core.number import D
from beancount.core.position import Cost
from beancount.core.position import CostSpec
from beancount.core.account import has_component
from beancount.utils.bisect_key import bisect_left_with_key
class Posting(NamedTuple):
"""
Postings are contained in Transaction entries. These represent the individual
legs of a transaction. Note: a posting may only appear within a single entry
(multiple transactions may not share a Posting instance), and that's what the
entry field should be set to.
Attributes:
account: A string, the account that is modified by this posting.
units: An Amount, the units of the position.
cost: A Cost or CostSpec instances, the units of the position.
price: An Amount, the price at which the position took place, or
None, where not relevant. Providing a price member to a posting
automatically adds a price in the prices database at the date of the
transaction.
flag: An optional flag, a one-character string or None, which is to be
associated with the posting. Most postings don't have a flag, but it can
be convenient to mark a particular posting as problematic or pending to
be reconciled for a future import of its account.
meta: A dict of strings to values, the metadata that was attached
specifically to that posting, or None, if not provided. In practice, most
of the instances will be unlikely to have metadata.
"""
account: Account
units: Amount
cost: Optional[Union[Cost, CostSpec]]
price: Optional[Amount]
flag: Optional[Flag]
meta: Optional[Meta]
class Amount(_Amount):
"""An 'Amount' represents a number of a particular unit of something.
It's essentially a typed number, with corresponding manipulation operations
defined on it.
"""
__slots__ = () # Prevent the creation of new attributes.
valid_types_number = (Decimal, type, type(None))
valid_types_currency = (str, type, type(None))
def __new__(cls, number, currency):
"""Constructor from a number and currency.
Args:
number: A Decimal instance.
currency: A string, the currency symbol to use.
"""
assert isinstance(number, Amount.valid_types_number), repr(number)
assert isinstance(currency, Amount.valid_types_currency), repr(currency)
return _Amount.__new__(cls, number, currency)
def to_string(self, dformat=DEFAULT_FORMATTER):
"""Convert an Amount instance to a printable string.
Args:
dformat: An instance of DisplayFormatter.
Returns:
A formatted string of the quantized amount and symbol.
"""
if isinstance(self.number, Decimal):
number_fmt = dformat.format(self.number, self.currency)
elif self.number is MISSING:
number_fmt = ''
else:
number_fmt = str(self.number)
return "{} {}".format(number_fmt, self.currency)
def __str__(self):
"""Convert an Amount instance to a printable string with the defaults.
Returns:
A formatted string of the quantized amount and symbol.
"""
return self.to_string()
__repr__ = __str__
def __bool__(self):
"""Boolean predicate returns true if the number is non-zero.
Returns:
A boolean, true if non-zero number.
"""
return self.number != ZERO
def __eq__(self, other):
"""Equality predicate. Returns true if both number and currency are equal.
Returns:
A boolean.
"""
if other is None:
return False
return (self.number, self.currency) == (other.number, other.currency)
def __lt__(self, other):
"""Ordering comparison. This is used in the sorting key of positions.
Args:
other: An instance of Amount.
Returns:
True if this is less than the other Amount.
"""
return sortkey(self) < sortkey(other)
def __hash__(self):
"""A hashing function for amounts. The hash includes the currency.
Returns:
An integer, the hash for this amount.
"""
return hash((self.number, self.currency))
def __neg__(self):
"""Return the negative of this amount.
Returns:
A new instance of Amount, with the negative number of units.
"""
return Amount(-self.number, self.currency)
def from_string(string):
"""Create an amount from a string.
This is a miniature parser used for building tests.
Args:
string: A string of <number> <currency>.
Returns:
A new instance of Amount.
"""
match = re.match(r'\s*([-+]?[0-9.]+)\s+({currency})'.format(currency=CURRENCY_RE),
string)
if not match:
raise ValueError("Invalid string for amount: '{}'".format(string))
number, currency = match.group(1, 2)
return Amount(D(number), currency)
def D(strord=None):
"""Convert a string into a Decimal object.
This is used in parsing amounts from files in the importers. This is the
main function you should use to build all numbers the system manipulates
(never use floating-point in an accounting system). Commas are stripped and
ignored, as they are assumed to be thousands separators (the French comma
separator as decimal is not supported). This function just returns the
argument if it is already a Decimal object, for convenience.
Args:
strord: A string or Decimal instance.
Returns:
A Decimal instance.
"""
try:
# Note: try a map lookup and optimize performance here.
if strord is None or strord == '':
return Decimal()
elif isinstance(strord, str):
return Decimal(_CLEAN_NUMBER_RE.sub('', strord))
elif isinstance(strord, Decimal):
return strord
elif isinstance(strord, (int, float)):
return Decimal(strord)
else:
assert strord is None, "Invalid value to convert: {}".format(strord)
except Exception as exc:
raise ValueError("Impossible to create Decimal instance from {!s}: {}".format(
strord, exc)) from exc
Cost = NamedTuple('Cost', [
('number', Decimal),
('currency', str),
('date', datetime.date),
('label', Optional[str])])
The provided code snippet includes necessary dependencies for implementing the `create_simple_posting_with_cost` function. Write a Python function `def create_simple_posting_with_cost(entry, account, number, currency, cost_number, cost_currency)` to solve the following problem:
Create a simple posting on the entry, with just a number and currency (no cost). Args: entry: The entry instance to add the posting to. account: A string, the account to use on the posting. number: A Decimal number or string to use in the posting's Amount. currency: A string, the currency for the Amount. cost_number: A Decimal number or string to use for the posting's cost Amount. cost_currency: a string, the currency for the cost Amount. Returns: An instance of Posting, and as a side-effect the entry has had its list of postings modified with the new Posting instance.
Here is the function:
def create_simple_posting_with_cost(entry, account,
number, currency,
cost_number, cost_currency):
"""Create a simple posting on the entry, with just a number and currency (no cost).
Args:
entry: The entry instance to add the posting to.
account: A string, the account to use on the posting.
number: A Decimal number or string to use in the posting's Amount.
currency: A string, the currency for the Amount.
cost_number: A Decimal number or string to use for the posting's cost Amount.
cost_currency: a string, the currency for the cost Amount.
Returns:
An instance of Posting, and as a side-effect the entry has had its list of
postings modified with the new Posting instance.
"""
if isinstance(account, str):
pass
if not isinstance(number, Decimal):
number = D(number)
if cost_number and not isinstance(cost_number, Decimal):
cost_number = D(cost_number)
units = Amount(number, currency)
cost = Cost(cost_number, cost_currency, None, None)
posting = Posting(account, units, cost, None, None, None)
if entry is not None:
entry.postings.append(posting)
return posting | Create a simple posting on the entry, with just a number and currency (no cost). Args: entry: The entry instance to add the posting to. account: A string, the account to use on the posting. number: A Decimal number or string to use in the posting's Amount. currency: A string, the currency for the Amount. cost_number: A Decimal number or string to use for the posting's cost Amount. cost_currency: a string, the currency for the cost Amount. Returns: An instance of Posting, and as a side-effect the entry has had its list of postings modified with the new Posting instance. |
3,050 | import builtins
import datetime
import enum
import sys
from decimal import Decimal
from typing import Any, Dict, List, NamedTuple, Optional, Set, Union
from beancount.core.amount import Amount
from beancount.core.number import D
from beancount.core.position import Cost
from beancount.core.position import CostSpec
from beancount.core.account import has_component
from beancount.utils.bisect_key import bisect_left_with_key
class Transaction(NamedTuple):
"""
A transaction! This is the main type of object that we manipulate, and the
entire reason this whole project exists in the first place, because
representing these types of structures with a spreadsheet is difficult.
Attributes:
meta: See above.
date: See above.
flag: A single-character string or None. This user-specified string
represents some custom/user-defined state of the transaction. You can use
this for various purposes. Otherwise common, pre-defined flags are defined
under beancount.core.flags, to flags transactions that are automatically
generated.
payee: A free-form string that identifies the payee, or None, if absent.
narration: A free-form string that provides a description for the transaction.
All transactions have at least a narration string, this is never None.
tags: A set of tag strings (without the '#'), or EMPTY_SET.
links: A set of link strings (without the '^'), or EMPTY_SET.
postings: A list of Posting instances, the legs of this transaction. See the
doc under Posting above.
"""
meta: Meta
date: datetime.date
flag: Flag
payee: Optional[str]
narration: str
tags: Set
links: Set
postings: List[Posting]
def posting_has_conversion(posting):
"""Return true if this position involves a conversion.
A conversion is when there is a price attached to the amount but no cost.
This is used on transactions to convert between units.
Args:
posting: an instance of Posting
Return:
A boolean, true if this posting has a price conversion.
"""
return (posting.cost is None and
posting.price is not None)
The provided code snippet includes necessary dependencies for implementing the `transaction_has_conversion` function. Write a Python function `def transaction_has_conversion(transaction)` to solve the following problem:
Given a Transaction entry, return true if at least one of the postings has a price conversion (without an associated cost). These are the source of non-zero conversion balances. Args: transaction: an instance of a Transaction entry. Returns: A boolean, true if this transaction contains at least one posting with a price conversion.
Here is the function:
def transaction_has_conversion(transaction):
"""Given a Transaction entry, return true if at least one of
the postings has a price conversion (without an associated
cost). These are the source of non-zero conversion balances.
Args:
transaction: an instance of a Transaction entry.
Returns:
A boolean, true if this transaction contains at least one posting with a
price conversion.
"""
assert isinstance(transaction, Transaction), (
"Invalid type of entry for transaction: {}".format(transaction))
for posting in transaction.postings:
if posting_has_conversion(posting):
return True
return False | Given a Transaction entry, return true if at least one of the postings has a price conversion (without an associated cost). These are the source of non-zero conversion balances. Args: transaction: an instance of a Transaction entry. Returns: A boolean, true if this transaction contains at least one posting with a price conversion. |
3,051 | import builtins
import datetime
import enum
import sys
from decimal import Decimal
from typing import Any, Dict, List, NamedTuple, Optional, Set, Union
from beancount.core.amount import Amount
from beancount.core.number import D
from beancount.core.position import Cost
from beancount.core.position import CostSpec
from beancount.core.account import has_component
from beancount.utils.bisect_key import bisect_left_with_key
class TxnPosting(NamedTuple):
"""
A pair of a Posting and its parent Transaction. This is inserted as
temporaries in lists of postings-of-entries, which is the product of a
realization.
Attributes:
txn: The parent Transaction instance.
posting: The Posting instance.
"""
txn: Transaction
posting: Posting
The provided code snippet includes necessary dependencies for implementing the `get_entry` function. Write a Python function `def get_entry(posting_or_entry)` to solve the following problem:
Return the entry associated with the posting or entry. Args: entry: A TxnPosting or entry instance Returns: A datetime instance.
Here is the function:
def get_entry(posting_or_entry):
"""Return the entry associated with the posting or entry.
Args:
entry: A TxnPosting or entry instance
Returns:
A datetime instance.
"""
return (posting_or_entry.txn
if isinstance(posting_or_entry, TxnPosting)
else posting_or_entry) | Return the entry associated with the posting or entry. Args: entry: A TxnPosting or entry instance Returns: A datetime instance. |
3,052 | import builtins
import datetime
import enum
import sys
from decimal import Decimal
from typing import Any, Dict, List, NamedTuple, Optional, Set, Union
from beancount.core.amount import Amount
from beancount.core.number import D
from beancount.core.position import Cost
from beancount.core.position import CostSpec
from beancount.core.account import has_component
from beancount.utils.bisect_key import bisect_left_with_key
class Transaction(NamedTuple):
"""
A transaction! This is the main type of object that we manipulate, and the
entire reason this whole project exists in the first place, because
representing these types of structures with a spreadsheet is difficult.
Attributes:
meta: See above.
date: See above.
flag: A single-character string or None. This user-specified string
represents some custom/user-defined state of the transaction. You can use
this for various purposes. Otherwise common, pre-defined flags are defined
under beancount.core.flags, to flags transactions that are automatically
generated.
payee: A free-form string that identifies the payee, or None, if absent.
narration: A free-form string that provides a description for the transaction.
All transactions have at least a narration string, this is never None.
tags: A set of tag strings (without the '#'), or EMPTY_SET.
links: A set of link strings (without the '^'), or EMPTY_SET.
postings: A list of Posting instances, the legs of this transaction. See the
doc under Posting above.
"""
meta: Meta
date: datetime.date
flag: Flag
payee: Optional[str]
narration: str
tags: Set
links: Set
postings: List[Posting]
def has_component(account_name: Account, component: str) -> bool:
"""Return true if one of the account contains a given component.
Args:
account_name: A string, an account name.
component: A string, a component of an account name. For instance,
``Food`` in ``Expenses:Food:Restaurant``. All components are considered.
Returns:
Boolean: true if the component is in the account. Note that a component
name must be whole, that is ``NY`` is not in ``Expenses:Taxes:StateNY``.
"""
return bool(re.search('(^|:){}(:|$)'.format(component), account_name))
The provided code snippet includes necessary dependencies for implementing the `has_entry_account_component` function. Write a Python function `def has_entry_account_component(entry, component)` to solve the following problem:
Return true if one of the entry's postings has an account component. Args: entry: A Transaction entry. component: A string, a component of an account name. For instance, ``Food`` in ``Expenses:Food:Restaurant``. All components are considered. Returns: Boolean: true if the component is in the account. Note that a component name must be whole, that is ``NY`` is not in ``Expenses:Taxes:StateNY``.
Here is the function:
def has_entry_account_component(entry, component):
"""Return true if one of the entry's postings has an account component.
Args:
entry: A Transaction entry.
component: A string, a component of an account name. For instance,
``Food`` in ``Expenses:Food:Restaurant``. All components are considered.
Returns:
Boolean: true if the component is in the account. Note that a component
name must be whole, that is ``NY`` is not in ``Expenses:Taxes:StateNY``.
"""
return (isinstance(entry, Transaction) and
any(has_component(posting.account, component)
for posting in entry.postings)) | Return true if one of the entry's postings has an account component. Args: entry: A Transaction entry. component: A string, a component of an account name. For instance, ``Food`` in ``Expenses:Food:Restaurant``. All components are considered. Returns: Boolean: true if the component is in the account. Note that a component name must be whole, that is ``NY`` is not in ``Expenses:Taxes:StateNY``. |
3,053 | import builtins
import datetime
import enum
import sys
from decimal import Decimal
from typing import Any, Dict, List, NamedTuple, Optional, Set, Union
from beancount.core.amount import Amount
from beancount.core.number import D
from beancount.core.position import Cost
from beancount.core.position import CostSpec
from beancount.core.account import has_component
from beancount.utils.bisect_key import bisect_left_with_key
class Transaction(NamedTuple):
"""
A transaction! This is the main type of object that we manipulate, and the
entire reason this whole project exists in the first place, because
representing these types of structures with a spreadsheet is difficult.
Attributes:
meta: See above.
date: See above.
flag: A single-character string or None. This user-specified string
represents some custom/user-defined state of the transaction. You can use
this for various purposes. Otherwise common, pre-defined flags are defined
under beancount.core.flags, to flags transactions that are automatically
generated.
payee: A free-form string that identifies the payee, or None, if absent.
narration: A free-form string that provides a description for the transaction.
All transactions have at least a narration string, this is never None.
tags: A set of tag strings (without the '#'), or EMPTY_SET.
links: A set of link strings (without the '^'), or EMPTY_SET.
postings: A list of Posting instances, the legs of this transaction. See the
doc under Posting above.
"""
meta: Meta
date: datetime.date
flag: Flag
payee: Optional[str]
narration: str
tags: Set
links: Set
postings: List[Posting]
The provided code snippet includes necessary dependencies for implementing the `remove_account_postings` function. Write a Python function `def remove_account_postings(account, entries)` to solve the following problem:
Remove all postings with the given account. Args: account: A string, the account name whose postings we want to remove. Returns: A list of entries without the rounding postings.
Here is the function:
def remove_account_postings(account, entries):
"""Remove all postings with the given account.
Args:
account: A string, the account name whose postings we want to remove.
Returns:
A list of entries without the rounding postings.
"""
new_entries = []
for entry in entries:
if isinstance(entry, Transaction) and (
any(posting.account == account for posting in entry.postings)):
entry = entry._replace(postings=[posting
for posting in entry.postings
if posting.account != account])
new_entries.append(entry)
return new_entries | Remove all postings with the given account. Args: account: A string, the account name whose postings we want to remove. Returns: A list of entries without the rounding postings. |
3,054 | import builtins
import datetime
import enum
import sys
from decimal import Decimal
from typing import Any, Dict, List, NamedTuple, Optional, Set, Union
from beancount.core.amount import Amount
from beancount.core.number import D
from beancount.core.position import Cost
from beancount.core.position import CostSpec
from beancount.core.account import has_component
from beancount.utils.bisect_key import bisect_left_with_key
def bisect_left_with_key(sequence, value, key=None):
"""Find the last element before the given value in a sorted list.
Args:
sequence: A sorted sequence of elements.
value: The value to search for.
key: An optional function used to extract the value from the elements of
sequence.
Returns:
Return the index. May return None.
"""
if key is None:
key = lambda x: x # Identity.
lo = 0
hi = len(sequence)
while lo < hi:
mid = (lo + hi) // 2
if key(sequence[mid]) < value:
lo = mid + 1
else:
hi = mid
return lo
The provided code snippet includes necessary dependencies for implementing the `iter_entry_dates` function. Write a Python function `def iter_entry_dates(entries, date_begin, date_end)` to solve the following problem:
Iterate over the entries in a date window. Args: entries: A date-sorted list of dated directives. date_begin: A datetime.date instance, the first date to include. date_end: A datetime.date instance, one day beyond the last date. Yields: Instances of the dated directives, between the dates, and in the order in which they appear.
Here is the function:
def iter_entry_dates(entries, date_begin, date_end):
"""Iterate over the entries in a date window.
Args:
entries: A date-sorted list of dated directives.
date_begin: A datetime.date instance, the first date to include.
date_end: A datetime.date instance, one day beyond the last date.
Yields:
Instances of the dated directives, between the dates, and in the order in
which they appear.
"""
getdate = lambda entry: entry.date
index_begin = bisect_left_with_key(entries, date_begin, key=getdate)
index_end = bisect_left_with_key(entries, date_end, key=getdate)
for index in range(index_begin, index_end):
yield entries[index] | Iterate over the entries in a date window. Args: entries: A date-sorted list of dated directives. date_begin: A datetime.date instance, the first date to include. date_end: A datetime.date instance, one day beyond the last date. Yields: Instances of the dated directives, between the dates, and in the order in which they appear. |
3,055 | import re
import os
import unicodedata
from os import path
from typing import Any, Callable, Iterable, Iterator, List, Tuple
import regex
Account = str
sep = ':'
def split(account_name: Account) -> List[str]:
"""Split an account's name into its components.
Args:
account_name: A string, an account name.
Returns:
A list of strings, the components of the account name (without the separators).
"""
return account_name.split(sep)
The provided code snippet includes necessary dependencies for implementing the `leaf` function. Write a Python function `def leaf(account_name: Account) -> Account` to solve the following problem:
Get the name of the leaf of this account. Args: account_name: A string, the name of the account whose leaf name to return. Returns: A string, the name of the leaf of the account.
Here is the function:
def leaf(account_name: Account) -> Account:
"""Get the name of the leaf of this account.
Args:
account_name: A string, the name of the account whose leaf name to return.
Returns:
A string, the name of the leaf of the account.
"""
assert isinstance(account_name, str)
return account_name.split(sep)[-1] if account_name else None | Get the name of the leaf of this account. Args: account_name: A string, the name of the account whose leaf name to return. Returns: A string, the name of the leaf of the account. |
3,056 | import re
import os
import unicodedata
from os import path
from typing import Any, Callable, Iterable, Iterator, List, Tuple
import regex
Account = str
sep = ':'
def join(*components: Tuple[str]) -> Account:
"""Join the names with the account separator.
Args:
*components: Strings, the components of an account name.
Returns:
A string, joined in a single account name.
"""
return sep.join(components)
def split(account_name: Account) -> List[str]:
"""Split an account's name into its components.
Args:
account_name: A string, an account name.
Returns:
A list of strings, the components of the account name (without the separators).
"""
return account_name.split(sep)
The provided code snippet includes necessary dependencies for implementing the `commonprefix` function. Write a Python function `def commonprefix(accounts: Iterable[Account]) -> Account` to solve the following problem:
Return the common prefix of a list of account names. Args: accounts: A sequence of account name strings. Returns: A string, the common parent account. If none, returns an empty string.
Here is the function:
def commonprefix(accounts: Iterable[Account]) -> Account:
"""Return the common prefix of a list of account names.
Args:
accounts: A sequence of account name strings.
Returns:
A string, the common parent account. If none, returns an empty string.
"""
accounts_lists = [account_.split(sep)
for account_ in accounts]
# Note: the os.path.commonprefix() function just happens to work here.
# Inspect its code, and even the special case of no common prefix
# works well with str.join() below.
common_list = path.commonprefix(accounts_lists)
return sep.join(common_list) | Return the common prefix of a list of account names. Args: accounts: A sequence of account name strings. Returns: A string, the common parent account. If none, returns an empty string. |
3,057 | import re
import os
import unicodedata
from os import path
from typing import Any, Callable, Iterable, Iterator, List, Tuple
import regex
Account = str
def parent(account_name: Account) -> Account:
"""Return the name of the parent account of the given account.
Args:
account_name: A string, the name of the account whose parent to return.
Returns:
A string, the name of the parent account of this account.
"""
assert isinstance(account_name, str), account_name
if not account_name:
return None
components = account_name.split(sep)
components.pop(-1)
return sep.join(components)
The provided code snippet includes necessary dependencies for implementing the `parents` function. Write a Python function `def parents(account_name: Account) -> Iterator[Account]` to solve the following problem:
A generator of the names of the parents of this account, including this account. Args: account_name: The name of the account we want to start iterating from. Returns: A generator of account name strings.
Here is the function:
def parents(account_name: Account) -> Iterator[Account]:
"""A generator of the names of the parents of this account, including this account.
Args:
account_name: The name of the account we want to start iterating from.
Returns:
A generator of account name strings.
"""
while account_name:
yield account_name
account_name = parent(account_name) | A generator of the names of the parents of this account, including this account. Args: account_name: The name of the account we want to start iterating from. Returns: A generator of account name strings. |
3,058 | import copy
import datetime
import re
from decimal import Decimal
from typing import NamedTuple, Optional
from beancount.core.number import ZERO
from beancount.core.number import NUMBER_RE
from beancount.core.number import D
from beancount.core.amount import Amount
from beancount.core.amount import mul as amount_mul
from beancount.core.amount import abs as amount_abs
from beancount.core.amount import CURRENCY_RE
from beancount.core.display_context import DEFAULT_FORMATTER
class Position(_Position):
"""A 'Position' is a pair of units and optional cost.
This is used to track inventories.
Attributes:
units: An Amount, the number of units and its currency.
cost: A Cost that represents the lot, or None.
"""
__slots__ = () # Prevent the creation of new attributes.
# Allowed data types for lot.cost
cost_types = (Cost, CostSpec)
def __new__(cls, units, cost=None):
assert isinstance(units, Amount), (
"Expected an Amount for units; received '{}'".format(units))
assert cost is None or isinstance(cost, Position.cost_types), (
"Expected a Cost for cost; received '{}'".format(cost))
return _Position.__new__(cls, units, cost)
def __hash__(self):
"""Compute a hash for this position.
Returns:
A hash of this position object.
"""
return hash((self.units, self.cost))
def to_string(self, dformat=DEFAULT_FORMATTER, detail=True):
"""Render the position to a string.See to_string() for details.
"""
return to_string(self, dformat, detail)
def __str__(self):
"""Return a string representation of the position.
Returns:
A string, a printable representation of the position.
"""
return self.to_string()
__repr__ = __str__
def __eq__(self, other):
"""Equality comparison with another Position. The objects are considered equal
if both number and lot are matching, and if the number of units is zero
and the other position is None, that is also okay.
Args:
other: An instance of Position, or None.
Returns:
A boolean, true if the positions are equal.
"""
return (self.units.number == ZERO
if other is None
else (self.units == other.units and self.cost == other.cost))
def sortkey(self):
"""Return a key to sort positions by. This key depends on the order of the
currency of the lot (we want to order common currencies first) and the
number of units.
Returns:
A tuple, used to sort lists of positions.
"""
currency = self.units.currency
order_units = CURRENCY_ORDER.get(currency, NCURRENCIES + len(currency))
if self.cost is not None:
cost_number = self.cost.number
cost_currency = self.cost.currency
else:
cost_number = ZERO
cost_currency = ''
return (order_units, cost_number, cost_currency, self.units.number)
def __lt__(self, other):
"""A less-than comparison operator for positions.
Args:
other: Another instance of Position.
Returns:
True if this positions is smaller than the other position.
"""
return self.sortkey() < other.sortkey()
def __copy__(self):
"""Shallow copy, except for the lot, which can be shared. This is important for
performance reasons; a lot of time is spent here during balancing.
Returns:
A shallow copy of this position.
"""
# Note: We use Decimal() for efficiency.
return Position(copy.copy(self.units), copy.copy(self.cost))
def currency_pair(self):
"""Return the currency pair associated with this position.
Returns:
A pair of a currency string and a cost currency string or None.
"""
return (self.units.currency, self.cost.currency if self.cost else None)
def get_negative(self):
"""Get a copy of this position but with a negative number.
Returns:
An instance of Position which represents the inverse of this Position.
"""
# Note: We use Decimal() for efficiency.
return Position(-self.units, self.cost)
__neg__ = get_negative
def __abs__(self):
"""Return the absolute value of the position.
Returns:
An instance of Position with the absolute units.
"""
return Position(amount_abs(self.units), self.cost)
def __mul__(self, scalar):
"""Scale/multiply the contents of the position.
Args:
scalar: A Decimal.
Returns:
An instance of Inventory.
"""
return Position(amount_mul(self.units, scalar), self.cost)
def is_negative_at_cost(self):
"""Return true if the position is held at cost and negative.
Returns:
A boolean.
"""
return (self.units.number < ZERO and self.cost is not None)
def from_string(string):
"""Create a position from a string specification.
This is a miniature parser used for building tests.
Args:
string: A string of <number> <currency> with an optional {<number>
<currency>} for the cost, similar to the parser syntax.
Returns:
A new instance of Position.
"""
match = re.match(
(r'\s*({})\s+({})'
r'(?:\s+{{([^}}]*)}})?'
r'\s*$').format(NUMBER_RE, CURRENCY_RE),
string)
if not match:
raise ValueError("Invalid string for position: '{}'".format(string))
number = D(match.group(1))
currency = match.group(2)
# Parse a cost expression.
cost_number = None
cost_currency = None
date = None
label = None
cost_expression = match.group(3)
if match.group(3):
expressions = [expr.strip() for expr in re.split('[,/]', cost_expression)]
for expr in expressions:
# Match a compound number.
match = re.match(
r'({NUMBER_RE})\s*(?:#\s*({NUMBER_RE}))?\s+({CURRENCY_RE})$'
.format(NUMBER_RE=NUMBER_RE, CURRENCY_RE=CURRENCY_RE),
expr
)
if match:
per_number, total_number, cost_currency = match.group(1, 2, 3)
per_number = D(per_number) if per_number else ZERO
total_number = D(total_number) if total_number else ZERO
if total_number:
# Calculate the per-unit cost.
total = number * per_number + total_number
per_number = total / number
cost_number = per_number
continue
# Match a date.
match = re.match(r'(\d\d\d\d)[-/](\d\d)[-/](\d\d)$', expr)
if match:
date = datetime.date(*map(int, match.group(1, 2, 3)))
continue
# Match a label.
match = re.match(r'"([^"]+)*"$', expr)
if match:
label = match.group(1)
continue
# Match a merge-cost marker.
match = re.match(r'\*$', expr)
if match:
raise ValueError("Merge-code not supported in string constructor.")
raise ValueError("Invalid cost component: '{}'".format(expr))
cost = Cost(cost_number, cost_currency, date, label)
else:
cost = None
return Position(Amount(number, currency), cost)
def from_amounts(units, cost_amount=None):
"""Create a position from an amount and a cost.
Args:
amount: An amount, that represents the number of units and the lot currency.
cost_amount: If not None, represents the cost amount.
Returns:
A Position instance.
"""
assert cost_amount is None or isinstance(cost_amount, Amount), (
"Invalid type for cost: {}".format(cost_amount))
cost = (Cost(cost_amount.number, cost_amount.currency, None, None)
if cost_amount else
None)
return Position(units, cost)
The provided code snippet includes necessary dependencies for implementing the `get_position` function. Write a Python function `def get_position(posting)` to solve the following problem:
Build a Position instance from a Posting instance. Args: posting: An instance of Posting. Returns: An instance of Position.
Here is the function:
def get_position(posting):
"""Build a Position instance from a Posting instance.
Args:
posting: An instance of Posting.
Returns:
An instance of Position.
"""
return Position(posting.units, posting.cost) | Build a Position instance from a Posting instance. Args: posting: An instance of Posting. Returns: An instance of Position. |
3,059 | import re
from collections import namedtuple
from typing import Tuple
from beancount.core import account
from beancount.core.account import Account
AccountTypes = namedtuple('AccountTypes', "assets liabilities equity income expenses")
def get_account_type(account_name: Account):
"""Return the type of this account's name.
Warning: No check is made on the validity of the account type. This merely
returns the root account of the corresponding account name.
Args:
account_name: A string, the name of the account whose type is to return.
Returns:
A string, the type of the account in 'account_name'.
"""
assert isinstance(account_name, str), "Account is not a string: {}".format(account_name)
return account.split(account_name)[0]
Account = str
The provided code snippet includes necessary dependencies for implementing the `get_account_sort_key` function. Write a Python function `def get_account_sort_key(account_types: AccountTypes, account_name: Account) -> Tuple[str, Account]` to solve the following problem:
Return a tuple that can be used to order/sort account names. Args: account_types: An instance of AccountTypes, a tuple of account type names. Returns: An object to use as the 'key' argument to the sort function.
Here is the function:
def get_account_sort_key(account_types: AccountTypes,
account_name: Account) -> Tuple[str, Account]:
"""Return a tuple that can be used to order/sort account names.
Args:
account_types: An instance of AccountTypes, a tuple of account type names.
Returns:
An object to use as the 'key' argument to the sort function.
"""
return (account_types.index(get_account_type(account_name)), account_name) | Return a tuple that can be used to order/sort account names. Args: account_types: An instance of AccountTypes, a tuple of account type names. Returns: An object to use as the 'key' argument to the sort function. |
3,060 | import re
from collections import namedtuple
from typing import Tuple
from beancount.core import account
from beancount.core.account import Account
Account = str
The provided code snippet includes necessary dependencies for implementing the `is_account_type` function. Write a Python function `def is_account_type(account_type: str, account_name: Account) -> bool` to solve the following problem:
Return the type of this account's name. Warning: No check is made on the validity of the account type. This merely returns the root account of the corresponding account name. Args: account_type: A string, the prefix type of the account. account_name: A string, the name of the account whose type is to return. Returns: A boolean, true if the account is of the given type.
Here is the function:
def is_account_type(account_type: str, account_name: Account) -> bool:
"""Return the type of this account's name.
Warning: No check is made on the validity of the account type. This merely
returns the root account of the corresponding account name.
Args:
account_type: A string, the prefix type of the account.
account_name: A string, the name of the account whose type is to return.
Returns:
A boolean, true if the account is of the given type.
"""
return bool(re.match('^{}{}'.format(account_type, account.sep), account_name)) | Return the type of this account's name. Warning: No check is made on the validity of the account type. This merely returns the root account of the corresponding account name. Args: account_type: A string, the prefix type of the account. account_name: A string, the name of the account whose type is to return. Returns: A boolean, true if the account is of the given type. |
3,061 | import re
from collections import namedtuple
from typing import Tuple
from beancount.core import account
from beancount.core.account import Account
Account = str
The provided code snippet includes necessary dependencies for implementing the `is_root_account` function. Write a Python function `def is_root_account(account_name: Account) -> bool` to solve the following problem:
Return true if the account name is a root account. This function does not verify whether the account root is a valid one, just that it is a root account or not. Args: account_name: A string, the name of the account to check for. Returns: A boolean, true if the account is root account.
Here is the function:
def is_root_account(account_name: Account) -> bool:
"""Return true if the account name is a root account.
This function does not verify whether the account root is a valid
one, just that it is a root account or not.
Args:
account_name: A string, the name of the account to check for.
Returns:
A boolean, true if the account is root account.
"""
assert isinstance(account_name, str), "Account is not a string: {}".format(account_name)
return (account_name and
bool(re.match(r'([A-Z][A-Za-z0-9\-]+)$', account_name))) | Return true if the account name is a root account. This function does not verify whether the account root is a valid one, just that it is a root account or not. Args: account_name: A string, the name of the account to check for. Returns: A boolean, true if the account is root account. |
3,062 | import re
from collections import namedtuple
from typing import Tuple
from beancount.core import account
from beancount.core.account import Account
AccountTypes = namedtuple('AccountTypes', "assets liabilities equity income expenses")
def get_account_type(account_name: Account):
"""Return the type of this account's name.
Warning: No check is made on the validity of the account type. This merely
returns the root account of the corresponding account name.
Args:
account_name: A string, the name of the account whose type is to return.
Returns:
A string, the type of the account in 'account_name'.
"""
assert isinstance(account_name, str), "Account is not a string: {}".format(account_name)
return account.split(account_name)[0]
Account = str
The provided code snippet includes necessary dependencies for implementing the `is_equity_account` function. Write a Python function `def is_equity_account(account_name: Account, account_types: AccountTypes) -> bool` to solve the following problem:
Return true if the given account is an equity account. Args: account_name: A string, an account name. account_types: An instance of AccountTypes. Returns: A boolean, true if the account is an equity account.
Here is the function:
def is_equity_account(account_name: Account, account_types: AccountTypes) -> bool:
"""Return true if the given account is an equity account.
Args:
account_name: A string, an account name.
account_types: An instance of AccountTypes.
Returns:
A boolean, true if the account is an equity account.
"""
assert isinstance(account_name, str), "Account is not a string: {}".format(account_name)
assert isinstance(account_types, AccountTypes), (
"Account types has invalid type: {}".format(account_types))
account_type = get_account_type(account_name)
return account_type == account_types.equity | Return true if the given account is an equity account. Args: account_name: A string, an account name. account_types: An instance of AccountTypes. Returns: A boolean, true if the account is an equity account. |
3,063 | import re
from collections import namedtuple
from typing import Tuple
from beancount.core import account
from beancount.core.account import Account
AccountTypes = namedtuple('AccountTypes', "assets liabilities equity income expenses")
def get_account_type(account_name: Account):
"""Return the type of this account's name.
Warning: No check is made on the validity of the account type. This merely
returns the root account of the corresponding account name.
Args:
account_name: A string, the name of the account whose type is to return.
Returns:
A string, the type of the account in 'account_name'.
"""
assert isinstance(account_name, str), "Account is not a string: {}".format(account_name)
return account.split(account_name)[0]
Account = str
The provided code snippet includes necessary dependencies for implementing the `is_inverted_account` function. Write a Python function `def is_inverted_account(account_name: Account, account_types: AccountTypes) -> bool` to solve the following problem:
Return true if the given account has inverted signs. An inverted sign is the inverse as you'd expect in an external report, i.e., with all positive signs expected. Args: account_name: A string, an account name. account_types: An instance of AccountTypes. Returns: A boolean, true if the account has an inverted sign.
Here is the function:
def is_inverted_account(account_name: Account, account_types: AccountTypes) -> bool:
"""Return true if the given account has inverted signs.
An inverted sign is the inverse as you'd expect in an external report, i.e.,
with all positive signs expected.
Args:
account_name: A string, an account name.
account_types: An instance of AccountTypes.
Returns:
A boolean, true if the account has an inverted sign.
"""
assert isinstance(account_name, str), "Account is not a string: {}".format(account_name)
assert isinstance(account_types, AccountTypes), (
"Account types has invalid type: {}".format(account_types))
account_type = get_account_type(account_name)
return account_type in (account_types.liabilities,
account_types.income,
account_types.equity) | Return true if the given account has inverted signs. An inverted sign is the inverse as you'd expect in an external report, i.e., with all positive signs expected. Args: account_name: A string, an account name. account_types: An instance of AccountTypes. Returns: A boolean, true if the account has an inverted sign. |
3,064 | import re
from collections import namedtuple
from typing import Tuple
from beancount.core import account
from beancount.core.account import Account
AccountTypes = namedtuple('AccountTypes', "assets liabilities equity income expenses")
DEFAULT_ACCOUNT_TYPES = AccountTypes("Assets",
"Liabilities",
"Equity",
"Income",
"Expenses")
def get_account_type(account_name: Account):
"""Return the type of this account's name.
Warning: No check is made on the validity of the account type. This merely
returns the root account of the corresponding account name.
Args:
account_name: A string, the name of the account whose type is to return.
Returns:
A string, the type of the account in 'account_name'.
"""
assert isinstance(account_name, str), "Account is not a string: {}".format(account_name)
return account.split(account_name)[0]
Account = str
The provided code snippet includes necessary dependencies for implementing the `get_account_sign` function. Write a Python function `def get_account_sign(account_name: Account, account_types: AccountTypes=None) -> int` to solve the following problem:
Return the sign of the normal balance of a particular account. Args: account_name: A string, the name of the account whose sign is to return. account_types: An optional instance of the current account_types. Returns: +1 or -1, depending on the account's type.
Here is the function:
def get_account_sign(account_name: Account, account_types: AccountTypes=None) -> int:
"""Return the sign of the normal balance of a particular account.
Args:
account_name: A string, the name of the account whose sign is to return.
account_types: An optional instance of the current account_types.
Returns:
+1 or -1, depending on the account's type.
"""
if account_types is None:
account_types = DEFAULT_ACCOUNT_TYPES
assert isinstance(account_name, str), "Account is not a string: {}".format(account_name)
account_type = get_account_type(account_name)
return (+1
if account_type in (account_types.assets,
account_types.expenses)
else -1) | Return the sign of the normal balance of a particular account. Args: account_name: A string, the name of the account whose sign is to return. account_types: An optional instance of the current account_types. Returns: +1 or -1, depending on the account's type. |
3,065 | from collections import defaultdict
from collections import OrderedDict
from beancount.core.data import Transaction
from beancount.core.data import Open
from beancount.core.data import Close
from beancount.core.data import Commodity
from beancount.core import account
def get_accounts(entries):
"""Gather all the accounts references by a list of directives.
Args:
entries: A list of directive instances.
Returns:
A set of account strings.
"""
_, accounts_last = _GetAccounts.get_accounts_use_map(entries)
return accounts_last.keys()
The provided code snippet includes necessary dependencies for implementing the `get_account_components` function. Write a Python function `def get_account_components(entries)` to solve the following problem:
Gather all the account components available in the given directives. Args: entries: A list of directive instances. Returns: A list of strings, the unique account components, including the root account names.
Here is the function:
def get_account_components(entries):
"""Gather all the account components available in the given directives.
Args:
entries: A list of directive instances.
Returns:
A list of strings, the unique account components, including the root
account names.
"""
accounts = get_accounts(entries)
components = set()
for account_name in accounts:
components.update(account.split(account_name))
return sorted(components) | Gather all the account components available in the given directives. Args: entries: A list of directive instances. Returns: A list of strings, the unique account components, including the root account names. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.