Skip to content

Commit 70236e8

Browse files
committed
Integrate TorchFT
**Summary** This is a WIP TorchFT integration PR. **Current Issues** This doesn't work at this moment as there are hanged groups when a new group joins. **Issue 1:** ~Group 0 and group 1 will hang during the first `should_commit` after group 1 applying the pending state_dict from group 0.~ Fixed with: pytorch/torchft#83 **Issue 2:** ~Group 0 and group 1 will pass the `should_commit` but group 0 needs healing which is wrong and the healing process will cause another hang.~ Fixed with: pytorch/torchft#83 **Issue 3:** ~The byproduct of issue 1 and issue 2: group 1 will continue to print out~ ``` [rank0]:devgpu051:76838:80357 [0] misc/socket.cc:50 NCCL WARN socketProgress: Connection closed by remote peer devgpu051.cln3.svc.fbinfra.net<33618> ``` Fixed with pytorch/torchft#91 and several other fixes. **Issue 4:** When there are 3 groups, everyone requests the state dict every step. ***How to reproduce?*** Using the `Reproduce steps` to run 2 groups, then add another group by modifying the command. Seems to be fixed, will need more tests. **Issue 5:** Hang will happen if using functional collective. ***How to reproduce?*** Pull the latest version of this PR and comment out line 41 and uncomment line 42 in `torchtitan/utils.py` **Reproduce steps:** 1. Patch TorchFT with pytorch/torchft#82 2. Execute lighthouse 3. Execute the following command in one terminal: ``` TORCHFT_MANAGER_PORT=29520 REPLICA_GROUP_ID=0 CUDA_VISIBLE_DEVICES=0,1 NGPU=2 ./run_llama_train.sh --training.data_parallel_shard_degree=2 --experimental.enable_torchft --experimental.ft_replica_group_id=0 ``` 4. Wait 10 seconds, execute following command in another terminal: ``` TORCHFT_MANAGER_PORT=29522 REPLICA_GROUP_ID=1 CUDA_VISIBLE_DEVICES=2,3 NGPU=2 ./run_llama_train.sh --training.data_parallel_shard_degree=2 --experimental.enable_torchft --experimental.ft_replica_group_id=1 ``` ghstack-source-id: 65c0469403170606b755b415df0439e020fa3187 Pull Request resolved: #834
1 parent 03245d6 commit 70236e8

File tree

8 files changed

+269
-63
lines changed

8 files changed

+269
-63
lines changed

run_llama_train.sh

