ColossalAI icon indicating copy to clipboard operation
ColossalAI copied to clipboard

[BUG]: shardformer使用PP失败

Open wangbluo opened this issue 3 years ago • 10 comments

🐛 Describe the bug

import math
from typing import Any, List, Union

import evaluate
import torch
import torch.distributed as dist
from data import GLUEDataBuilder
from torch import nn
from torch.optim import Adam, AdamW, Optimizer
from torch.utils._pytree import tree_map
from torch.utils.data import DataLoader
from tqdm import tqdm
from transformers import BertConfig, BertForSequenceClassification, get_linear_schedule_with_warmup
from transformers import LlamaConfig, LlamaForCausalLM
import colossalai
from colossalai.cluster import DistCoordinator
from colossalai.nn.optimizer import HybridAdam
from colossalai.shardformer import ShardConfig, ShardFormer
from time import time
from colossalai.logging import disable_existing_loggers, get_dist_logger
from functools import partial
from colossalai.cluster import ProcessGroupMesh
from colossalai.pipeline.stage_manager import PipelineStageManager

def to_device(x: Any, device: torch.device) -> Any:

    def _to(t: Any):
        if isinstance(t, torch.Tensor):
            return t.to(device)
        return t

    return tree_map(_to, x)


def train(args):
    colossalai.launch_from_torch(config={}, seed=42)
    coordinator = DistCoordinator()

    if args.model == "llama":
        #cfg = BertConfig.from_pretrained(args.pretrain, num_labels=data_builder.num_labels)
        model = LlamaForCausalLM.from_pretrained(args.pretrain)

    model.to(torch.cuda.current_device())
    
    DP_DIM, PP_DIM = 0, 1
    DP_SIZE, PP_SIZE = 2, 4
    pg_mesh = ProcessGroupMesh(DP_SIZE, PP_SIZE)
    stage_manager = PipelineStageManager(pg_mesh, PP_DIM)

    # if multiple GPUs, shard the model
    if dist.get_world_size() > 1:
        shard_config = ShardConfig(tensor_parallel_process_group=None, pipeline_stage_manager=stage_manager, enable_tensor_parallelism=True, enable_fused_normalization=True, enable_all_optimization=True)
        print("shard_config: ", shard_config)
        shard_former = ShardFormer(shard_config=shard_config)
        model = shard_former.optimize(model)[0]

    optim = Adam(model.parameters(), lr=args.lr)   
    fit(model, optim, stage_manager,args.max_epochs, args.accumulation_steps, args.batch_size, coordinator)
def get_tflops(model_numel, batch_size, seq_len, step_time):
    # Tflops_per_GPU = global_batch * global_numel * seq_len * 8 / #gpu
    return model_numel * batch_size * seq_len * 8 / 1e12 / (step_time + 1e-12) / 8         

# Randomly Generated Data
def get_data(batch_size, seq_len, vocab_size):
    input_ids = torch.randint(0, vocab_size, (batch_size, seq_len), device=torch.cuda.current_device())
    attention_mask = torch.ones_like(input_ids)
    return input_ids, attention_mask

