Comments (43)
С такой ошибкой сталкивался когда были не те версии llvm и тритона
llvm-9-dev стоит?
pip install triton==0.2.3 делали?
Также в коде torch.backends.cudnn.enabled = False так что вроде как не надо CUDNN. Это чтобы эксперименты были воспроизводимы - cudnn рандомная
from ru-gpts.
llvm-9-dev стоит?
pip install triton==0.2.3 делали?
Да и да. Сейчас начал пробовать поставить triton==0.3.0 и вместе с ним llvm-10-dev. Пока уперся в то, что для версии 0.3 нужно сменить версию питона, в 3.6.5 проблемы с cmath библиотекой.
Раз пока не понятно в чем дело, возможно подскажете на каких версия CUDA точно работает?
from ru-gpts.
Установка triton==0.3.0 и вместе с ним llvm-10-dev ничего не изменило, по прежнему модель нормально загружается с
gpt = RuGPT3XL.from_pretrained("sberbank-ai/rugpt3xl", seq_len=512)
но так же падает при попытке ее вызвать
from ru-gpts.
Triton точно должен быть более ранней версии как указано. также мы тестили только на llvm-9-dev. У нас cuda 10.1.
from ru-gpts.
Triton точно должен быть более ранней версии как указано. также мы тестили только на llvm-9-dev. У нас cuda 10.1.
Вот странно, та же версия CUDA, что и у меня. Ок, я откачу triton до 0.2.3 и llvm-9-dev. Не знаю пока на что думать, может дело в версии питона, хотя вряд ли конечно. Ошибка связана с CUDA + triton. Спасибо за информацию!
На всякий случай, сам pytorch CUDA видит, тензоры на GPU создает нормально. Что-то triton специфическое.
from ru-gpts.
Note! Model has sparse attention blocks.
Note: Currently DeepSpeed Sparse Attention can be used only on NVIDIA V100 GPU using Torch >= 1.5 and Cuda 10.1 or 10.2.
https://www.deepspeed.ai/tutorials/sparse-attention/
from ru-gpts.
Note! Model has sparse attention blocks.
Note: Currently DeepSpeed Sparse Attention can be used only on NVIDIA V100 GPU using Torch >= 1.5 and Cuda 10.1 or 10.2.
https://www.deepspeed.ai/tutorials/sparse-attention/
Actually, it works on Titan RTX with CUDA 11.1 and Deepspeed built from 'sparse-attn-cuda11’ branch. Doesnt work on 3090 (and A100, probably), because Deepspeed aren’t using the unreleased version of Triton. Triton has very early support of latest GPUs.
from ru-gpts.
Поставил все так же как в этом ноутбуке у себя локально: https://github.com/sberbank-ai/ru-gpts/blob/master/examples/ruGPT3XL_generation.ipynb
~$ ds_report -------------------------------------------------- DeepSpeed C++/CUDA extension op report -------------------------------------------------- NOTE: Ops not installed will be just-in-time (JIT) compiled at runtime if needed. Op compatibility means that your system meet the required dependencies to JIT install the op. -------------------------------------------------- JIT compiled ops requires ninja ninja .................. [OKAY] -------------------------------------------------- op name ................ installed .. compatible -------------------------------------------------- cpu_adam ............... [YES] ...... [OKAY] fused_adam ............. [NO] ....... [OKAY] fused_lamb ............. [NO] ....... [OKAY] sparse_attn ............ [YES] ...... [OKAY] transformer ............ [NO] ....... [OKAY] stochastic_transformer . [NO] ....... [OKAY] utils .................. [NO] ....... [OKAY] -------------------------------------------------- DeepSpeed general environment info: torch install path ............... ['/home/antoly/3env/lib/python3.6/site-packages/torch'] torch version .................... 1.7.1+cu101 torch cuda version ............... 10.1 nvcc version ..................... 10.1 deepspeed install path ........... ['/home/antoly/3env/lib/python3.6/site-packages/deepspeed'] deepspeed info ................... 0.3.7, unknown, unknown deepspeed wheel compiled w. ...... torch 1.7, cuda 10.1
Модель нормально загружается в память, но при обращении к модели падает:
gpt("Кто был президентом США в 2020? ").logits
/home/antoly/3env/lib/python3.6/site-packages/deepspeed/ops/sparse_attention/matmul.py:272: UserWarning: This overload of nonzero is deprecated: nonzero() Consider using one of the following signatures instead: nonzero(*, bool as_tuple) (Triggered internally at /pytorch/torch/csrc/utils/python_arg_parser.cpp:882.) nnz = layout.nonzero() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "ru-gpts/src/xl_wrapper.py", line 281, in __call__ lm_logits = self.model(tokens, position_ids, attention_mask) File "/home/antoly/3env/lib/python3.6/site-packages/torch/nn/modules/module.py", line 727, in _call_impl result = self.forward(*input, **kwargs) File "ru-gpts/src/fp16/fp16.py", line 72, in forward return fp16_to_fp32(self.module(*(fp32_to_fp16(inputs)), **kwargs)) File "/home/antoly/3env/lib/python3.6/site-packages/torch/nn/modules/module.py", line 727, in _call_impl result = self.forward(*input, **kwargs) File "ru-gpts/src/model/gpt3_modeling.py", line 108, in forward transformer_output = self.transformer(embeddings, attention_mask) File "/home/antoly/3env/lib/python3.6/site-packages/torch/nn/modules/module.py", line 727, in _call_impl result = self.forward(*input, **kwargs) File "ru-gpts/src/mpu/transformer.py", line 449, in forward hidden_states = layer(hidden_states, attention_mask) File "/home/antoly/3env/lib/python3.6/site-packages/torch/nn/modules/module.py", line 727, in _call_impl result = self.forward(*input, **kwargs) File "ru-gpts/src/mpu/transformer.py", line 301, in forward attention_output = self.attention(layernorm_output, ltor_mask) File "/home/antoly/3env/lib/python3.6/site-packages/torch/nn/modules/module.py", line 727, in _call_impl result = self.forward(*input, **kwargs) File "ru-gpts/src/mpu/transformer.py", line 131, in forward attn_mask=ltor_mask) File "/home/antoly/3env/lib/python3.6/site-packages/torch/nn/modules/module.py", line 727, in _call_impl result = self.forward(*input, **kwargs) File "/home/antoly/3env/lib/python3.6/site-packages/deepspeed/ops/sparse_attention/sparse_self_attention.py", line 130, in forward attn_output_weights = sparse_dot_sdd_nt(query, key) File "/home/antoly/3env/lib/python3.6/site-packages/deepspeed/ops/sparse_attention/matmul.py", line 746, in __call__ time_db) File "/home/antoly/3env/lib/python3.6/site-packages/deepspeed/ops/sparse_attention/matmul.py", line 550, in forward c_time) File "/home/antoly/3env/lib/python3.6/site-packages/deepspeed/ops/sparse_attention/matmul.py", line 228, in _sdd_matmul bench=bench) File "/home/antoly/3env/lib/python3.6/site-packages/triton/kernel.py", line 86, in __call__ torch.ops.triton.launch_kernel(self.op_id, device, params) RuntimeError: CUDA: Error- invalid ptx
Единственное мое подозрение, что у меня стоит две версии CUDA 9.2 и 10.1. Я везде настроил пути на 10.1, но возможно все же triton смотрит на 9.2. Возможно вы сталкивались с такой ошибкой?
Возможно нужно поставить CUDNN? У меня для 10.1 не стоит
Получил такую же ошибку. Какое-нибудь решение удалось найти?
from ru-gpts.
@KyrmyzyOleg Насколько я понял, Triton имеет очень ограниченную поддержку GPUs, судя по комментариям выше. Точно работает на V100 и возможно на Titan RTX. Все остальные потребительские видеокарты не поддерживаются
from ru-gpts.
@KyrmyzyOleg Насколько я понял, Triton имеет очень ограниченную поддержку GPUs, судя по комментариям выше. Точно работает на V100 и возможно на Titan RTX. Все остальные потребительские видеокарты не поддерживаются
Печально всё. Под colab, значит, не запустить.
Но всё равно спасибо!
from ru-gpts.
@avostryakov dev версия Тритон поддерживает новые видеокарты. Я собрал Deepspeed из бранча sparse-attn/support-latest-triton
и у меня работает на 3090. Так же должно работать на A100.
from ru-gpts.
@avostryakov dev версия Тритон поддерживает новые видеокарты. Я собрал Deepspeed из бранча
sparse-attn/support-latest-triton
и у меня работает на 3090. Так же должно работать на A100.
Спасибо за информацию! Я еще почитал описание Triton. Заявляют поддержку карт с Compute Capability 7+. А это карты от RTX 2080 и выше. Так что мои GTX 1080ti не будут поддерживаться
from ru-gpts.
@avostryakov dev версия Тритон поддерживает новые видеокарты. Я собрал Deepspeed из бранча
sparse-attn/support-latest-triton
и у меня работает на 3090. Так же должно работать на A100.
Расскажите пожалуйста поподробнее. У меня видюха 3090, и я поставил старую куду 10.1 как рекомендовано к этому репозиторию. И даже арех собрал с поддержной старой архитектуры 7.0.
По вашей рекомердации поставил свежую дев версию тритона и Deepspeed из указаной ветки. Результата ноль. Всё то же сообщение при загрузке модели:
RuntimeError: CUDA error: no kernel image is available for execution on the device
Может я что-то не так делаю?
from ru-gpts.
Cuda 10.x не работает на новых видеокартах. Нужно ставить CUDA 11.1.
from ru-gpts.
@mgrankin А какую версию pytorch нужно использовать? Версия 1.8.1+cu111 даёт ошибку:
ImportError: cannot import name 'SAVE_STATE_WARNING' from 'torch.optim.lr_scheduler'
from ru-gpts.
Так, я обновил transformers до последней версии и теперь у меня другая ошибка:
RuntimeError: Error(s) in loading state_dict for GPT3Model:
Missing key(s) in state_dict: "transformer.layers.0.attention.sparse_self_attention.master_layout",
"transformer.layers.2.attention.sparse_self_attention.master_layout",
"transformer.layers.4.attention.sparse_self_attention.master_layout",
"transformer.layers.6.attention.sparse_self_attention.master_layout",
"transformer.layers.8.attention.sparse_self_attention.master_layout",
"transformer.layers.10.attention.sparse_self_attention.master_layout",
"transformer.layers.12.attention.sparse_self_attention.master_layout",
"transformer.layers.14.attention.sparse_self_attention.master_layout",
"transformer.layers.16.attention.sparse_self_attention.master_layout",
"transformer.layers.18.attention.sparse_self_attention.master_layout",
"transformer.layers.20.attention.sparse_self_attention.master_layout",
"transformer.layers.22.attention.sparse_self_attention.master_layout".
Такое ощущение что в чекпоинте нету весов для разряжённого sparse слоя.
from ru-gpts.
В ранней версии лэйаут разряженной матрицы генерировался каждый раз заново. В текущей версии они генерируют его один раз и затем сохраняют/загружают. (Кажется, там присутствовал некоторый рандом, от которого пытались избавиться выставляя seed случайных чисел. От этого когда теперь можно избавиться при желании.)
Что бы корректно загрузить модель достаточно указать strict=False
при загрузке. Это команда model.load_state_dict(checkpoint, strict=False)
в файле src/xl_wrapper.py
from ru-gpts.
mgrankin@0807b02#diff-97521d021dc7092c7661f60b33be9a9f52a3eb0130f3ec52cc2baffa2e51fbbd
from ru-gpts.
Спасибо за помощь, но теперь у меня уже во время генерации такая ерунда выплыла:
ImportError: /export/DeepSpeed-triton/deepspeed/ops/sparse_attention/sparse_attn_op.cpython-38-x86_64-linux-gnu.so: undefined symbol: _ZN6caffe28TypeMeta21_typeMetaDataInstanceIN3c107complexIfEEEEPKNS_6detail12TypeMetaDataEv
Может это потому что у меня версия тритона не та что вы указывали в переписке (той дев версии уже нет в репозитории) а немного поновее (triton==1.0.0.dev20210509)?
P.S. нашел в обсуждении репы DeepSpeed microsoft/DeepSpeed#902 упоминание что похже на то что авторы тритона изменили АПИ удалив старую версию из pip. Стоит вопрос о том чтоб авторы данной доработки в DeepSpeed доработали свой коммит под новый тритон.
from ru-gpts.
@mgrankin Я перепроверил нотбук с генерацией текста, там есть такая ячейка:
# And this cell should be run without errors
import deepspeed.ops.sparse_attention.sparse_attn_op
И как раз на ней сейчас идёт ошибка:
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-2-2d9098395ca5> in <module>
1 # And this cell should be run without errors
----> 2 import deepspeed.ops.sparse_attention.sparse_attn_op
ImportError: /export/DeepSpeed-triton/deepspeed/ops/sparse_attention/sparse_attn_op.cpython-38-x86_64-linux-gnu.so: undefined symbol: _ZN6caffe28TypeMeta21_typeMetaDataInstanceIN3c107complexIfEEEEPKNS_6detail12TypeMetaDataEv
Вы можете что-нибудь сказать на этот счёт? Куда вообще стоит копать?
from ru-gpts.
Попытался поставить старый питон, но что на 3.6 что на 3.7 выдаёт при загрузке следующее :
/export/triton/python/triton/kernel.py in __init__(self, src, device, defines, num_warps, autotune_vals, autotune_key)
63 if device.type == 'cuda':
64 self.device_id = torch.cuda.current_device() if device.index is None else device.index
---> 65 self.device = _triton.driver.cu_device(self.device_id, False)
66 cu_stream = torch.cuda.current_stream(self.device_id).cuda_stream
67 self.stream = _triton.driver.cu_stream(cu_stream, False)
RuntimeError: dlsym unable to load function
Может я на правильном пути и тут можно что-то исправить?
from ru-gpts.
Проблема решена. Оказывается triton динамически грузил библиотеку куды libcuda.so а у меня она была установлена как libcuda.so.1. Линкование исправило проблему.
from ru-gpts.
@exelents так у вас в итоге заработало с новой версией triton? Что нужно сделать для линкования правильной библиотеки?
from ru-gpts.
Я создал симлинк c /usr/lib/x86_64-linux-gnu/libcuda.so.1 на до этого не существовавший путь /usr/lib/x86_64-linux-gnu/libcuda.so и данная проблема с "dlsym unable to load function" ушла
from ru-gpts.
И да, у меня стоит версия тритона triton==0.4.0, помню что новая, которая на 1.0 начинается не подходила.
from ru-gpts.
@exelents спасибо, буду пробовать. Для будущих поколений тут отпишусь.
from ru-gpts.
И да, у меня стоит версия тритона triton==0.4.0, помню что новая, которая на 1.0 начинается не подходила.
А можно подробнее? Какая версия torch, какая версия triton? Собирали deepspeed из ветки, или какой версии? Очень хочу запустить на 3090, памяти на 2080 очень мало. Потому что triton 0.4.0 удалили. Какая версия Питона?
from ru-gpts.
@megamen32 у меня заработало с triton==0.4.2
JIT compiled ops requires ninja
ninja .................. [OKAY]
--------------------------------------------------
op name ................ installed .. compatible
--------------------------------------------------
cpu_adam ............... [YES] ...... [OKAY]
fused_adam ............. [NO] ....... [OKAY]
fused_lamb ............. [NO] ....... [OKAY]
sparse_attn ............ [YES] ...... [OKAY]
transformer ............ [NO] ....... [OKAY]
stochastic_transformer . [NO] ....... [OKAY]
async_io ............... [NO] ....... [OKAY]
transformer_inference .. [NO] ....... [OKAY]
utils .................. [NO] ....... [OKAY]
quantizer .............. [NO] ....... [OKAY]
--------------------------------------------------
DeepSpeed general environment info:
torch install path ............... ['/usr/local/lib/python3.7/dist-packages/torch']
torch version .................... 1.7.0+cu101
torch cuda version ............... 10.1
nvcc version ..................... 10.1
deepspeed install path ........... ['/usr/local/lib/python3.7/dist-packages/deepspeed']
deepspeed info ................... 0.4.4, unknown, unknown
deepspeed wheel compiled w. ...... torch 1.7, cuda 10.1
from ru-gpts.
- cuda 11.1
- deepspeed из ветки
sparse-attn/support-latest-triton
ссылку на которую я нашел в этом обсуждении microsoft/DeepSpeed#902 но похоже что она уже вмерджена в мастер ветку - triton сейчас у меня стоит версии 0.4.0 но как сказали выше можно попробовать и 0.4.2
еще вариант - поставить тритон из репы:
git clone https://github.com/ptillet/triton
cd ./triton/python
git reset --hard a598fba0f5ad2db54bf0bbcbe9f23b85c408fc25
python setup.py develop
python setup.py install
- torch у меня такой версии: 1.8.0+cu111
- transformers==4.5.1
P.S. Питон версии 3.7.9
from ru-gpts.
@Artyrm Но ведь cuda 10.x не работает для 3090. Или это не важно? Но ведь pytorch ругаеться что sm_38 не поддерживается в этой версии torch.
from ru-gpts.
@megamen32 по 3090 не могу сказать, я в Colab, там P100. Но вот Экселенц написал выше, что у него Cuda 11.1, и у него заработало ещё раньше меня и на своём железе.
from ru-gpts.
@exelents
Я сделал все возможное по инструкции, но все равно ошибка. Единственное различие, это python у меня 3.7.11. Но ведь не может быть в этом ошибка. Проверьте пожалуйста точную копию коммита Deepspeed и Triton. Многим у кого 3090 это будет невероятно полезно. Так же я перепробовал последние ветки Deepspeed==0.5.0 и Triton==1.0.0 и 0.4.2
Вот полный скрипт для Ubuntu 20.04.
#python 3.7
sudo apt install python3.7 python3.7-dev python3.7-venv -y
#CUDA 11.1
wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64/cuda-ubuntu2004.pin
sudo mv cuda-ubuntu2004.pin /etc/apt/preferences.d/cuda-repository-pin-600
sudo apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64/7fa2af80.pub
sudo add-apt-repository "deb https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64/ /"
sudo apt-get update
sudo apt install cuda-toolkit-11-1 -y
export CUDA_HOME=/usr/local/cuda-11.1
#VirtualEnv
python3.7 -m venv gpt-cp37-cuda111
. gpt-cp37-cuda111/bin/activate
pip install torch==1.8.0+cu111 torchvision==0.9.0+cu111 torchaudio==0.8.0 -f https://download.pytorch.org/whl/torch_stable.html
#apex
git clone https://github.com/NVIDIA/apex
pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" ./apex
#triton
git clone https://github.com/ptillet/triton
cd ./triton/python
git reset --hard a598fba0f5ad2db54bf0bbcbe9f23b85c408fc25
python setup.py develop
python setup.py install
cd ../..
#cpufeature
pip install cpufeature
#deepspeed
DS_BUILD_CPU_ADAM=1 DS_BUILD_SPARSE_ATTN=1 pip install git+https://github.com/microsoft/DeepSpeed.git@sparse-attn/support-latest-triton --no-cache-dir --global-option="build_ext"
#transformers
pip install transformers==4.5.1
pip install natsort
python -c 'import apex;from apex.normalization.fused_layer_norm import FusedLayerNorm'
python -c 'import torch; torch.cuda.is_available()'
python -c 'import torch; print(torch.cuda.device_count())'
python -c 'import deepspeed.ops.sparse_attention.sparse_attn_op'
# Ru-GPT3
git clone https://github.com/sberbank-ai/ru-gpts.git
sed -i 's/model.load_state_dict(checkpoint)/model.load_state_dict(checkpoint,strict=False)/g' ru-gpts/src/xl_wrapper.py
echo 'import warnings
warnings.filterwarnings("ignore")
import sys
sys.path.append("ru-gpts/")
import os
os.environ["USE_DEEPSPEED"] = "1"
from src.xl_wrapper import RuGPT3XL
gpt = RuGPT3XL.from_pretrained("sberbank-ai/rugpt3xl", seq_len=512)
logits = gpt("Кто был президентом США в 2020? ").logits' >test.py
python test.py
Ошибка:
initializing model parallel with size 1
initializing model parallel cuda seeds on global rank 0, model parallel rank 0, and data parallel rank 0 with model parallel seed: 3952 and data parallel seed: 1234
Use alternating sparse & dense attention layers
Traceback (most recent call last):
File "test.py", line 9, in
logits = gpt("Кто был президентом США в 2020? ").logits
File "ru-gpts/src/xl_wrapper.py", line 294, in call
lm_logits = self.model(tokens, position_ids, attention_mask)
File "/mnt/2TB/demi-cuda/test_folder/gpt-cp37-cuda111/lib/python3.7/site-packages/torch/nn/modules/module.py", line 889, in _call_impl
result = self.forward(input, **kwargs)
File "ru-gpts/src/fp16/fp16.py", line 72, in forward
return fp16_to_fp32(self.module((fp32_to_fp16(inputs)), **kwargs))
File "/mnt/2TB/demi-cuda/test_folder/gpt-cp37-cuda111/lib/python3.7/site-packages/torch/nn/modules/module.py", line 889, in _call_impl
result = self.forward(*input, **kwargs)
File "ru-gpts/src/model/gpt3_modeling.py", line 108, in forward
transformer_output = self.transformer(embeddings, attention_mask)
File "/mnt/2TB/demi-cuda/test_folder/gpt-cp37-cuda111/lib/python3.7/site-packages/torch/nn/modules/module.py", line 889, in _call_impl
result = self.forward(*input, **kwargs)
File "ru-gpts/src/mpu/transformer.py", line 449, in forward
hidden_states = layer(hidden_states, attention_mask)
File "/mnt/2TB/demi-cuda/test_folder/gpt-cp37-cuda111/lib/python3.7/site-packages/torch/nn/modules/module.py", line 889, in _call_impl
result = self.forward(*input, **kwargs)
File "ru-gpts/src/mpu/transformer.py", line 301, in forward
attention_output = self.attention(layernorm_output, ltor_mask)
File "/mnt/2TB/demi-cuda/test_folder/gpt-cp37-cuda111/lib/python3.7/site-packages/torch/nn/modules/module.py", line 889, in _call_impl
result = self.forward(*input, **kwargs)
File "ru-gpts/src/mpu/transformer.py", line 131, in forward
attn_mask=ltor_mask)
File "/mnt/2TB/demi-cuda/test_folder/gpt-cp37-cuda111/lib/python3.7/site-packages/torch/nn/modules/module.py", line 889, in _call_impl
result = self.forward(*input, **kwargs)
File "/mnt/2TB/demi-cuda/test_folder/gpt-cp37-cuda111/lib/python3.7/site-packages/deepspeed/ops/sparse_attention/sparse_self_attention.py", line 152, in forward
attn_output_weights = sparse_dot_sdd_nt(query, key)
File "/mnt/2TB/demi-cuda/test_folder/gpt-cp37-cuda111/lib/python3.7/site-packages/deepspeed/ops/sparse_attention/matmul.py", line 745, in call
time_db)
File "/mnt/2TB/demi-cuda/test_folder/gpt-cp37-cuda111/lib/python3.7/site-packages/deepspeed/ops/sparse_attention/matmul.py", line 549, in forward
c_time)
File "/mnt/2TB/demi-cuda/test_folder/gpt-cp37-cuda111/lib/python3.7/site-packages/deepspeed/ops/sparse_attention/matmul.py", line 224, in _sdd_matmul
grid=lambda opt: [opt.TZ,
File "/mnt/2TB/demi-cuda/test_folder/gpt-cp37-cuda111/lib/python3.7/site-packages/triton-1.0.0-py3.7-linux-x86_64.egg/triton/kernel.py", line 116, in call
kernel = self.fn.autotune(params, grid, self.stream)
IndexError: map::at
Вот прекрасный вывод ds_report
DeepSpeed C++/CUDA extension op report
NOTE: Ops not installed will be just-in-time (JIT) compiled at
runtime if needed. Op compatibility means that your system
meet the required dependencies to JIT install the op.JIT compiled ops requires ninja
ninja .................. [OKAY]op name ................ installed .. compatible
cpu_adam ............... [YES] ...... [OKAY]
fused_adam ............. [NO] ....... [OKAY]
fused_lamb ............. [NO] ....... [OKAY]
sparse_attn ............ [YES] ...... [OKAY]
transformer ............ [NO] ....... [OKAY]
stochastic_transformer . [NO] ....... [OKAY]
async_io ............... [NO] ....... [OKAY]
transformer_inference .. [NO] ....... [OKAY]
utils .................. [NO] ....... [OKAY]
quantizer .............. [NO] ....... [OKAY]DeepSpeed general environment info:
torch install path ............... ['/mnt/2TB/demi-cuda/test_folder/gpt-cp37-cuda111/lib/python3.7/site-packages/torch']
torch version .................... 1.8.0+cu111
torch cuda version ............... 11.1
nvcc version ..................... 11.1
deepspeed install path ........... ['/mnt/2TB/demi-cuda/test_folder/gpt-cp37-cuda111/lib/python3.7/site-packages/deepspeed']
deepspeed info ................... 0.4.0+e7378a4, e7378a4, sparse-attn/support-latest-triton
deepspeed wheel compiled w. ...... torch 1.8, cuda 11.1
from ru-gpts.
@megamen32 судя по ошибке, я бы попробовал для начала с отключенным fp16 запустить, памяти вроде должно хватить. Или ключ вроде fp16=False должно быть возможным куда-то передать, ну или прямо в исходниках найти, где ключ задаётся.
А вы попробовали запускать с минимальными отличиями конфигурации от приведённых в примере? Вроде например triton=0.4.2 , а версии остального те же?
Кстати, Deepspeed = 0.5.0 у меня тоже что-то ломает, остался на 0.4.5 пока.
from ru-gpts.
@Artyrm Точно тоже самое если закомментить model = FP16_Module(model)
Traceback (most recent call last):
File "test.py", line 9, in
logits = gpt("Кто был президентом США в 2020? ").logits
File "ru-gpts/src/xl_wrapper.py", line 294, in call
lm_logits = self.model(tokens, position_ids, attention_mask)
File "/mnt/2TB/demi-cuda/test_folder/gpt-cp37-cuda111/lib/python3.7/site-packages/torch/nn/modules/module.py", line 889, in _call_impl
result = self.forward(*input, **kwargs)
File "ru-gpts/src/model/gpt3_modeling.py", line 108, in forward
transformer_output = self.transformer(embeddings, attention_mask)
File "/mnt/2TB/demi-cuda/test_folder/gpt-cp37-cuda111/lib/python3.7/site-packages/torch/nn/modules/module.py", line 889, in _call_impl
result = self.forward(*input, **kwargs)
File "ru-gpts/src/mpu/transformer.py", line 449, in forward
hidden_states = layer(hidden_states, attention_mask)
File "/mnt/2TB/demi-cuda/test_folder/gpt-cp37-cuda111/lib/python3.7/site-packages/torch/nn/modules/module.py", line 889, in _call_impl
result = self.forward(*input, **kwargs)
File "ru-gpts/src/mpu/transformer.py", line 301, in forward
attention_output = self.attention(layernorm_output, ltor_mask)
File "/mnt/2TB/demi-cuda/test_folder/gpt-cp37-cuda111/lib/python3.7/site-packages/torch/nn/modules/module.py", line 889, in _call_impl
result = self.forward(*input, **kwargs)
File "ru-gpts/src/mpu/transformer.py", line 131, in forward
attn_mask=ltor_mask)
File "/mnt/2TB/demi-cuda/test_folder/gpt-cp37-cuda111/lib/python3.7/site-packages/torch/nn/modules/module.py", line 889, in _call_impl
result = self.forward(*input, **kwargs)
File "/mnt/2TB/demi-cuda/test_folder/gpt-cp37-cuda111/lib/python3.7/site-packages/deepspeed/ops/sparse_attention/sparse_self_attention.py", line 152, in forward
attn_output_weights = sparse_dot_sdd_nt(query, key)
File "/mnt/2TB/demi-cuda/test_folder/gpt-cp37-cuda111/lib/python3.7/site-packages/deepspeed/ops/sparse_attention/matmul.py", line 745, in call
time_db)
File "/mnt/2TB/demi-cuda/test_folder/gpt-cp37-cuda111/lib/python3.7/site-packages/deepspeed/ops/sparse_attention/matmul.py", line 549, in forward
c_time)
File "/mnt/2TB/demi-cuda/test_folder/gpt-cp37-cuda111/lib/python3.7/site-packages/deepspeed/ops/sparse_attention/matmul.py", line 224, in _sdd_matmul
grid=lambda opt: [opt.TZ,
File "/mnt/2TB/demi-cuda/test_folder/gpt-cp37-cuda111/lib/python3.7/site-packages/triton-1.0.0-py3.7-linux-x86_64.egg/triton/kernel.py", line 116, in call
kernel = self.fn.autotune(params, grid, self.stream)
IndexError: map::at
Проблема в тритоне. Я даже находил в их коммитах что-то по поводу autotune и matmul
Ради интереса поставил deepspeed==0.4.5 . Тоже самое. Даже если поставить triton==0.4.2
Но если поставить новее triton>=1.0.0(или последний dev) , то уже другая ошибка.
Traceback (most recent call last):
File "test.py", line 9, in
logits = gpt("Кто был президентом США в 2020? ").logits
File "ru-gpts/src/xl_wrapper.py", line 294, in call
lm_logits = self.model(tokens, position_ids, attention_mask)
File "/mnt/2TB/demi-cuda/test_folder/gpt-cp37-cuda111/lib/python3.7/site-packages/torch/nn/modules/module.py", line 889, in _call_impl
result = self.forward(*input, **kwargs)
File "ru-gpts/src/model/gpt3_modeling.py", line 108, in forward
transformer_output = self.transformer(embeddings, attention_mask)
File "/mnt/2TB/demi-cuda/test_folder/gpt-cp37-cuda111/lib/python3.7/site-packages/torch/nn/modules/module.py", line 889, in _call_impl
result = self.forward(*input, **kwargs)
File "ru-gpts/src/mpu/transformer.py", line 449, in forward
hidden_states = layer(hidden_states, attention_mask)
File "/mnt/2TB/demi-cuda/test_folder/gpt-cp37-cuda111/lib/python3.7/site-packages/torch/nn/modules/module.py", line 889, in _call_impl
result = self.forward(*input, **kwargs)
File "ru-gpts/src/mpu/transformer.py", line 301, in forward
attention_output = self.attention(layernorm_output, ltor_mask)
File "/mnt/2TB/demi-cuda/test_folder/gpt-cp37-cuda111/lib/python3.7/site-packages/torch/nn/modules/module.py", line 889, in _call_impl
result = self.forward(*input, **kwargs)
File "ru-gpts/src/mpu/transformer.py", line 131, in forward
attn_mask=ltor_mask)
File "/mnt/2TB/demi-cuda/test_folder/gpt-cp37-cuda111/lib/python3.7/site-packages/torch/nn/modules/module.py", line 889, in _call_impl
result = self.forward(*input, **kwargs)
File "/mnt/2TB/demi-cuda/test_folder/gpt-cp37-cuda111/lib/python3.7/site-packages/deepspeed/ops/sparse_attention/sparse_self_attention.py", line 152, in forward
attn_output_weights = sparse_dot_sdd_nt(query, key)
File "/mnt/2TB/demi-cuda/test_folder/gpt-cp37-cuda111/lib/python3.7/site-packages/deepspeed/ops/sparse_attention/matmul.py", line 745, in call
time_db)
File "/mnt/2TB/demi-cuda/test_folder/gpt-cp37-cuda111/lib/python3.7/site-packages/deepspeed/ops/sparse_attention/matmul.py", line 549, in forward
c_time)
File "/mnt/2TB/demi-cuda/test_folder/gpt-cp37-cuda111/lib/python3.7/site-packages/deepspeed/ops/sparse_attention/matmul.py", line 188, in _sdd_matmul
_sparse_matmul.sdd_cache[key] = triton.kernel(
AttributeError: module 'triton' has no attribute 'kernel'
from ru-gpts.
@megamen32 мельком глянул стек ошибки - похоже какая-то проблема с операцией matmul для sparce attention в deepspeed.
У меня такой проблемы не было, но когда я разбирался со своими, то слышал предложение от разработчика тритона, мол заменить эти операции из deepspeed-а на аналогичные из тритона, мол они всё равно идентичные, не понимает почему разработчики deepspeed до сих пор используют свои костыли.
В файле DeepSpeed-triton3/deepspeed/ops/sparse_attention/init.py
Добавить
from triton.ops.blocksparse.matmul import matmul as MatMul
from triton.ops.blocksparse.softmax import softmax as Softmax
Закомментить
from .softmax import Softmax
from .matmul import MatMul
В файле DeepSpeed-triton3/deepspeed/ops/sparse_attention/sparse_self_attention.py
Добавить
from triton.ops.blocksparse.matmul import matmul as MatMul
from triton.ops.blocksparse.softmax import softmax as Softmax
Закомментить
from deepspeed.ops.sparse_attention import MatMul, Softmax, SparsityConfig
PS и пересобрать DeepSpeed
Ну и в принципе поискать по проекту, не добавили ли они нигде еще импортов MatMul и Softmax.
Я не уверен, поможет ли это решить данную проблему, но попробовать стоит.
from ru-gpts.
Пардон, обновил инструкцию редактирования для init.py, ошибочка вышла.
from ru-gpts.
Заработало вы гений! @exelents . Завтра выложу полный скрипт. Огромное спасибо!!!
П.с. я настолько отчаялся что написал скрипт который билдит и тестит все коммиты тритона. Но и он не помог. Только вы
from ru-gpts.
@megamen32 , @exelents , есть новости? У меня ошибки как в изначальном посте, RuntimeError: CUDA: Error- invalid ptx
.
from ru-gpts.
В ранней версии лэйаут разряженной матрицы генерировался каждый раз заново. В текущей версии они генерируют его один раз и затем сохраняют/загружают. (Кажется, там присутствовал некоторый рандом, от которого пытались избавиться выставляя seed случайных чисел. От этого когда теперь можно избавиться при желании.)
Что бы корректно загрузить модель достаточно указать
strict=False
при загрузке. Это командаmodel.load_state_dict(checkpoint, strict=False)
в файлеsrc/xl_wrapper.py
@mgrankin , скажите, пожалуйста, а их можно перегенерировать, что ли?
Потому что по этой инструкции RuntimeError: CUDA: Error- invalid ptx.
возникает уже позже (на ноутбуке из топик-старта).
from ru-gpts.
@avostryakov , а Вам удалось запустить?
from ru-gpts.
from ru-gpts.
@kuraga Вот полный скрипт.
#python 3.7
sudo apt install python3.7 python3.7-dev python3.7-venv -y
#CUDA 11.1
wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64/cuda-ubuntu2004.pin
sudo mv cuda-ubuntu2004.pin /etc/apt/preferences.d/cuda-repository-pin-600
sudo apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64/7fa2af80.pub
sudo add-apt-repository "deb https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64/ /"
sudo apt-get update
sudo apt install cuda-toolkit-11-1 -y
export CUDA_HOME=/usr/local/cuda-11.1
#VirtualEnv
python3.7 -m venv gpt2-cp37-cuda111
. gpt2-cp37-cuda111/bin/activate
pip install torch==1.8.0+cu111 torchvision==0.9.0+cu111 torchaudio==0.8.0 -f https://download.pytorch.org/whl/torch_stable.html
##apex
git clone https://github.com/NVIDIA/apex
pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" ./apex
#cpufeature
pip install cpufeature
#deepspeed
git clone https://github.com/microsoft/DeepSpeed.git
cd ./DeepSpeed
git reset --hard e7378a462e7348df230871c96e3d3e05b677f6b8
echo 'from .sparsity_config import SparsityConfig, DenseSparsityConfig, FixedSparsityConfig, VariableSparsityConfig, BigBirdSparsityConfig, BSLongformerSparsityConfig
#from .softmax import Softmax
#from .matmul import MatMul
from triton.ops.blocksparse.matmul import matmul as MatMul
from triton.ops.blocksparse.softmax import softmax as Softmax
from .sparse_self_attention import SparseSelfAttention
from .bert_sparse_self_attention import BertSparseSelfAttention
from .sparse_attention_utils import SparseAttentionUtils' >./deepspeed/ops/sparse_attention/__init__.py
sed -i 's/from deepspeed.ops.sparse_attention import MatMul, Softmax, SparsityConfig/from deepspeed.ops.sparse_attention import SparsityConfig;from triton.ops.blocksparse.matmul import matmul as MatMul;from triton.ops.blocksparse.softmax import softmax as Softmax/g'./deepspeed/ops/sparse_attention/sparse_self_attention.py
DS_BUILD_CPU_ADAM=1 DS_BUILD_SPARSE_ATTN=1 python setup.py develop
DS_BUILD_CPU_ADAM=1 DS_BUILD_SPARSE_ATTN=1 python setup.py install
cd ..
#transformers
pip install transformers==4.5.1
pip install natsort
python -c 'import apex;from apex.normalization.fused_layer_norm import FusedLayerNorm'
python -c 'import torch; print(torch.cuda.is_available())'
python -c 'import torch; print(torch.cuda.device_count())'
python -c 'import deepspeed.ops.sparse_attention.sparse_attn_op'
## Ru-GPT3
git clone https://github.com/sberbank-ai/ru-gpts.git
sed -i 's/model.load_state_dict(checkpoint)/model.load_state_dict(checkpoint,strict=False)/g' ru-gpts/src/xl_wrapper.py
sed -i 's/model = FP16_Module(model)/#model = FP16_Module(model)/g' ru-gpts/src/xl_wrapper.py
#testing
echo 'import warnings
warnings.filterwarnings("ignore")
import sys
sys.path.append("ru-gpts/")
import os
os.environ["USE_DEEPSPEED"] = "1"
from src.xl_wrapper import RuGPT3XL
gpt = RuGPT3XL.from_pretrained("sberbank-ai/rugpt3xl", seq_len=512)
logits = gpt("Кто был президентом США в 2020? ").logits
print(
gpt.generate(
"Кто был президентом США в 2020? ",max_length=50,no_repeat_ngram_size=3,repetition_penalty=2.,)
)' >test.py
python test.py
Правда я помню там еще проблемы с установкой apex бывают. Вроде я их так подправлял.
sudo apt-get install -y gcc-8 g++-8
apt-get install -y llvm-9-dev
apt-get install -y cmake
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-8 10
sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-8 10
sudo update-alternatives --install /usr/bin/cc cc /usr/bin/gcc 30
sudo update-alternatives --set cc /usr/bin/gcc
sudo update-alternatives --install /usr/bin/c++ c++ /usr/bin/g++ 30
sudo update-alternatives --set c++ /usr/bin/g++
П.С Я совсем новичок в этих ваших bash. Но может даже этот плохой скрипт кому-то пригодиться
from ru-gpts.
@megamen32 , спасибо большое!
По идее должно работать. Но, увы, без fp16 Alenush/rugpt3simplification_rsse#2 (comment)
from ru-gpts.
Related Issues (20)
- describe carbon emission
- ruGPT3XL_generation.ipynb not working HOT 3
- Новость курс
- AssertionError: model parallel group is not initialized HOT 1
- The model requires `num_beams`, although it is not needed in the example HOT 3
- Ru-gpts for chit-chat bot HOT 2
- Прямая трансляция по apex legends HOT 1
- Games
- Correct data format for fine-tuning RUGPT3 models
- A
- The XL Model and the latest DeepSpeed
- Как настроить на вопрос\ответ? HOT 2
- Apackage missing HOT 2
- Hello
- Are there hardware requirements to execute the script? HOT 17
- Ускорение инференса rugpt3-large HOT 1
- Как embedding'и получить и какой они длины? HOT 1
- Unable to use RuGPT3FinetuneHF.ipynb Colab notebook HOT 1
- Link to code implementation is not available
- No "nvcc" utilite founded during environment installation HOT 3
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from ru-gpts.