В основном есть две части к вопросу, первая часть заключается в том, что, выводя вывод на модели и сохраняя минимальные результаты, приложение Python занимает около 3 ГБ памяти в моей системе (у меня жестко кодированное устройство = 'ЦП'), Это неожиданно, так как модель представляет собой модель Vit-MSN-базы с 12 слоями и размером около 160 МБ, мой размер партии составляет 1 .. Также, даже при использовании gc.collect (), кажется, что использование памяти просто продолжает увеличивать < /p>
Вторая часть заключается в том, что использование памяти приводит к примерно 10 ГБ, когда я использую Device = 'cuda', это было действительно неожиданно, на некотором поиске, похоже, результаты обработки памяти Pytorch В обширной фрагментации, но я не уверен в том, как справиться с этим < /p>
Вот соответствующие фрагменты кода -< /p>
model_name = 'facebook/vit-msn-base-4'
layers = 1
< /code>
cka_score_list = []
tokenizer = AutoImageProcessor.from_pretrained(
model_name,
use_fast=True, # Use the fast tokenizer implementation
trust_remote_code=True, # Trust remote code (required for some models)
add_bos_token=False, # Do not add beginning-of-sequence token
add_eos_token=False, # Do not add end-of-sequence token
padding_side="left" # Pad sequences on the left side
)
# Load the pre-trained causal language model with appropriate settings
model = AutoModel.from_pretrained(
model_name,
trust_remote_code=True, # Trust remote code (required for some models)
device_map="auto", # Automatically map layers to available devices
torch_dtype=torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float32, # Use bfloat16 if supported
)
print(dir(model))
model.eval()
model = model.to(device)
cur_score = eval_meth(classA, classB, num_images)
cka_score_list.append(cur_score)
< /code>
def latent_embeddings_for_class(classA, num_images):
cur_csv = os.path.join(val_csv , (classA+ '.csv'))
df = pd.read_csv(cur_csv, header = None)
embeddings = []
for i in range(num_images):
image_name = df.iloc[random.randint(1, 50), 0]
image_path = os.path.join(val_images, image_name)
image =Image.open(image_path)
inputs = tokenizer(image, return_tensors="pt").to(device).to(torch.bfloat16)
print(inputs['pixel_values'].shape)
snapshot = tracemalloc.take_snapshot()
# Print top memory-consuming lines
top_stats = snapshot.statistics('lineno')
for stat in top_stats[:3]:
print(stat)
output = model(**inputs)
embeddings.append(output.last_hidden_state[0,1])
del inputs
del image
del output
clear_memory()
print(embeddings[0].shape)
embeddings = torch.stack(embeddings)
return embeddings
def eval_meth(classA, classB, num_images ):
X= latent_embeddings_for_class( classA, num_images)
Y= latent_embeddings_for_class( classB, num_images)
cka_score = cka(X,Y)
clear_memory()
return cka_score
< /code>
also, on CPU, this is the output -
torch.Size([1, 3, 224, 224])
:647: size=3355 KiB, count=19535, average=176 B
c:\Users\hp\miniconda3\envs\mka_research\lib\ast.py:50: size=661 KiB, count=11348, average=60 B
c:\Users\hp\miniconda3\envs\mka_research\lib\selectors.py:315: size=288 KiB, count=6, average=48.0 KiB
torch.Size([768])
torch.Size([1, 3, 224, 224])
:647: size=3355 KiB, count=19535, average=176 B
c:\Users\hp\miniconda3\envs\mka_research\lib\ast.py:50: size=661 KiB, count=11348, average=60 B
c:\Users\hp\miniconda3\envs\mka_research\lib\tracemalloc.py:505: size=537 KiB, count=9815, average=56 B
torch.Size([768])
torch.Size([1, 3, 224, 224])
:647: size=3355 KiB, count=19535, average=176 B
c:\Users\hp\miniconda3\envs\mka_research\lib\ast.py:50: size=661 KiB, count=11348, average=60 B
c:\Users\hp\miniconda3\envs\mka_research\lib\tracemalloc.py:505: size=533 KiB, count=9732, average=56 B
torch.Size([768])
< /code>
on GPU it shows -
CUDA out of memory. Tried to allocate 452.00 MiB. GPU 0 has a total capacity of 4.00 GiB of which 0 bytes is free. Of the allocated memory 10.17 GiB is allocated by PyTorch, and 144.56 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/c ... -variables)
< /code>
this is weird as this does not reflect the memory usage shown in task manager
Подробнее здесь: https://stackoverflow.com/questions/793 ... -msn-model
Аномальное использование памяти CUDA и CPU с трансформаторами guggingface transformers vit-msn ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Невозможно подавить предупреждение из Transformers/src/transformers/modeling_utils.py.
Anonymous » » в форуме Python - 0 Ответы
- 29 Просмотры
-
Последнее сообщение Anonymous
-