+4
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,11 @@ if [ $# -ne 0 ]; then
1919
overrides="$*"
2020
fi
2121

22+
TORCHFT_MANAGER_PORT=${TORCHFT_MANAGER_PORT:-"29512"}
23+
2224
PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True" \
25+
TORCHFT_LIGHTHOUSE=http://localhost:29510 \
26+
TORCHFT_MANAGER_PORT=${TORCHFT_MANAGER_PORT} \
2327
torchrun --nproc_per_node=${NGPU} --rdzv_backend c10d --rdzv_endpoint="localhost:0" \
2428
--local-ranks-filter ${LOG_RANK} --role rank --tee 3 \
2529
train.py --job.config_file ${CONFIG_FILE} $overrides

torchtitan/checkpoint.py

+117-50
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
import torch.distributed as dist
2020
import torch.distributed.checkpoint as dcp
2121
import torch.nn as nn
22+
from torch.distributed._state_dict_utils import _copy_state_dict, _create_cpu_state_dict
2223
from torch.distributed.checkpoint.state_dict import (
2324
get_model_state_dict,
2425
set_model_state_dict,
@@ -151,13 +152,18 @@ def __init__(
151152
lr_schedulers: LRSchedulersContainer,
152153
states: Dict[str, Any],
153154
job_config: JobConfig,
155+
ft_manager: Optional[Any] = None,
154156
) -> None:
155157
ckpt_config = job_config.checkpoint
156158
self.enable_checkpoint = ckpt_config.enable_checkpoint
157-
self.keep_latest_k = ckpt_config.keep_latest_k
159+
self.ft_manager = ft_manager
160+
self.enable_staging = (
161+
self.enable_checkpoint and async_mode == AsyncMode.ASYNC_WITH_PINNED_MEM
162+
) or self.ft_manager
158163

159-
if not self.enable_checkpoint:
164+
if not self.enable_checkpoint and self.ft_manager is None:
160165
return
166+
161167
"""
162168
Note: Pipeline Parallelism and Virtual Stages
163169
@@ -192,6 +198,13 @@ def __init__(
192198
}
193199
)
194200

201+
async_mode = ckpt_config.async_mode.lower()
202+
self.staging = False
203+
self.sending_to_checkpoint_mp = False
204+
self.staging_id = None
205+
self.cpu_offload_state_dict = None
206+
self.staging_stream = torch.cuda.Stream() if self.enable_staging else None
207+
195208
self.folder = os.path.join(job_config.job.dump_folder, ckpt_config.folder)
196209
self.interval_type = (
197210
IntervalType.SECONDS
@@ -206,6 +219,7 @@ def __init__(
206219
if async_mode == AsyncMode.ASYNC or self.interval_type == IntervalType.SECONDS:
207220
self.pg = dist.new_group(backend="gloo")
208221

222+
self.keep_latest_k = ckpt_config.keep_latest_k
209223
self.model_weights_only = ckpt_config.model_weights_only
210224
self.export_dtype = TORCH_DTYPE_MAP[ckpt_config.export_dtype]
211225
self.exclude_from_loading = ckpt_config.exclude_from_loading
@@ -230,10 +244,6 @@ def __init__(
230244
daemon=True,
231245
)
232246
self.mp.start()
233-
self.cpu_offload_state_dict = None
234-
self.staging = False
235-
self.staging_id = None
236-
self.staging_stream = torch.cuda.Stream()
237247
else:
238248
raise ValueError(f"Unkown checkpoint async_mode {ckpt_config.async_mode}")
239249

@@ -247,8 +257,61 @@ def __del__(self):
247257
self.mp.join()
248258

249259
def reset(self) -> None:
260+
# We need to stage the local state if another replicate joins during the
261+
# first step.
262+
if self.ft_manager:
263+
self.cpu_staging(None)
250264
self.begin_time = time.monotonic()
251265

266+
def _initialize_states(
267+
self,
268+
states: Dict[str, Any],
269+
dataloader: DataLoader,
270+
model_parts: List[nn.Module],
271+
optimizers: OptimizersContainer,
272+
lr_schedulers: LRSchedulersContainer,
273+
) -> None:
274+
"""
275+
Note: Pipeline Parallelism and Virtual Stages
276+
277+
1. Even for simple PP schedules, there is a separate optimizer each PP rank.
278+
rank0's optimizer would have a param_group[0] which refers to layers.0 in the
279+
original model. rank1's would _also_ have a param_group[0], since it's index based,
280+
but referring to layers.1.
281+
When saving, these collide and one of them is lost. Then when reloading, only one
282+
stage can restore its optimizer states, others will error.
283+
284+
The solution to this problem is optimizer flattening: it landed in #127071
285+
and is enabled in TorchTitan by passing the 'flatten_optimizer_state_dict'
286+
kwarg to DCP functions called in the OptimizerContainer.
287+
288+
2. With complex PP schedules, we have multiple model chunks per pp rank. This
289+
compounds challenge (1) by also requiring us to reason about multiple 'optim'
290+
objects locally.
291+
292+
We solve this in the Model and Optimizer wrapper classes by flattening the
293+
state dicts from each object into one state dict before saving/loading.
294+
We rely on the individual state_dicts to not collide, which is gauranteed for
295+
the model by correct pipeline splitting and for the optimizer by the flattening
296+
support described in (1).
297+
298+
3. LR schedulers also index model states like optimizers and would need to be
299+
flattened properly to support resharding. Unfortunately, the implementations of
300+
different lr_schedulers do not follow a clear pattern like optimizers do, so it's
301+
hard to write a generic 'flattener' utility.
302+
303+
TODO: This is currently unsolved and needs a fix.
304+
"""
305+
self.states = states
306+
self.states.update(
307+
{
308+
"model": ModelWrapper(model_parts),
309+
"optimizer": optimizers,
310+
"dataloader": dataloader,
311+
"lr_scheduler": lr_schedulers,
312+
}
313+
)
314+
252315
def _create_checkpoint_id(self, step: int) -> str:
253316
return os.path.join(self.folder, f"step-{step}")
254317

@@ -331,31 +394,8 @@ def _async_wait(self) -> None:
331394
self.async_future.result()
332395

333396
def _async_with_pinned_memory(self, checkpoint_id: str) -> None:
334-
try:
335-
from torch.distributed._state_dict_utils import (
336-
_copy_state_dict,
337-
_create_cpu_state_dict,
338-
)
339-
except ImportError as e:
340-
raise ImportError(
341-
"Please install the latest PyTorch nightly to use async checkpointing with pinned memory."
342-
) from e
343-
state_dict = dcp.state_dict_saver._stateful_to_state_dict(self.states)
344-
if self.cpu_offload_state_dict is None:
345-
logger.debug(f"Preparing the CPU memory, {time.monotonic()=}.:.2f")
346-
self.cpu_offload_state_dict = _create_cpu_state_dict(
347-
state_dict, pin_memory=True, share_memory=True
348-
)
349-
350-
logger.debug(f"Staging the state_dict, {time.monotonic()=}.:.2f")
351-
with torch.cuda.stream(self.staging_stream):
352-
self.cpu_offload_state_dict = _copy_state_dict(
353-
state_dict,
354-
self.cpu_offload_state_dict,
355-
non_blocking=True,
356-
)
357-
self.staging = True
358-
self.staging_id = checkpoint_id
397+
self.cpu_staging(checkpoint_id)
398+
self.sending_to_checkpoint_mp = True
359399

360400
def save(self, curr_step: int, force: bool = False) -> None:
361401
"""
@@ -365,6 +405,8 @@ def save(self, curr_step: int, force: bool = False) -> None:
365405
for initial seed checkpoint.
366406
"""
367407
if not self._should_save(curr_step, force):
408+
if self.ft_manager:
409+
self.cpu_staging(None)
368410
return
369411

370412
begin = time.monotonic()
@@ -393,26 +435,51 @@ def save(self, curr_step: int, force: bool = False) -> None:
393435
f"in {time.monotonic() - begin:.2f} seconds."
394436
)
395437

438+
def cpu_staging(self, checkpoint_id: Optional[str]) -> None:
439+
"""Offload state_dict to CPU memory"""
440+
state_dict = dcp.state_dict_saver._stateful_to_state_dict(self.states)
441+
if self.cpu_offload_state_dict is None:
442+
logger.debug(f"Preparing the CPU memory, {time.monotonic()=}.:.2f")
443+
self.cpu_offload_state_dict = _create_cpu_state_dict(
444+
state_dict, pin_memory=True, share_memory=True
445+
)
446+
447+
logger.debug(f"Staging the state_dict, {time.monotonic()=}.:.2f")
448+
with torch.cuda.stream(self.staging_stream):
449+
self.cpu_offload_state_dict = _copy_state_dict(
450+
state_dict,
451+
self.cpu_offload_state_dict,
452+
non_blocking=True,
453+
)
454+
self.staging = True
455+
self.staging_id = checkpoint_id
456+
457+
def wait_for_staging(self) -> None:
458+
if not self.staging_stream.query():
459+
self.staging_stream.synchronize()
460+
self.staging = False
461+
462+
def staging_results(self) -> Dict[str, Any]:
463+
self.maybe_wait_for_staging()
464+
return self.cpu_offload_state_dict
465+
396466
def maybe_wait_for_staging(self) -> None:
397-
if (
398-
self.enable_checkpoint
399-
and self.async_mode == AsyncMode.ASYNC_WITH_PINNED_MEM
400-
and self.staging
401-
):
402-
if not self.staging_stream.query():
403-
self.staging_stream.synchronize()
404-
405-
def sync_func():
406-
self.mp_queue_send.put_nowait(
407-
(self.cpu_offload_state_dict, self.staging_id)
408-
)
409-
410-
# This may be a faster way to do zero-overhead checkpointing staging
411-
# checkpointing but we need more thorough investigation before
412-
# swithing to this method.
413-
# self.my_thread = threading.Thread(target=func).start()
414-
sync_func()
415-
self.staging = False
467+
if self.enable_staging and self.staging:
468+
self.wait_for_staging()
469+
470+
if self.sending_to_checkpoint_mp:
471+
# Copy the sync staging result to another process.
472+
def sync_func():
473+
self.mp_queue_send.put_nowait(
474+
(self.cpu_offload_state_dict, self.staging_id)
475+
)
476+
477+
# This may be a faster way to do zero-overhead checkpointing staging
478+
# checkpointing but we need more thorough investigation before
479+
# swithing to this method.
480+
# self.my_thread = threading.Thread(target=func).start()
481+
sync_func()
482+
self.sending_to_checkpoint_mp = False
416483

417484
def load(self, step: int = -1) -> bool:
418485
if not self.enable_checkpoint:

torchtitan/config_manager.py

+13
Original file line numberDiff line numberDiff line change
@@ -631,6 +631,19 @@ def __init__(self):
631631
action="store_true",
632632
)
633633

634+
self.parser.add_argument(
635+
"--experimental.enable_torchft",
636+
action="store_true",
637+
help="Enable TorchFT integration.",
638+
)
639+
640+
self.parser.add_argument(
641+
"--experimental.ft_replica_group_id",
642+
type=int,
643+
default=-1,
644+
help="The FT replicate group of this run.",
645+
)
646+
634647
def to_dict(self):
635648
return self.args_dict
636649

torchtitan/ft.py

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import importlib
2+
from typing import Any, Callable, Optional
3+
4+
from torch.distributed._state_dict_utils import _copy_state_dict, _create_cpu_state_dict
5+
6+
from torchtitan.config_manager import JobConfig
7+
8+
if importlib.util.find_spec("torchft") is not None:
9+
import torchft as ft
10+
11+
has_torchft = True
12+
else:
13+
has_torchft = False
14+
15+
16+
def init_ft_manager(job: JobConfig) -> Optional["ft.Manager"]:
17+
"""
18+
Initialize the FT manager for the given job.
19+
"""
20+
if not job.experimental.enable_torchft:
21+
return None
22+
23+
if not has_torchft:
24+
raise ImportError("torchft is not installed. Please install it.")
25+
26+
pg = ft.ProcessGroupBabyNCCL()
27+
manager = ft.Manager(
28+
pg=pg,
29+
min_replica_size=1,
30+
load_state_dict=None,
31+
state_dict=None,
32+
use_async_quorum=True,
33+
replica_id=f"torchtitan_ft_{job.experimental.ft_replica_group_id}",
34+
)
35+
36+
return manager
37+
38+
39+
def set_ft_state_dict_fns(manager: Optional["ft.Manager"], ckpt_manager) -> None:
40+
"""
41+
Set the state dict for the given manager.
42+
"""
43+
if manager is None:
44+
return
45+
46+
def state_dict():
47+
ret = {}
48+
for k, v in ckpt_manager.staging_results().items():
49+
if k in {"model", "optimizer", "lr_schedulers"}:
50+
ret[k] = v
51+
return ret
52+
53+
def load_state_dict(state_dict):
54+
assert state_dict is not None
55+
for k, v in state_dict.items():
56+
ckpt_manager.states[k].load_state_dict(v)
57+
58+
manager.set_state_dict_fns(load_state_dict, state_dict)

torchtitan/optimizer.py

+33-6
Original file line numberDiff line numberDiff line change
@@ -177,8 +177,32 @@ def zero_grad(self) -> None:
177177
pass
178178

179179

180+
class FTOptimizersContainer(Optimizer):
181+
def __init__(
182+
self,
183+
model_parts: List[nn.Module],
184+
optimizer_kwargs: Dict[str, Any],
185+
name: str,
186+
ft_manager: Any,
187+
) -> None:
188+
import torchft as ft
189+
190+
super().__init__()
191+
192+
# Force to initialize the optimizer state so that `optim.step()`
193+
# won't be called by state_dict() and load_state_dict().
194+
_ = {
195+
k: v
196+
for sd in map(get_optimizer_state_dict, model_parts, self.optimizers)
197+
for k, v in sd.items()
198+
}
199+
self.optimizers = [ft.Optimizer(ft_manager, optim) for optim in self.optimizers]
200+
201+
180202
def build_optimizers(
181-
model_parts: List[nn.Module], job_config: JobConfig
203+
model_parts: List[nn.Module],
204+
job_config: JobConfig,
205+
ft_manager: Optional[Any] = None,
182206
) -> OptimizersContainer:
183207
"""Create a OptimizersContainer for the given model parts and job config.
184208
@@ -213,11 +237,14 @@ def build_optimizers(
213237
"foreach": not fused,
214238
}
215239

216-
return (
217-
OptimizersContainer(model_parts, optimizer_kwargs, name)
218-
if not optim_in_bwd
219-
else OptimizersInBackwardContainer(model_parts, optimizer_kwargs, name)
220-
)
240+
if optim_in_bwd and ft_manager:
241+
raise ValueError("TorchFT is not supported with optimizers in backward.")
242+
elif optim_in_bwd:
243+
return OptimizersInBackwardContainer(model_parts, optimizer_kwargs, name)
244+
elif ft_manager:
245+
return FTOptimizersContainer(model_parts, optimizer_kwargs, name, ft_manager)
246+
else:
247+
return OptimizersContainer(model_parts, optimizer_kwargs, name)
221248

222249

223250
class LRSchedulersContainer(Stateful):

0 commit comments

Comments
 (0)