Skip to content

Commit 158acdd

Browse files
authored
Add support for downcasting bf16 on TPUs (#523)
* Allow for downcast
1 parent f6df405 commit 158acdd

5 files changed

Lines changed: 42 additions & 2 deletions

File tree

src/accelerate/accelerator.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,13 @@ def __init__(
238238
**kwargs,
239239
)
240240

241+
if (
242+
(mixed_precision != "bf16")
243+
and getattr(self.state, "downcast_bfloat", False)
244+
and (self.state.distributedType != DistributedType.TPU)
245+
):
246+
raise ValueError("Can only use `downcast_bf16` when using `mixed_precision='bf16'` and on a TPU")
247+
241248
if gradient_accumulation_steps > 1:
242249
if self.state.distributed_type == DistributedType.TPU:
243250
raise NotImplementedError(

src/accelerate/commands/config/cluster.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -293,11 +293,18 @@ def get_cluster_input():
293293
else:
294294
mixed_precision = "no"
295295

296+
downcast_bf16 = "no"
297+
if distributed_type == DistributedType.TPU and mixed_precision == "bf16":
298+
downcast_bf16 = _ask_field(
299+
"Should `torch.float` be cast as `bfloat16` and `torch.double` remain `float32` on TPUs?", default="no"
300+
)
301+
296302
return ClusterConfig(
297303
compute_environment=ComputeEnvironment.LOCAL_MACHINE,
298304
distributed_type=distributed_type,
299305
num_processes=num_processes,
300306
mixed_precision=mixed_precision,
307+
downcast_bf16=downcast_bf16,
301308
machine_rank=machine_rank,
302309
num_machines=num_machines,
303310
main_process_ip=main_process_ip,

src/accelerate/commands/config/config_args.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,8 @@ class ClusterConfig(BaseConfig):
143143
deepspeed_config: dict = None
144144
# args for fsdp
145145
fsdp_config: dict = None
146+
# args for TPU
147+
downcast_bf16: bool = False
146148

147149
def __post_init__(self):
148150
if self.deepspeed_config is None:

src/accelerate/commands/launch.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
get_launch_prefix,
3535
is_deepspeed_available,
3636
is_sagemaker_available,
37+
patch_environment,
3738
)
3839
from accelerate.utils.constants import DEEPSPEED_MULTINODE_LAUNCHERS
3940
from accelerate.utils.dataclasses import SageMakerDistributedType
@@ -217,6 +218,11 @@ def launch_command_parser(subparsers=None):
217218
default=None,
218219
help="The name of the main function to be executed in your script (only for TPU training).",
219220
)
221+
parser.add_argument(
222+
"--downcast_bf16",
223+
action="store_true",
224+
help="Whether when using bf16 precision on TPUs if both float and double tensors are cast to bfloat16 or if double tensors remain as float32",
225+
)
220226
parser.add_argument(
221227
"-m",
222228
"--module",
@@ -455,9 +461,19 @@ def deepspeed_launcher(args):
455461
def tpu_launcher(args):
456462
import torch_xla.distributed.xla_multiprocessing as xmp
457463

464+
current_env = {}
465+
458466
if args.no_python:
459467
raise ValueError("--no_python cannot be used with TPU launcher")
460468

469+
if args.mixed_precision == "bf16":
470+
if args.downcast_bf16:
471+
current_env["XLA_USE_BF16"] = "0"
472+
current_env["XLA_DOWNCAST_BF16"] = "1"
473+
else:
474+
current_env["XLA_USE_BF16"] = "1"
475+
current_env["XLA_DOWNCAST_BF16"] = "0"
476+
461477
if args.module:
462478
mod_name = args.training_script
463479
else:
@@ -477,7 +493,8 @@ def tpu_launcher(args):
477493
sys.argv = [mod.__file__] + args.training_script_args
478494

479495
main_function = getattr(mod, args.main_training_function)
480-
xmp.spawn(PrepareForLaunch(main_function), args=(), nprocs=args.num_processes)
496+
with patch_environment(**current_env):
497+
xmp.spawn(PrepareForLaunch(main_function), args=(), nprocs=args.num_processes)
481498

482499

483500
def _convert_nargs_to_dict(nargs: List[str]) -> Dict[str, str]:

src/accelerate/state.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,14 @@ def __init__(
115115
self.local_process_index = xm.get_local_ordinal()
116116
self.device = xm.xla_device()
117117
if mixed_precision == "bf16":
118-
os.environ["XLA_USE_BF16"] = str(1)
118+
if os.environ.get("DOWNCAST_BF16"):
119+
os.environ["XLA_USE_BF16"] = str(0)
120+
os.environ["XLA_DOWNCAST_BF16"] = str(1)
121+
self.downcast_bfloat = True
122+
else:
123+
os.environ["XLA_USE_BF16"] = str(1)
124+
os.environ["XLA_DOWNCAST_BF16"] = str(0)
125+
self.downcast_bfloat = False
119126
self.mixed_precision = mixed_precision
120127
elif os.environ.get("USE_DEEPSPEED", "false") == "true" and not cpu:
121128
assert (

0 commit comments

Comments
 (0)