def fit(model: nn.Module, optimizer: Optimizer,stage_manager:PipelineStageManager, max_epochs, accumulation_steps, batch_size,
        coordinator):
    logger = get_dist_logger()
    BATCH_SIZE = args.batch_size
    SEQ_LENGTH = 2048
    VOCAB_SIZE = 32000
    NUM_STEPS = 1000
    total_loss = 0
    global_numel = sum([p.numel() for p in model.parameters()])
    get_tflops_func = partial(get_tflops, global_numel, BATCH_SIZE, SEQ_LENGTH)
    model.train()
    for n in range(10):
        #batch = to_device(batch, torch.cuda.current_device())
        input_ids, attn_mask = get_data(BATCH_SIZE, SEQ_LENGTH, VOCAB_SIZE)
        input_ids.to('cuda')
        attn_mask.to('cuda')
        model.to('cuda')
        start = time()
        print("model",model)
        outputs = model(input_ids, attn_mask,None,None,None,input_ids,False,None,None,None,stage_manager)
        loss = outputs['loss']
        #loss = loss / accumulation_steps
        loss.backward()
        optimizer.step()
        torch.cuda.synchronize()
        step_time = time() - start
        logger.info(
            f'[{n+1}/{NUM_STEPS}] Loss:{loss.item():.3f}, Step time: {step_time:.3f}s, TFLOPS: {get_tflops_func(step_time):.3f}',
            ranks=[0])
    torch.cuda.synchronize()

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-t', '--task', default='mrpc', help="GLUE task to run")
    parser.add_argument('--model', type=str, default="bert")
    parser.add_argument('--pretrain', type=str, default="bert-base-uncased")
    parser.add_argument('--max_epochs', type=int, default=1)
    parser.add_argument('--batch_size', type=int, default=4)
    parser.add_argument('--lr', type=float, default=2.4e-5)
    parser.add_argument('--tensor_parallelism', type=bool, default=False)
    parser.add_argument('--accumulation_steps', type=int, default=8)
    parser.add_argument('--warmup_fraction', type=float, default=0.03)
    parser.add_argument('--target_f1', type=float, default=None)
    parser.add_argument('--grad_checkpoint', default=True, action='store_true')
    args = parser.parse_args()
    train(args)```
    
    您好我是这样使用的,参考了你们的PipelineStageManager的设计和其他的一些例子,但是前向的时候没有替换forward成功,报错是这样的:
    
```Traceback (most recent call last):
  File "llama_7b_convergence_benchmark.py", line 155, in <module>
    train(args)
  File "llama_7b_convergence_benchmark.py", line 59, in train
    fit(model, optim, stage_manager,args.max_epochs, args.accumulation_steps, args.batch_size, coordinator)
  File "llama_7b_convergence_benchmark.py", line 89, in fit
    outputs = model(input_ids, attn_mask,None,None,None,input_ids,False,None,None,None,stage_manager)
  File "/opt/conda/lib/python3.8/site-packages/torch/nn/modules/module.py", line 1501, in _call_impl
    return forward_call(*args, **kwargs)
