Я встретил эту ошибку в функции потерь. Пример ниже:
Мой код работал нормально, но что-то потерялось, не могу найти проблему. Пробовал обновлять библиотеки, тестировать предыдущие версии, проверял тензоры, индексы... Кто-нибудь может мне помочь, в конце страницы есть ссылка на мой репозиторий с файлами, которые я использовал. Версия библиотеки:
import os
import traceback
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
os.environ['CUDA_LAUNCH_BLOCKING'] = "1"
os.environ['TORCH_USE_CUDA_DSA'] = '1'
import torch
from tokenizers.implementations import ByteLevelBPETokenizer
from tokenizers.processors import BertProcessing
from transformers import RobertaConfig
from transformers import RobertaForMaskedLM
from transformers import RobertaTokenizerFast
from transformers import DataCollatorForLanguageModeling
from transformers import Trainer, TrainingArguments
from transformers import pipeline
from datasets import load_dataset
def read_document(document_path):
with open(document_path, 'r', encoding='utf-8') as file:
return file.read()
def main():
try:
# Create the directory if it does not exist
if not os.path.exists('raw_model'):
os.makedirs('raw_model')
training_data = 'C:\\Users\\caiqu\\OneDrive\\Documentos\\IA\\crepusculoDosIdolos.txt'
os.path.join(os.path.abspath('.'), 'raw_model')
# Initialize a ByteLevelBPETokenizer
tokenizer = ByteLevelBPETokenizer()
tokenizer.train(files=[training_data], vocab_size=52_000, min_frequency=2, special_tokens=[
"",
"
",
"",
"",
"",
])
tokenizer.save_model('raw_model')
tokenizer = RobertaTokenizerFast.from_pretrained('raw_model', max_len=512)
print("Vocabulary size: ", tokenizer.vocab_size)
tokenizer._tokenizer.post_process = BertProcessing(
("", tokenizer.convert_tokens_to_ids("")),
("", tokenizer.convert_tokens_to_ids("")),
)
# Creating our Transformer
config = RobertaConfig(
vocab_size=52_000,
max_position_embeddings=512,
num_attention_heads=12,
num_hidden_layers=6,
type_vocab_size=1,
)
model = RobertaForMaskedLM(config=config)
model.num_parameters()
# Check if a GPU is available and, if not, use the CPU
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Move the model to the device
model = model.to(device)
print("Model is using : ", next(model.parameters()).device)
# Loading the dataset
dataset = load_dataset('text', data_files=training_data)
# Tokenizing the dataset
def tokenize_function(examples):
encodings = tokenizer(examples["text"], truncation=True, padding='max_length', max_length=512)
# Opening the file in write mode
with open('indices.txt', 'w') as f:
# Writing the indices to the file
f.write("input_ids: " + str(encodings['input_ids']) + "\n")
return {"input_ids": encodings['input_ids']}
tokenized_datasets = dataset.map(tokenize_function, batched=True, num_proc=8, remove_columns=["text"])
with open('results.txt', 'w') as f:
for batch in tokenized_datasets['train']:
input_ids = torch.tensor(batch['input_ids']).to(device) # Add .to(device) here
print("Inputs are using :", input_ids.device) # Now should print 'cuda' if a GPU is available
min_id = input_ids.min().item()
max_id = input_ids.max().item()
f.write(f'Minimum ID: {min_id}, Maximum ID: {max_id}\n')
data_collator = DataCollatorForLanguageModeling(
tokenizer=tokenizer, mlm=True, mlm_probability=0.1
)
output_dir = os.path.abspath('C:\\Users\\caiqu\\OneDrive\\Documentos\\IA\\raw_model')
training_args = TrainingArguments(
output_dir=output_dir,
overwrite_output_dir=True,
num_train_epochs=1200,
per_device_train_batch_size=64,
save_steps=10_000,
save_total_limit=2,
prediction_loss_only=True,
)
trainer = Trainer(
model=model,
args=training_args,
data_collator=data_collator,
train_dataset=tokenized_datasets['train'],
)
# Check if the output directory exists before starting the training
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# Enable mixed precision
trainer.train()
trainer.save_model('raw_model')
# Create a fill-mask pipeline with the model and the tokenizer
fill_mask = pipeline(
"fill-mask",
model='raw_model',
tokenizer='raw_model'
)
while True: # Infinite loop
question = input("You: ") # Ask a question to the user
if question.lower() == "exit": # If the question is "exit"
break # Exit the loop
response = fill_mask(question) # Generate a response to the question
print("AI: ", response) # Print the response
except Exception as e:
with open('error_log.txt', 'w') as f:
f.write(str(e))
f.write(traceback.format_exc())
if __name__ == '__main__':
main()
[b]Я встретил эту ошибку в функции потерь. Пример ниже:[/b] Мой код работал нормально, но что-то потерялось, не могу найти проблему. Пробовал обновлять библиотеки, тестировать предыдущие версии, проверял тензоры, индексы... Кто-нибудь может мне помочь, в конце страницы есть ссылка на мой репозиторий с файлами, которые я использовал. [b]Версия библиотеки:[/b] [code]Windows 11 GTX 1050 TI (Driver-Version==552.12) Python==3.12.3 transformers==4.39.3 tokenizers==0.15.2 torch==2.2.2+cu121 datasets==2.18.0 Cudatoolkit==12.1 CuDNN==8801
# Opening the file in write mode with open('indices.txt', 'w') as f: # Writing the indices to the file f.write("input_ids: " + str(encodings['input_ids']) + "\n")
with open('results.txt', 'w') as f: for batch in tokenized_datasets['train']: input_ids = torch.tensor(batch['input_ids']).to(device) # Add .to(device) here print("Inputs are using :", input_ids.device) # Now should print 'cuda' if a GPU is available min_id = input_ids.min().item() max_id = input_ids.max().item() f.write(f'Minimum ID: {min_id}, Maximum ID: {max_id}\n')
# Check if the output directory exists before starting the training if not os.path.exists(output_dir): os.makedirs(output_dir)
# Enable mixed precision trainer.train()
trainer.save_model('raw_model')
# Create a fill-mask pipeline with the model and the tokenizer fill_mask = pipeline( "fill-mask", model='raw_model', tokenizer='raw_model' )
while True: # Infinite loop question = input("You: ") # Ask a question to the user if question.lower() == "exit": # If the question is "exit" break # Exit the loop response = fill_mask(question) # Generate a response to the question print("AI: ", response) # Print the response
except Exception as e: with open('error_log.txt', 'w') as f: f.write(str(e)) f.write(traceback.format_exc())
if __name__ == '__main__': main() [/code] [b]Ошибка:[/b] [code]C:\Users\caiqu\AppData\Local\Programs\Python\Python312\Lib\site-packages\accelerate\accelerator.py:436: FutureWarning: Passing the following arguments to `Accelerator` is deprecated and will be removed in version 1.0 of Accelerate: dict_keys(['dispatch_batches', 'split_batches', 'even_batches', 'use_seedable_sampler']). Please pass an `accelerate.DataLoaderConfiguration` instead: dataloader_config = DataLoaderConfiguration(dispatch_batches=None, split_batches=False, even_batches=True, use_seedable_sampler=True)
C:\actions-runner\_work\pytorch\pytorch\builder\windows\pytorch\aten\src\ATen\native\cuda\Indexing.cu:1290: block: [42,0,0], thread: [124,0,0] Assertion `srcIndex < srcSelectDimSize` failed. C:\actions-runner\_work\pytorch\pytorch\builder\windows\pytorch\aten\src\ATen\native\cuda\Indexing.cu:1290: block: [42,0,0], thread: [125,0,0] Assertion `srcIndex < srcSelectDimSize` failed. C:\actions-runner\_work\pytorch\pytorch\builder\windows\pytorch\aten\src\ATen\native\cuda\Indexing.cu:1290: block: [42,0,0], thread: [126,0,0] Assertion `srcIndex < srcSelectDimSize` failed. C:\actions-runner\_work\pytorch\pytorch\builder\windows\pytorch\aten\src\ATen\native\cuda\Indexing.cu:1290: block: [42,0,0], thread: [127,0,0] Assertion `srcIndex < srcSelectDimSize` failed. Traceback (most recent call last): File "c:\Users\caiqu\OneDrive\Documentos\IA\treinar3.py", line 141, in main() File "c:\Users\caiqu\OneDrive\Documentos\IA\treinar3.py", line 122, in main trainer.train() File "C:\Users\caiqu\AppData\Local\Programs\Python\Python312\Lib\site-packages\transformers\trainer.py", line 1780, in train return inner_training_loop( ^^^^^^^^^^^^^^^^^^^^ File "C:\Users\caiqu\AppData\Local\Programs\Python\Python312\Lib\site-packages\transformers\trainer.py", line 2118, in _inner_training_loop tr_loss_step = self.training_step(model, inputs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\caiqu\AppData\Local\Programs\Python\Python312\Lib\site-packages\transformers\trainer.py", line 3036, in training_step loss = self.compute_loss(model, inputs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\caiqu\AppData\Local\Programs\Python\Python312\Lib\site-packages\transformers\trainer.py", line 3059, in compute_loss outputs = model(**inputs) ^^^^^^^^^^^^^^^ File "C:\Users\caiqu\AppData\Local\Programs\Python\Python312\Lib\site-packages\torch\nn\modules\module.py", line 1511, in _wrapped_call_impl return self._call_impl(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\caiqu\AppData\Local\Programs\Python\Python312\Lib\site-packages\torch\nn\modules\module.py", line 1520, in _call_impl return forward_call(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\caiqu\AppData\Local\Programs\Python\Python312\Lib\site-packages\transformers\models\roberta\modeling_roberta.py", line 1084, in forward outputs = self.roberta( ^^^^^^^^^^^^^ File "C:\Users\caiqu\AppData\Local\Programs\Python\Python312\Lib\site-packages\torch\nn\modules\module.py", line 1511, in _wrapped_call_impl return self._call_impl(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\caiqu\AppData\Local\Programs\Python\Python312\Lib\site-packages\torch\nn\modules\module.py", line 1520, in _call_impl return forward_call(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\caiqu\AppData\Local\Programs\Python\Python312\Lib\site-packages\transformers\models\roberta\modeling_roberta.py", line 828, in forward embedding_output = self.embeddings( ^^^^^^^^^^^^^^^^ File "C:\Users\caiqu\AppData\Local\Programs\Python\Python312\Lib\site-packages\torch\nn\modules\module.py", line 1511, in _wrapped_call_impl return self._call_impl(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\caiqu\AppData\Local\Programs\Python\Python312\Lib\site-packages\torch\nn\modules\module.py", line 1520, in _call_impl return forward_call(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\caiqu\AppData\Local\Programs\Python\Python312\Lib\site-packages\transformers\models\roberta\modeling_roberta.py", line 130, in forward position_embeddings = self.position_embeddings(position_ids) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\caiqu\AppData\Local\Programs\Python\Python312\Lib\site-packages\torch\nn\modules\module.py", line 1511, in _wrapped_call_impl return self._call_impl(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\caiqu\AppData\Local\Programs\Python\Python312\Lib\site-packages\torch\nn\modules\module.py", line 1520, in _call_impl return forward_call(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\caiqu\AppData\Local\Programs\Python\Python312\Lib\site-packages\torch\nn\modules\sparse.py", line 163, in forward return F.embedding( ^^^^^^^^^^^^ File "C:\Users\caiqu\AppData\Local\Programs\Python\Python312\Lib\site-packages\torch\nn\functional.py", line 2237, in embedding return torch.embedding(weight, input, padding_idx, scale_grad_by_freq, sparse) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ RuntimeError: CUDA error: device-side assert triggered Compile with `TORCH_USE_CUDA_DSA` to enable device-side assertions. [/code] [b]Репозитории Github:[/b] https://github.com/DonatoReis/bert-new
Я обучаю две модели в одной и той же среде, и одна из них работает нормально с одной и той же конфигурацией, но другая выдает ошибки без какой-либо дополнительной причины. Я также добавил CUDA_LAUNCH_BLOCKING=1, но проблема осталась прежней....
Я обучаю две модели в одной и той же среде, и одна из них работает нормально с одной и той же конфигурацией, но другая выдает ошибки без какой-либо дополнительной причины. Я также добавил CUDA_LAUNCH_BLOCKING=1, но проблема осталась прежней....
Работа над курсом Java MOOC. Почему while(end > Begin) не сработало, а while(begin под методомbinarySearch
Ссылка на мой код: нажмите здесь
Для моей первоначальной отправки while(end > Begin) не сработало (там проверяли ошибки при отправке), но...
Блокнот для моего кода находится по этой ссылке:
Так что проблема в том, что даже после нескольких проходов вперед код внезапно выходит из строя и выдает ошибку времени выполнения cuda. как показано ниже:
29 / 1363
forward passing
src_pad_idx: 1...
поэтому я пытаюсь реализовать функцию промежуточного программного обеспечения, которая проверяет достоверность идентификатора сеанса и вызывает next(), когда сеанс действителен. я создал функцию под названием checkSession() ,...