2023-06-21 01:32:46 +00:00
|
|
|
import copy
|
2023-08-16 07:41:20 +00:00
|
|
|
import math
|
2023-07-10 02:48:53 +00:00
|
|
|
from contextlib import nullcontext
|
2023-08-03 09:50:15 +00:00
|
|
|
from typing import Any, Callable, Dict, List, Optional
|
2023-06-21 01:32:46 +00:00
|
|
|
|
2023-07-20 02:39:06 +00:00
|
|
|
import torch
|
2023-08-03 06:51:36 +00:00
|
|
|
import torch.distributed as dist
|
2023-08-03 09:50:15 +00:00
|
|
|
from torch import Tensor
|
|
|
|
from torch import distributed as dist
|
|
|
|
from torch.distributed import ProcessGroup
|
2023-07-20 02:39:06 +00:00
|
|
|
from torch.nn import Module
|
2023-08-03 09:50:15 +00:00
|
|
|
from torch.optim import Adam, Optimizer
|
2023-10-18 03:05:25 +00:00
|
|
|
from torch.testing import assert_close
|
2023-07-20 02:39:06 +00:00
|
|
|
|
2023-08-03 09:50:15 +00:00
|
|
|
from colossalai.booster import Booster
|
|
|
|
from colossalai.booster.plugin import HybridParallelPlugin
|
2023-08-16 08:11:57 +00:00
|
|
|
from colossalai.booster.plugin.hybrid_parallel_plugin import HybridParallelModule
|
2023-07-10 02:48:53 +00:00
|
|
|
from colossalai.lazy import LazyInitContext
|
2023-08-03 09:50:15 +00:00
|
|
|
from colossalai.pipeline.stage_manager import PipelineStageManager
|
2023-06-21 01:32:46 +00:00
|
|
|
from colossalai.shardformer import ShardConfig, ShardFormer
|
2023-08-03 06:51:36 +00:00
|
|
|
from colossalai.shardformer._utils import getattr_
|
2023-08-10 05:59:30 +00:00
|
|
|
from colossalai.shardformer.policies.auto_policy import Policy
|
2023-08-03 06:51:36 +00:00
|
|
|
from colossalai.tensor.d_tensor.api import is_customized_distributed_tensor, is_distributed_tensor
|
2023-06-21 01:32:46 +00:00
|
|
|
|
|
|
|
|
2023-09-19 06:20:26 +00:00
|
|
|
def build_model(
|
|
|
|
model_fn,
|
|
|
|
enable_fused_normalization=True,
|
|
|
|
enable_tensor_parallelism=True,
|
|
|
|
enable_flash_attention=False,
|
|
|
|
enable_jit_fused=False,
|
|
|
|
enable_sequence_parallelism=False,
|
|
|
|
use_lazy_init: bool = False,
|
|
|
|
):
|
2023-08-07 08:41:07 +00:00
|
|
|
# create new model
|
2023-07-10 02:48:53 +00:00
|
|
|
ctx = LazyInitContext() if use_lazy_init else nullcontext()
|
|
|
|
with ctx:
|
|
|
|
# create new model
|
|
|
|
org_model = model_fn()
|
|
|
|
model_copy = copy.deepcopy(org_model)
|
|
|
|
if use_lazy_init:
|
|
|
|
ctx.materialize(org_model)
|
2023-06-21 01:32:46 +00:00
|
|
|
# shard model
|
2023-09-19 06:20:26 +00:00
|
|
|
shard_config = ShardConfig(
|
|
|
|
enable_fused_normalization=enable_fused_normalization,
|
|
|
|
enable_tensor_parallelism=enable_tensor_parallelism,
|
|
|
|
enable_flash_attention=enable_flash_attention,
|
|
|
|
enable_jit_fused=enable_jit_fused,
|
|
|
|
enable_sequence_parallelism=enable_sequence_parallelism,
|
|
|
|
)
|
2023-08-07 08:41:07 +00:00
|
|
|
model_copy = copy.deepcopy(org_model)
|
2023-06-21 01:32:46 +00:00
|
|
|
shard_former = ShardFormer(shard_config=shard_config)
|
2023-07-05 06:30:17 +00:00
|
|
|
sharded_model, shared_params = shard_former.optimize(model_copy)
|
2023-07-10 02:48:53 +00:00
|
|
|
return org_model.cuda(), sharded_model.cuda()
|
2023-06-21 01:32:46 +00:00
|
|
|
|
|
|
|
|
2023-09-19 06:20:26 +00:00
|
|
|
def build_pipeline_model(
|
|
|
|
model_fn,
|
|
|
|
stage_manager=None,
|
|
|
|
enable_fused_normalization=False,
|
|
|
|
enable_tensor_parallelism=False,
|
|
|
|
use_lazy_init: bool = False,
|
|
|
|
policy: Optional[Policy] = None,
|
|
|
|
):
|
2023-07-10 05:58:58 +00:00
|
|
|
ctx = LazyInitContext() if use_lazy_init else nullcontext()
|
|
|
|
with ctx:
|
|
|
|
# create new model
|
|
|
|
org_model = model_fn()
|
|
|
|
model_copy = copy.deepcopy(org_model)
|
|
|
|
if use_lazy_init:
|
|
|
|
ctx.materialize(org_model)
|
|
|
|
|
|
|
|
# shard model
|
2023-09-19 06:20:26 +00:00
|
|
|
shard_config = ShardConfig(
|
|
|
|
enable_fused_normalization=enable_fused_normalization,
|
|
|
|
enable_tensor_parallelism=enable_tensor_parallelism,
|
|
|
|
pipeline_stage_manager=stage_manager,
|
|
|
|
)
|
2023-07-11 03:37:26 +00:00
|
|
|
|
2023-07-10 05:58:58 +00:00
|
|
|
shard_former = ShardFormer(shard_config=shard_config)
|
2023-08-04 06:55:31 +00:00
|
|
|
sharded_model, shared_params = shard_former.optimize(model_copy, policy=policy)
|
2023-07-10 05:58:58 +00:00
|
|
|
return org_model.cuda(), sharded_model.cuda()
|
|
|
|
|
|
|
|
|
2023-06-21 01:32:46 +00:00
|
|
|
def run_forward(original_model, sharded_model, data_gen_fn, output_transform_fn, loss_fn):
|
|
|
|
# prepare input
|
|
|
|
data = data_gen_fn()
|
|
|
|
data = {k: v.cuda() for k, v in data.items()}
|
|
|
|
# switch to train mode
|
|
|
|
original_model.train()
|
|
|
|
sharded_model.train()
|
|
|
|
# run forward
|
|
|
|
org_output = original_model(**data)
|
|
|
|
org_output = output_transform_fn(org_output)
|
|
|
|
org_loss = loss_fn(org_output)
|
|
|
|
|
|
|
|
shard_output = sharded_model(**data)
|
|
|
|
shard_output = output_transform_fn(shard_output)
|
|
|
|
shard_loss = loss_fn(shard_output)
|
2023-06-30 01:32:37 +00:00
|
|
|
return org_output, org_loss, shard_output, shard_loss
|
2023-07-20 02:39:06 +00:00
|
|
|
|
|
|
|
|
2023-09-19 06:20:26 +00:00
|
|
|
def check_state_dict(org_model: Module, sharded_model: Module, name: str = ""):
|
2023-07-20 02:39:06 +00:00
|
|
|
org_sd = org_model.state_dict()
|
|
|
|
shard_sd = sharded_model.state_dict()
|
|
|
|
for k, v in org_sd.items():
|
2023-09-19 06:20:26 +00:00
|
|
|
assert k in shard_sd, f"{name} {k} not in sharded model"
|
2023-07-20 02:39:06 +00:00
|
|
|
shard_v = shard_sd[k]
|
2023-09-19 06:20:26 +00:00
|
|
|
assert v.shape == shard_v.shape, f"{name} {k} shape mismatch, {v.shape} vs {shard_v.shape}"
|
|
|
|
assert v.dtype == shard_v.dtype, f"{name} {k} dtype mismatch, {v.dtype} vs {shard_v.dtype}"
|
|
|
|
assert torch.equal(v, shard_v), f"{name} {k} value mismatch"
|
2023-08-03 06:51:36 +00:00
|
|
|
|
|
|
|
|
2023-08-03 09:50:15 +00:00
|
|
|
def build_model_from_hybrid_plugin(model_fn: Callable, loss_fn: Callable, test_config: Dict[str, Any]):
|
|
|
|
use_lazy_init = False
|
2023-09-19 06:20:26 +00:00
|
|
|
if "use_lazy_init" in test_config:
|
|
|
|
use_lazy_init = test_config.pop("use_lazy_init")
|
2023-08-03 09:50:15 +00:00
|
|
|
|
2023-08-11 07:43:23 +00:00
|
|
|
ctx = LazyInitContext() if use_lazy_init else nullcontext()
|
2023-08-03 09:50:15 +00:00
|
|
|
with ctx:
|
2023-08-11 07:43:23 +00:00
|
|
|
org_model = model_fn()
|
2023-08-03 09:50:15 +00:00
|
|
|
sharded_model = copy.deepcopy(org_model)
|
|
|
|
if use_lazy_init:
|
2023-08-11 07:43:23 +00:00
|
|
|
ctx.materialize(org_model)
|
2023-08-03 09:50:15 +00:00
|
|
|
|
2023-08-11 07:43:23 +00:00
|
|
|
org_model = org_model.cuda()
|
2023-08-03 09:50:15 +00:00
|
|
|
org_optimizer = Adam(org_model.parameters(), lr=1e-3)
|
|
|
|
sharded_optimizer = Adam(sharded_model.parameters(), lr=1e-3)
|
|
|
|
criterion = loss_fn
|
|
|
|
|
2023-08-11 07:43:23 +00:00
|
|
|
plugin = HybridParallelPlugin(**test_config)
|
|
|
|
booster = Booster(plugin=plugin)
|
2023-08-03 09:50:15 +00:00
|
|
|
|
2023-08-11 07:43:23 +00:00
|
|
|
sharded_model, sharded_optimizer, criterion, _, _ = booster.boost(sharded_model, sharded_optimizer, criterion)
|
2023-08-03 09:50:15 +00:00
|
|
|
return org_model, org_optimizer, sharded_model, sharded_optimizer, criterion, booster
|
|
|
|
|
|
|
|
|
2023-09-19 06:20:26 +00:00
|
|
|
def run_forward_backward_with_hybrid_plugin(
|
|
|
|
org_model: Module,
|
|
|
|
sharded_model: Module,
|
|
|
|
sharded_optimizer: Optimizer,
|
|
|
|
data_gen_fn: Callable,
|
|
|
|
output_transform_fn: Callable,
|
|
|
|
criterion: Callable,
|
|
|
|
booster: Booster,
|
|
|
|
):
|
2023-08-11 02:32:53 +00:00
|
|
|
org_model.cuda()
|
|
|
|
sharded_model.cuda()
|
2023-08-03 09:50:15 +00:00
|
|
|
|
|
|
|
def _criterion(outputs, inputs):
|
|
|
|
outputs = output_transform_fn(outputs)
|
|
|
|
loss = criterion(outputs)
|
|
|
|
return loss
|
|
|
|
|
|
|
|
data = data_gen_fn()
|
2023-08-16 07:41:20 +00:00
|
|
|
|
|
|
|
if booster.plugin.enable_sequence_parallelism and booster.plugin.tp_size != 0:
|
2023-09-19 06:20:26 +00:00
|
|
|
seq_len = data["input_ids"].shape[-1]
|
2023-08-16 07:41:20 +00:00
|
|
|
lcm = booster.plugin.tp_size * seq_len // math.gcd(booster.plugin.tp_size, seq_len)
|
|
|
|
times = lcm // seq_len
|
2023-09-19 06:20:26 +00:00
|
|
|
input_shape = data["input_ids"].shape
|
2023-08-16 07:41:20 +00:00
|
|
|
for k, v in data.items():
|
|
|
|
if v.shape == input_shape:
|
2023-10-18 03:05:25 +00:00
|
|
|
data[k] = v.repeat((1,) * (v.dim() - 1) + (times,))
|
2023-08-16 07:41:20 +00:00
|
|
|
|
2023-08-03 09:50:15 +00:00
|
|
|
sharded_model.train()
|
|
|
|
if booster.plugin.stage_manager is not None:
|
2023-08-11 07:43:23 +00:00
|
|
|
for k, v in data.items():
|
2023-09-19 06:20:26 +00:00
|
|
|
if torch.is_tensor(v) or "Tensor" in v.__class__.__name__:
|
2023-08-11 07:43:23 +00:00
|
|
|
new_shape = [1] * v.dim()
|
|
|
|
new_shape[0] = 4
|
2023-09-19 06:20:26 +00:00
|
|
|
data[k] = v.to("cuda").repeat(*new_shape)
|
2023-08-11 07:43:23 +00:00
|
|
|
|
2023-08-03 09:50:15 +00:00
|
|
|
data_iter = iter([data])
|
2023-09-19 06:20:26 +00:00
|
|
|
sharded_output = booster.execute_pipeline(
|
|
|
|
data_iter, sharded_model, _criterion, sharded_optimizer, return_loss=True, return_outputs=True
|
|
|
|
)
|
|
|
|
sharded_loss = sharded_output["loss"]
|
2023-08-03 09:50:15 +00:00
|
|
|
else:
|
|
|
|
data = {k: v.cuda() for k, v in data.items()}
|
|
|
|
sharded_output = sharded_model(**data)
|
2023-08-10 05:59:30 +00:00
|
|
|
|
2023-08-03 09:50:15 +00:00
|
|
|
sharded_loss = criterion(sharded_output)
|
2023-08-10 05:59:30 +00:00
|
|
|
sharded_optimizer.backward(sharded_loss)
|
2023-08-03 09:50:15 +00:00
|
|
|
|
|
|
|
org_model.train()
|
2023-08-10 05:59:30 +00:00
|
|
|
data = {k: v.cuda() for k, v in data.items()}
|
2023-08-03 09:50:15 +00:00
|
|
|
org_output = org_model(**data)
|
2023-08-11 02:32:53 +00:00
|
|
|
|
2023-08-03 09:50:15 +00:00
|
|
|
org_loss = criterion(org_output)
|
|
|
|
org_loss.backward()
|
|
|
|
|
|
|
|
return org_loss, org_output, sharded_loss, sharded_output
|
|
|
|
|
|
|
|
|
2023-09-19 06:20:26 +00:00
|
|
|
def check_output_hidden_state(
|
|
|
|
org_output: Tensor,
|
|
|
|
sharded_output: Tensor,
|
|
|
|
stage_manager: Optional[PipelineStageManager] = None,
|
|
|
|
atol: float = 1e-5,
|
|
|
|
rtol: float = 1e-3,
|
|
|
|
dim: int = 0,
|
|
|
|
):
|
2023-08-03 09:50:15 +00:00
|
|
|
org_hidden_state = org_output.last_hidden_state
|
|
|
|
|
|
|
|
if stage_manager and stage_manager.is_last_stage():
|
2023-09-19 06:20:26 +00:00
|
|
|
sharded_hidden_state = sharded_output["outputs"]["last_hidden_state"]
|
2023-09-04 09:52:23 +00:00
|
|
|
else:
|
|
|
|
sharded_hidden_state = sharded_output.last_hidden_state
|
2023-08-03 09:50:15 +00:00
|
|
|
|
2023-10-18 03:05:25 +00:00
|
|
|
assert_close(org_hidden_state.float(), sharded_hidden_state.float(), atol=atol, rtol=rtol)
|
2023-08-03 09:50:15 +00:00
|
|
|
|
|
|
|
|
|
|
|
def check_loss(org_loss: Tensor, sharded_loss: Tensor, atol: float = 1e-5, rtol: float = 1e-3):
|
2023-10-18 03:05:25 +00:00
|
|
|
assert torch.allclose(org_loss.float(), sharded_loss.float(), atol=atol, rtol=rtol)
|
2023-09-19 06:20:26 +00:00
|
|
|
|
|
|
|
|
|
|
|
def check_weight(
|
|
|
|
org_model: Module,
|
|
|
|
sharded_model: Module,
|
|
|
|
layer_suffix: List[str],
|
|
|
|
tp_group: Optional[ProcessGroup] = None,
|
|
|
|
dim: int = 0,
|
|
|
|
atol: float = 1e-5,
|
|
|
|
rtol: float = 1e-3,
|
|
|
|
verbose: bool = False,
|
|
|
|
):
|
2023-08-03 09:50:15 +00:00
|
|
|
for suffix in layer_suffix:
|
|
|
|
org_weight = getattr_(org_model, suffix).weight
|
|
|
|
sharded_weight = getattr_(sharded_model, suffix).weight
|
|
|
|
|
|
|
|
if is_distributed_tensor(sharded_weight) or is_customized_distributed_tensor(sharded_weight):
|
|
|
|
sharded_weight_list = [
|
2023-09-19 06:20:26 +00:00
|
|
|
torch.zeros_like(sharded_weight).to("cuda") for _ in range(dist.get_world_size(tp_group))
|
2023-08-03 09:50:15 +00:00
|
|
|
]
|
|
|
|
dist.all_gather(sharded_weight_list, sharded_weight, tp_group)
|
|
|
|
sharded_weight = torch.cat(sharded_weight_list, dim=dim)
|
|
|
|
|
|
|
|
if verbose and dist.get_rank() == 0:
|
|
|
|
print(f"'{suffix}' weight: {org_weight}, {sharded_weight}")
|
|
|
|
|
2023-10-18 03:05:25 +00:00
|
|
|
assert_close(org_weight.float(), sharded_weight.float(), atol=atol, rtol=rtol)
|
2023-09-19 06:20:26 +00:00
|
|
|
|
|
|
|
|
|
|
|
def get_grad_tensors_for_check(
|
|
|
|
org_model: Module,
|
|
|
|
sharded_model: Module,
|
|
|
|
layer_suffix: List[str],
|
|
|
|
tp_group: ProcessGroup = None,
|
|
|
|
dim: int = 0,
|
|
|
|
atol: float = 1e-5,
|
|
|
|
rtol: float = 1e-3,
|
|
|
|
verbose: bool = False,
|
|
|
|
name: str = None,
|
|
|
|
):
|
2023-08-30 06:50:34 +00:00
|
|
|
grad_to_check = {}
|
|
|
|
for suffix in layer_suffix:
|
|
|
|
org_grad = getattr_(org_model, suffix).weight.grad
|
|
|
|
shard_grad = getattr_(sharded_model, suffix).weight.grad
|
|
|
|
shard_weight = getattr_(sharded_model, suffix).weight
|
|
|
|
if is_distributed_tensor(shard_weight) or is_customized_distributed_tensor(shard_weight):
|
2023-09-19 06:20:26 +00:00
|
|
|
shard_grad_list = [torch.zeros_like(shard_grad).to("cuda") for _ in range(dist.get_world_size(tp_group))]
|
2023-08-30 06:50:34 +00:00
|
|
|
dist.all_gather(shard_grad_list, shard_grad, tp_group)
|
|
|
|
shard_grad = torch.cat(shard_grad_list, dim=dim)
|
|
|
|
|
|
|
|
# embedding may be resized when using tensor parallel
|
|
|
|
if shard_grad.shape[0] > org_grad.shape[0]:
|
2023-09-19 06:20:26 +00:00
|
|
|
shard_grad = shard_grad[: org_grad.shape[0], :]
|
2023-08-30 06:50:34 +00:00
|
|
|
if verbose and dist.get_rank() == 0:
|
|
|
|
print(f"'{suffix}' grad: {org_grad}, {shard_grad}")
|
|
|
|
|
|
|
|
grad_to_check[suffix] = {
|
|
|
|
"org_grad": org_grad.float(),
|
|
|
|
"shard_grad": shard_grad.float(),
|
|
|
|
"rtol": rtol,
|
2023-09-19 06:20:26 +00:00
|
|
|
"atol": atol,
|
2023-08-30 06:50:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return grad_to_check
|
|
|
|
|
|
|
|
|
|
|
|
# used by sam/blip2
|
2023-09-19 06:20:26 +00:00
|
|
|
def check_grad(
|
|
|
|
org_model: Module,
|
|
|
|
sharded_model: Module,
|
|
|
|
layer_suffix: List[str],
|
|
|
|
tp_group: ProcessGroup = None,
|
|
|
|
dim: int = 0,
|
|
|
|
atol: float = 1e-5,
|
|
|
|
rtol: float = 1e-3,
|
|
|
|
verbose: bool = False,
|
|
|
|
):
|
2023-08-03 06:51:36 +00:00
|
|
|
for suffix in layer_suffix:
|
2023-08-03 09:50:15 +00:00
|
|
|
org_grad = getattr_(org_model, suffix).weight.grad
|
2023-08-03 06:51:36 +00:00
|
|
|
shard_grad = getattr_(sharded_model, suffix).weight.grad
|
|
|
|
shard_weight = getattr_(sharded_model, suffix).weight
|
|
|
|
if is_distributed_tensor(shard_weight) or is_customized_distributed_tensor(shard_weight):
|
2023-09-19 06:20:26 +00:00
|
|
|
shard_grad_list = [torch.zeros_like(shard_grad).to("cuda") for _ in range(dist.get_world_size(tp_group))]
|
2023-08-03 09:50:15 +00:00
|
|
|
dist.all_gather(shard_grad_list, shard_grad, tp_group)
|
|
|
|
shard_grad = torch.cat(shard_grad_list, dim=dim)
|
|
|
|
|
|
|
|
# embedding may be resized when using tensor parallel
|
|
|
|
if shard_grad.shape[0] > org_grad.shape[0]:
|
2023-09-19 06:20:26 +00:00
|
|
|
shard_grad = shard_grad[: org_grad.shape[0], :]
|
2023-08-03 06:51:36 +00:00
|
|
|
if verbose and dist.get_rank() == 0:
|
2023-08-03 09:50:15 +00:00
|
|
|
print(f"'{suffix}' grad: {org_grad}, {shard_grad}")
|
2023-08-10 05:59:30 +00:00
|
|
|
|
2023-10-18 03:05:25 +00:00
|
|
|
assert_close(org_grad.float(), shard_grad.float(), rtol=rtol, atol=atol)
|
2023-08-16 08:11:57 +00:00
|
|
|
|
|
|
|
|
2023-09-19 06:20:26 +00:00
|
|
|
def unwrap_model(
|
|
|
|
module: Module, base_model_class_name: Optional[str] = None, base_model_attribute_name: Optional[str] = None
|
|
|
|
):
|
2023-08-16 08:11:57 +00:00
|
|
|
if isinstance(module, HybridParallelModule):
|
|
|
|
module = module.unwrap()
|
|
|
|
if base_model_class_name is None:
|
|
|
|
return module
|
|
|
|
if module.__class__.__name__ == base_model_class_name:
|
|
|
|
return module
|
|
|
|
return getattr(module, base_model_attribute_name, None)
|
2023-08-30 06:50:34 +00:00
|
|
|
|
|
|
|
|
|
|
|
def check_all_grad_tensors(check_tensors):
|
|
|
|
"""
|
|
|
|
"org_grad": tensor to be compared from the original model
|
|
|
|
"shard_grad": tensor to be compared from the sharded model
|
|
|
|
"""
|
|
|
|
for suffix, check_info in check_tensors.items():
|
|
|
|
org_grad = check_info["org_grad"]
|
|
|
|
shard_grad = check_info["shard_grad"]
|
|
|
|
rtol = check_info["rtol"]
|
|
|
|
atol = check_info["atol"]
|
2023-10-18 03:05:25 +00:00
|
|
|
assert_close(org_grad, shard_grad, atol=atol, rtol=rtol)
|