TypeError: llama_for_causal_lm_forward() got multiple values for argument 'stage_manager'```

![image](https://github.com/hpcaitech/ColossalAI/assets/32676639/7d4b1a6f-7cd4-4e2b-b960-e70468655716)

切分之后的模型打印出来长这样:
```(
  (model): LlamaModel(
    (embed_tokens): Embedding(32000, 4096, padding_idx=0)
    (layers): ModuleList(
      (0-7): 8 x LlamaDecoderLayer(
        (self_attn): LlamaAttention(
          (q_proj): Linear1D_Col()
          (k_proj): Linear1D_Col()
          (v_proj): Linear1D_Col()
          (o_proj): Linear1D_Row()
          (rotary_emb): LlamaRotaryEmbedding()
        )
        (mlp): LlamaMLP(
          (gate_proj): Linear1D_Col()
          (down_proj): Linear1D_Row()
          (up_proj): Linear1D_Col()
          (act_fn): SiLUActivation()
        )
        (input_layernorm): FusedRMSNorm(torch.Size([4096]), eps=1e-05, elementwise_affine=True)
        (post_attention_layernorm): FusedRMSNorm(torch.Size([4096]), eps=1e-05, elementwise_affine=True)
      )
      (8-31): 24 x LlamaDecoderLayer(
        (self_attn): LlamaAttention(
          (q_proj): Linear(in_features=4096, out_features=4096, bias=False)
          (k_proj): Linear(in_features=4096, out_features=4096, bias=False)
          (v_proj): Linear(in_features=4096, out_features=4096, bias=False)
          (o_proj): Linear(in_features=4096, out_features=4096, bias=False)
          (rotary_emb): LlamaRotaryEmbedding()
        )
        (mlp): LlamaMLP(
          (gate_proj): Linear(in_features=4096, out_features=11008, bias=False)
          (down_proj): Linear(in_features=11008, out_features=4096, bias=False)
          (up_proj): Linear(in_features=4096, out_features=11008, bias=False)
          (act_fn): SiLUActivation()
        )
        (input_layernorm): LlamaRMSNorm()
        (post_attention_layernorm): LlamaRMSNorm()
      )
    )
    (norm): LlamaRMSNorm()
  )
  (lm_head): Linear(in_features=4096, out_features=32000, bias=False)
)    return forward_call(*args, **kwargs)```

![image](https://github.com/hpcaitech/ColossalAI/assets/32676639/3e88efda-2108-45e6-80e1-e4959b9590bd)


看起来并没有使用到你们的llama_for_causal_lm_forward,
我打印了日志,它走到了LlamaForCausalLMPolicy,类里面的if self.pipeline_stage_manager:分支去了,
但是接下来的llama_for_causal_lm_forward并没有打印成功,我查看了代码似乎没有看到前向的替换

想确认一下这个pp能否work,因为这个pp还是比较关键的,
现在没有pp的话,八卡A100最多只能跑7b大小的模型,且稍微改点参数就out of memory,
没有办法测试你们benchmark给出的sequence length = 2048的效果
    

### Environment

_No response_

wangbluo avatar Aug 28 '23 04:08 wangbluo

您好,目前Shardformer的Pipeline功能还在完善当中,未正式发布。直接手动创建ShardConfig和PipelineManager是无法正常运作流水线并行训练的,要把流水线跑起来需要用到另外一个叫做HybridParallelPlugin的功能,可以等待我们不久以后发布的正式教程。

如果您急着使用的话,可以参考tests/test_shardformer/test_model下的测试脚本里面是如何使用HybridParallelPlugin进行混合并行训练的。

Fridge003 avatar Aug 28 '23 04:08 Fridge003

您好,目前Shardformer的Pipeline功能还在完善当中,未正式发布。直接手动创建ShardConfig和PipelineManager是无法正常运作流水线并行训练的,要把流水线跑起来需要用到另外一个叫做HybridParallelPlugin的功能,可以等待我们不久以后发布的正式教程。

如果您急着使用的话,可以参考tests/test_shardformer/test_model下的测试脚本里面是如何使用HybridParallelPlugin进行混合并行训练的。

您好,我尝试运行了tests/test_shardformer/test_model里面的test_shard_llama.py,运行命令是torchrun --standalone --nproc_per_node=8 test_shard_llama.py 遇到了报错,似乎是你们lazy_init遇到的问题,在八卡A100上运行的:

Traceback (most recent call last):
  File "test_shard_llama.py", line 161, in <module>
    test_llama()
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/colossalai/testing/utils.py", line 143, in _run_until_success
    raise e
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/colossalai/testing/utils.py", line 132, in _run_until_success
    ret = func(*args, **kwargs)
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/colossalai/testing/utils.py", line 274, in _clear_cache
    f(*args, **kwargs)
  File "test_shard_llama.py", line 157, in test_llama
    spawn(check_llama, 4)
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/colossalai/testing/utils.py", line 252, in spawn
    mp.spawn(wrapped_func, nprocs=nprocs)
  File "/opt/conda/lib/python3.8/site-packages/torch/multiprocessing/spawn.py", line 239, in spawn
    return start_processes(fn, args, nprocs, join, daemon, start_method='spawn')
  File "/opt/conda/lib/python3.8/site-packages/torch/multiprocessing/spawn.py", line 197, in start_processes
    while not context.join():
  File "/opt/conda/lib/python3.8/site-packages/torch/multiprocessing/spawn.py", line 160, in join
    raise ProcessRaisedException(msg, error_index, failed_process.pid)
torch.multiprocessing.spawn.ProcessRaisedException: 

-- Process 3 terminated with the following error:
Traceback (most recent call last):
  File "/opt/conda/lib/python3.8/site-packages/torch/multiprocessing/spawn.py", line 69, in _wrap
    fn(i, *args)
  File "/workspace/workfile/ColossalAI-main/tests/test_shardformer/test_model/test_shard_llama.py", line 150, in check_llama
    run_llama_test()
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/colossalai/testing/utils.py", line 63, in _execute_function_by_param
    partial_func(**kwargs)
  File "/workspace/workfile/ColossalAI-main/tests/test_shardformer/test_model/test_shard_llama.py", line 141, in run_llama_test
    check_forward_backward(model_fn, data_gen_fn, output_transform_fn, loss_fn, test_config)
  File "/workspace/workfile/ColossalAI-main/tests/test_shardformer/test_model/test_shard_llama.py", line 27, in check_forward_backward
    build_model_from_hybrid_plugin(model_fn, loss_fn, test_config)
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/tests/test_shardformer/test_model/_utils.py", line 109, in build_model_from_hybrid_plugin
    org_model = model_fn()
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/tests/kit/model_zoo/transformers/llama.py", line 60, in <lambda>
    model_fn=lambda: transformers.LlamaModel(config),
  File "/opt/conda/lib/python3.8/site-packages/transformers/models/llama/modeling_llama.py", line 446, in __init__
    self.layers = nn.ModuleList([LlamaDecoderLayer(config) for _ in range(config.num_hidden_layers)])
  File "/opt/conda/lib/python3.8/site-packages/transformers/models/llama/modeling_llama.py", line 446, in <listcomp>
    self.layers = nn.ModuleList([LlamaDecoderLayer(config) for _ in range(config.num_hidden_layers)])
  File "/opt/conda/lib/python3.8/site-packages/transformers/models/llama/modeling_llama.py", line 256, in __init__
    self.self_attn = LlamaAttention(config=config)
  File "/opt/conda/lib/python3.8/site-packages/transformers/models/llama/modeling_llama.py", line 177, in __init__
    self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
  File "/opt/conda/lib/python3.8/site-packages/torch/nn/modules/linear.py", line 101, in __init__
    self.reset_parameters()
  File "/opt/conda/lib/python3.8/site-packages/torch/nn/modules/linear.py", line 107, in reset_parameters
    init.kaiming_uniform_(self.weight, a=math.sqrt(5))
  File "/opt/conda/lib/python3.8/site-packages/torch/nn/init.py", line 396, in kaiming_uniform_
    return torch.overrides.handle_torch_function(
  File "/opt/conda/lib/python3.8/site-packages/torch/overrides.py", line 1551, in handle_torch_function
    result = torch_func_method(public_api, types, args, kwargs)
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/colossalai/lazy/lazy_init.py", line 324, in __torch_function__
    o = func(*tree_map(unwrap, args), **tree_map(unwrap, kwargs))
  File "/opt/conda/lib/python3.8/site-packages/torch/nn/init.py", line 396, in kaiming_uniform_
    return torch.overrides.handle_torch_function(
  File "/opt/conda/lib/python3.8/site-packages/torch/overrides.py", line 1551, in handle_torch_function
    result = torch_func_method(public_api, types, args, kwargs)
  File "/opt/conda/lib/python3.8/site-packages/torch/_tensor.py", line 1295, in __torch_function__
    ret = func(*args, **kwargs)
  File "/opt/conda/lib/python3.8/site-packages/torch/nn/init.py", line 412, in kaiming_uniform_
    return tensor.uniform_(-bound, bound)
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/colossalai/_analyzer/_subclasses/meta_tensor.py", line 113, in __torch_dispatch__
    ret = func(*args, **kwargs)
  File "/opt/conda/lib/python3.8/site-packages/torch/_ops.py", line 287, in __call__
    return self._op(*args, **kwargs or {})
  File "/opt/conda/lib/python3.8/site-packages/torch/_decomp/decompositions.py", line 1958, in uniform_
    return self.copy_((high - low) * torch.rand_like(self) + low)
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/colossalai/lazy/lazy_init.py", line 476, in wrapper
    return self.tensor_cls(orig_target, *args[1:], device=orig_t.device, dtype=orig_t.dtype, **kwargs)
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/colossalai/lazy/lazy_init.py", line 163, in __new__
    elem = func(*args, **{**kwargs, 'device': 'meta'})
TypeError: rand() received an invalid combination of arguments - got (dtype=torch.dtype, device=str, ), but expected one of:
 * (tuple of ints size, *, torch.Generator generator, tuple of names names, torch.dtype dtype, torch.layout layout, torch.device device, bool pin_memory, bool requires_grad)
 * (tuple of ints size, *, torch.Generator generator, Tensor out, torch.dtype dtype, torch.layout layout, torch.device device, bool pin_memory, bool requires_grad)
 * (tuple of ints size, *, Tensor out, torch.dtype dtype, torch.layout layout, torch.device device, bool pin_memory, bool requires_grad)
 * (tuple of ints size, *, tuple of names names, torch.dtype dtype, torch.layout layout, torch.device device, bool pin_memory, bool requires_grad)```

wangbluo avatar Aug 28 '23 08:08 wangbluo

您好,目前Shardformer的Pipeline功能还在完善当中,未正式发布。直接手动创建ShardConfig和PipelineManager是无法正常运作流水线并行训练的,要把流水线跑起来需要用到另外一个叫做HybridParallelPlugin的功能,可以等待我们不久以后发布的正式教程。

如果您急着使用的话,可以参考tests/test_shardformer/test_model下的测试脚本里面是如何使用HybridParallelPlugin进行混合并行训练的。

这是我跑的关于test_shard_gpt2.py的脚本报错,我之前尝试在pytorch2.x上跑colossalai也遇到过这个HermeticPyObject 的报错,是pytorch2.x不支持metatensor导致的:

环境是pytorch2.0.1,应该就是这个原因导致的

但是我这个初始环境是pytorch1.12,应该是装flash_attn的时候自动装的,装的是flash_attn2.0.5版本

Maximum number of attempts is reached or pattern is not matched, no more retrying...
Traceback (most recent call last):
  File "test_shard_gpt2.py", line 138, in <module>
    test_gpt2()
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/colossalai/testing/utils.py", line 143, in _run_until_success
    raise e
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/colossalai/testing/utils.py", line 132, in _run_until_success
    ret = func(*args, **kwargs)
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/colossalai/testing/utils.py", line 274, in _clear_cache
    f(*args, **kwargs)
  File "test_shard_gpt2.py", line 134, in test_gpt2
    spawn(check_gpt2, 4)
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/colossalai/testing/utils.py", line 252, in spawn
    mp.spawn(wrapped_func, nprocs=nprocs)
  File "/opt/conda/lib/python3.8/site-packages/torch/multiprocessing/spawn.py", line 239, in spawn
    return start_processes(fn, args, nprocs, join, daemon, start_method='spawn')
  File "/opt/conda/lib/python3.8/site-packages/torch/multiprocessing/spawn.py", line 197, in start_processes
    while not context.join():
  File "/opt/conda/lib/python3.8/site-packages/torch/multiprocessing/spawn.py", line 160, in join
    raise ProcessRaisedException(msg, error_index, failed_process.pid)
torch.multiprocessing.spawn.ProcessRaisedException: 

-- Process 3 terminated with the following error:
Traceback (most recent call last):
  File "/opt/conda/lib/python3.8/site-packages/torch/multiprocessing/spawn.py", line 69, in _wrap
    fn(i, *args)
  File "/workspace/workfile/ColossalAI-main/tests/test_shardformer/test_model/test_shard_gpt2.py", line 127, in check_gpt2
    run_gpt2_test()
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/colossalai/testing/utils.py", line 63, in _execute_function_by_param
    partial_func(**kwargs)
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/colossalai/testing/utils.py", line 274, in _clear_cache
    f(*args, **kwargs)
  File "/workspace/workfile/ColossalAI-main/tests/test_shardformer/test_model/test_shard_gpt2.py", line 118, in run_gpt2_test
    check_forward_backward(model_fn, data_gen_fn, output_transform_fn, loss_fn, test_config)
  File "/workspace/workfile/ColossalAI-main/tests/test_shardformer/test_model/test_shard_gpt2.py", line 24, in check_forward_backward
    build_model_from_hybrid_plugin(model_fn, loss_fn, test_config)
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/tests/test_shardformer/test_model/_utils.py", line 109, in build_model_from_hybrid_plugin
    org_model = model_fn()
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/tests/kit/model_zoo/transformers/gpt.py", line 84, in <lambda>
    model_fn=lambda: transformers.GPT2Model(config),
  File "/opt/conda/lib/python3.8/site-packages/transformers/models/gpt2/modeling_gpt2.py", line 680, in __init__
    self.h = nn.ModuleList([GPT2Block(config, layer_idx=i) for i in range(config.num_hidden_layers)])
  File "/opt/conda/lib/python3.8/site-packages/transformers/models/gpt2/modeling_gpt2.py", line 680, in <listcomp>
    self.h = nn.ModuleList([GPT2Block(config, layer_idx=i) for i in range(config.num_hidden_layers)])
  File "/opt/conda/lib/python3.8/site-packages/transformers/models/gpt2/modeling_gpt2.py", line 368, in __init__
    self.attn = GPT2Attention(config, layer_idx=layer_idx)
  File "/opt/conda/lib/python3.8/site-packages/transformers/models/gpt2/modeling_gpt2.py", line 131, in __init__
    torch.tril(torch.ones((max_positions, max_positions), dtype=torch.bool)).view(
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/colossalai/lazy/lazy_init.py", line 468, in wrapper
    return self.tensor_cls(target, *args, **kwargs)
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/colossalai/lazy/lazy_init.py", line 163, in __new__
    elem = func(*args, **{**kwargs, 'device': 'meta'})
  File "/opt/conda/lib/python3.8/site-packages/torch/_prims_common/wrappers.py", line 220, in _fn
    result = fn(*args, **kwargs)
  File "/opt/conda/lib/python3.8/site-packages/torch/_refs/__init__.py", line 4161, in ones
    return torch.full(
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/colossalai/lazy/lazy_init.py", line 468, in wrapper
    return self.tensor_cls(target, *args, **kwargs)
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/colossalai/lazy/lazy_init.py", line 163, in __new__
    elem = func(*args, **{**kwargs, 'device': 'meta'})
  File "/opt/conda/lib/python3.8/site-packages/torch/_meta_registrations.py", line 1735, in full
    return torch.empty(size, *args, **kwargs)
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/colossalai/lazy/lazy_init.py", line 468, in wrapper
    return self.tensor_cls(target, *args, **kwargs)
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/colossalai/lazy/lazy_init.py", line 164, in __new__
    meta_data = MetaTensor(elem, device=device)
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/colossalai/_analyzer/_subclasses/meta_tensor.py", line 61, in __new__
    r = torch.Tensor._make_wrapper_subclass(
RuntimeError: !check_has_torch_dispatch(obj) INTERNAL ASSERT FAILED at "../torch/csrc/autograd/python_variable.cpp":1835, please report a bug to PyTorch. While HermeticPyObject was enabled, we attempted to create a tensor subclass with __torch_dispatch__.  This violates the invariant that operations in HermeticPyObject have equivalent C++ implementations. If your operator registered from Python operator registration isn't doing anything strange, there may be an internal PyTorch bug involving not appropriately disabling TorchDispatchMode before executing Python op registration.

wangbluo avatar Aug 28 '23 09:08 wangbluo

您好,目前Shardformer的Pipeline功能还在完善当中,未正式发布。直接手动创建ShardConfig和PipelineManager是无法正常运作流水线并行训练的,要把流水线跑起来需要用到另外一个叫做HybridParallelPlugin的功能,可以等待我们不久以后发布的正式教程。

如果您急着使用的话,可以参考tests/test_shardformer/test_model下的测试脚本里面是如何使用HybridParallelPlugin进行混合并行训练的。

或者方便提供一下tests/test_shardformer/test_model的环境配置吗,类似requirement.txt这种,非常感谢

wangbluo avatar Aug 28 '23 10:08 wangbluo

Bot detected the issue body's language is not English, translate it automatically. 👯👭🏻🧑‍🤝‍🧑👫🧑🏿‍🤝‍🧑🏻👩🏾‍🤝‍👨🏿👬🏿


Hello, the Pipeline function of Shardformer is still being improved and has not been officially released. Manually creating ShardConfig and PipelineManager directly cannot run the parallel training of the pipeline. To run the pipeline, another function called HybridParallelPlugin is required. You can wait for the official tutorial we will release soon.

If you are in a hurry, you can refer to how to use HybridParallelPlugin for hybrid parallel training in the test script under tests/test_shardformer/test_model.

Or is it convenient to provide the environment configuration of tests/test_shardformer/test_model, similar to requirement.txt, thank you very much

Issues-translate-bot avatar Aug 28 '23 10:08 Issues-translate-bot

您好,目前Shardformer的Pipeline功能还在完善当中,未正式发布。直接手动创建ShardConfig和PipelineManager是无法正常运作流水线并行训练的,要把流水线跑起来需要用到另外一个叫做HybridParallelPlugin的功能,可以等待我们不久以后发布的正式教程。 如果您急着使用的话,可以参考tests/test_shardformer/test_model下的测试脚本里面是如何使用HybridParallelPlugin进行混合并行训练的。

这是我跑的关于test_shard_gpt2.py的脚本报错,我之前尝试在pytorch2.x上跑colossalai也遇到过这个HermeticPyObject 的报错,是pytorch2.x不支持metatensor导致的:

环境是pytorch2.0.1,应该就是这个原因导致的

但是我这个初始环境是pytorch1.12,应该是装flash_attn的时候自动装的,装的是flash_attn2.0.5版本

Maximum number of attempts is reached or pattern is not matched, no more retrying...
Traceback (most recent call last):
  File "test_shard_gpt2.py", line 138, in <module>
    test_gpt2()
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/colossalai/testing/utils.py", line 143, in _run_until_success
    raise e
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/colossalai/testing/utils.py", line 132, in _run_until_success
    ret = func(*args, **kwargs)
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/colossalai/testing/utils.py", line 274, in _clear_cache
    f(*args, **kwargs)
  File "test_shard_gpt2.py", line 134, in test_gpt2
    spawn(check_gpt2, 4)
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/colossalai/testing/utils.py", line 252, in spawn
    mp.spawn(wrapped_func, nprocs=nprocs)
  File "/opt/conda/lib/python3.8/site-packages/torch/multiprocessing/spawn.py", line 239, in spawn
    return start_processes(fn, args, nprocs, join, daemon, start_method='spawn')
  File "/opt/conda/lib/python3.8/site-packages/torch/multiprocessing/spawn.py", line 197, in start_processes
    while not context.join():
  File "/opt/conda/lib/python3.8/site-packages/torch/multiprocessing/spawn.py", line 160, in join
    raise ProcessRaisedException(msg, error_index, failed_process.pid)
torch.multiprocessing.spawn.ProcessRaisedException: 

-- Process 3 terminated with the following error:
Traceback (most recent call last):
  File "/opt/conda/lib/python3.8/site-packages/torch/multiprocessing/spawn.py", line 69, in _wrap
    fn(i, *args)
  File "/workspace/workfile/ColossalAI-main/tests/test_shardformer/test_model/test_shard_gpt2.py", line 127, in check_gpt2
    run_gpt2_test()
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/colossalai/testing/utils.py", line 63, in _execute_function_by_param
    partial_func(**kwargs)
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/colossalai/testing/utils.py", line 274, in _clear_cache
    f(*args, **kwargs)
  File "/workspace/workfile/ColossalAI-main/tests/test_shardformer/test_model/test_shard_gpt2.py", line 118, in run_gpt2_test
    check_forward_backward(model_fn, data_gen_fn, output_transform_fn, loss_fn, test_config)
  File "/workspace/workfile/ColossalAI-main/tests/test_shardformer/test_model/test_shard_gpt2.py", line 24, in check_forward_backward
    build_model_from_hybrid_plugin(model_fn, loss_fn, test_config)
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/tests/test_shardformer/test_model/_utils.py", line 109, in build_model_from_hybrid_plugin
    org_model = model_fn()
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/tests/kit/model_zoo/transformers/gpt.py", line 84, in <lambda>
    model_fn=lambda: transformers.GPT2Model(config),
  File "/opt/conda/lib/python3.8/site-packages/transformers/models/gpt2/modeling_gpt2.py", line 680, in __init__
    self.h = nn.ModuleList([GPT2Block(config, layer_idx=i) for i in range(config.num_hidden_layers)])
  File "/opt/conda/lib/python3.8/site-packages/transformers/models/gpt2/modeling_gpt2.py", line 680, in <listcomp>
    self.h = nn.ModuleList([GPT2Block(config, layer_idx=i) for i in range(config.num_hidden_layers)])
  File "/opt/conda/lib/python3.8/site-packages/transformers/models/gpt2/modeling_gpt2.py", line 368, in __init__
    self.attn = GPT2Attention(config, layer_idx=layer_idx)
  File "/opt/conda/lib/python3.8/site-packages/transformers/models/gpt2/modeling_gpt2.py", line 131, in __init__
    torch.tril(torch.ones((max_positions, max_positions), dtype=torch.bool)).view(
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/colossalai/lazy/lazy_init.py", line 468, in wrapper
    return self.tensor_cls(target, *args, **kwargs)
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/colossalai/lazy/lazy_init.py", line 163, in __new__
    elem = func(*args, **{**kwargs, 'device': 'meta'})
  File "/opt/conda/lib/python3.8/site-packages/torch/_prims_common/wrappers.py", line 220, in _fn
    result = fn(*args, **kwargs)
  File "/opt/conda/lib/python3.8/site-packages/torch/_refs/__init__.py", line 4161, in ones
    return torch.full(
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/colossalai/lazy/lazy_init.py", line 468, in wrapper
    return self.tensor_cls(target, *args, **kwargs)
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/colossalai/lazy/lazy_init.py", line 163, in __new__
    elem = func(*args, **{**kwargs, 'device': 'meta'})
  File "/opt/conda/lib/python3.8/site-packages/torch/_meta_registrations.py", line 1735, in full
    return torch.empty(size, *args, **kwargs)
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/colossalai/lazy/lazy_init.py", line 468, in wrapper
    return self.tensor_cls(target, *args, **kwargs)
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/colossalai/lazy/lazy_init.py", line 164, in __new__
    meta_data = MetaTensor(elem, device=device)
  File "/opt/conda/lib/python3.8/site-packages/colossalai-0.3.1-py3.8.egg/colossalai/_analyzer/_subclasses/meta_tensor.py", line 61, in __new__
    r = torch.Tensor._make_wrapper_subclass(
RuntimeError: !check_has_torch_dispatch(obj) INTERNAL ASSERT FAILED at "../torch/csrc/autograd/python_variable.cpp":1835, please report a bug to PyTorch. While HermeticPyObject was enabled, we attempted to create a tensor subclass with __torch_dispatch__.  This violates the invariant that operations in HermeticPyObject have equivalent C++ implementations. If your operator registered from Python operator registration isn't doing anything strange, there may be an internal PyTorch bug involving not appropriately disabling TorchDispatchMode before executing Python op registration.

Sure, https://github.com/hpcaitech/ColossalAI/blob/feature/shardformer/requirements/requirements.txt

flybird11111 avatar Aug 28 '23 10:08 flybird11111

@flybird11111 thank you for your reply, I have installed https://github.com/hpcaitech/ColossalAI/blob/feature/shardformer/requirements/requirements.txt and https://github.com/hpcaitech/ColossalAI/blob/feature/shardformer/requirements/requirements-test.txt, 1d232f44e04b46423375c0f232dee5bf85f7d0a9

but I still got the error: fbgemm_gpu_py.so not found I search the error and found many users said it's because fbgemm-gpu==0.2.0 torchrec==0.2.0 refer:https://github.com/pytorch/FBGEMM/issues/1250 https://github.com/pytorch/torchrec/issues/557

I'm really confused.

image

Besides, after I installed these requirements.txt, when I run the tests/test_shardformer/test_model/test_shard_llama.py, I got an warning: Please install the xformers And when I installed the xformers, it will install pytorch2.0.1 automatically. Could you please tell which version of xformers should I install? 12a17d1162c25c990f445ef094fee4388c8f504a

wangbluo avatar Aug 28 '23 13:08 wangbluo

fbgemm

Please install fbgemm-gpu-cpu== 0.2.0

flybird11111 avatar Aug 29 '23 02:08 flybird11111

Hi, thanks for reporting this, and sorry it went unanswered for so long. We're going through older issues and closing the ones that no longer apply to the current codebase. It concerns an older release, example or interface, and the components involved have changed substantially since then. We're marking it as stale and will close it in 14 days. If you still see this problem with the latest ColossalAI on PyTorch 2.x, please comment here (or open a new issue) with your environment and a minimal reproduction, and we'll take a look.

JazyJiang avatar Oct 22 '26 06:10 JazyJiang

Closing this issue since there has been no response in the 14 days after it was marked as stale. If you still run into this problem with the latest ColossalAI on PyTorch 2.x, please open a new issue using the bug report template, with your environment and a minimal reproduction.

JazyJiang avatar Nov 05 '26 03:11 JazyJiang