Why does my GPU memory keep increasing when I sweep over model parameters?

I am trying to evaluate model classification error rate with different dropout rates for a specific architecture. As I do so, memory usage increases, and I am not able to stop this from happening (see code below for details):

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>N=2048 split 0 memory usage
{'current': 170630912, 'peak': 315827456}
{'current': 345847552, 'peak': 430210560}
{'current': 530811136, 'peak': 610477568}
...
{'current': 1795582208, 'peak': 1873805056}
N=2048 split 1 memory usage
{'current': 1978317568, 'peak': 2056609280}
{'current': 2157136640, 'peak': 2235356160}
...
2024-12-15 18:55:04.141690: W external/local_xla/xla/tsl/framework/bfc_allocator.cc:497] Allocator (GPU_0_bfc) ran out of memory trying to allocate 52.00MiB (rounded to 54531328)requested by op
...
2024-12-15 18:55:04.144298: I tensorflow/core/framework/local_rendezvous.cc:405] Local rendezvous is aborting with status: RESOURCE_EXHAUSTED: Out of memory while trying to allocate 54531208 bytes.
...
</code>
<code>N=2048 split 0 memory usage {'current': 170630912, 'peak': 315827456} {'current': 345847552, 'peak': 430210560} {'current': 530811136, 'peak': 610477568} ... {'current': 1795582208, 'peak': 1873805056} N=2048 split 1 memory usage {'current': 1978317568, 'peak': 2056609280} {'current': 2157136640, 'peak': 2235356160} ... 2024-12-15 18:55:04.141690: W external/local_xla/xla/tsl/framework/bfc_allocator.cc:497] Allocator (GPU_0_bfc) ran out of memory trying to allocate 52.00MiB (rounded to 54531328)requested by op ... 2024-12-15 18:55:04.144298: I tensorflow/core/framework/local_rendezvous.cc:405] Local rendezvous is aborting with status: RESOURCE_EXHAUSTED: Out of memory while trying to allocate 54531208 bytes. ... </code>
N=2048 split 0 memory usage
{'current': 170630912, 'peak': 315827456}
{'current': 345847552, 'peak': 430210560}
{'current': 530811136, 'peak': 610477568}
...
{'current': 1795582208, 'peak': 1873805056}
N=2048 split 1 memory usage
{'current': 1978317568, 'peak': 2056609280}
{'current': 2157136640, 'peak': 2235356160}
...
2024-12-15 18:55:04.141690: W external/local_xla/xla/tsl/framework/bfc_allocator.cc:497] Allocator (GPU_0_bfc) ran out of memory trying to allocate 52.00MiB (rounded to 54531328)requested by op 
...
2024-12-15 18:55:04.144298: I tensorflow/core/framework/local_rendezvous.cc:405] Local rendezvous is aborting with status: RESOURCE_EXHAUSTED: Out of memory while trying to allocate 54531208 bytes.
...

This is the relevant part of the code that I am running, including some unsuccessful attempts to clear the memory after each iteration.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import tensorflow as tf
import tensorflow_datasets as tfds
import gc
batch_size = 128
sizes = [2048 + n * batch_size * 5 for n in range(10)]
dropout_points = 10
vals_ds = tfds.load(
'mnist',
split=[f'train[{k}%:{k+10}%]' for k in range(0, 100, 10)],
as_supervised=True,
)
trains_ds = tfds.load(
'mnist',
split=[f'train[:{k}%]+train[{k+10}%:]' for k in range(0, 100, 10)],
as_supervised=True,
)
_, ds_info = tfds.load('mnist', with_info=True)
def normalize_img(image, label):
return tf.cast(image, tf.float32) / 255., label
for N in sizes:
for i, (ds_train, ds_test) in enumerate(zip(trains_ds, vals_ds)):
ds_train = ds_train.map(normalize_img, num_parallel_calls=tf.data.AUTOTUNE)
ds_train = ds_train.shuffle(ds_info.splits['train'].num_examples)
ds_train = ds_train.batch(128)
ds_test = ds_test.map(normalize_img, num_parallel_calls=tf.data.AUTOTUNE)
ds_test = ds_test.batch(128)
print(f"N={N} split {i} memory usage")
with open(f"out_{N}_{i}.csv", "w") as f:
f.write(("retention_rate,"
"train_loss,"
"train_err,"
"test_loss,"
"test_err,"
"epochsn"))
for p in range(dropout_points):
dropout_rate = p / dropout_points
layers = [tf.keras.layers.Flatten(input_shape=(28, 28))]
for i in range(4):
layers.append(tf.keras.layers.Dense(N, activation='relu'))
layers.append(tf.keras.layers.Dropout(dropout_rate))
layers.append(tf.keras.layers.Dense(10))
with tf.device('/GPU:0'):
model = tf.keras.models.Sequential(layers)
model.compile(
optimizer=tf.keras.optimizers.Adam(0.001),
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=[tf.keras.metrics.SparseCategoricalAccuracy()],
)
callback = tf.keras.callbacks.EarlyStopping(monitor='loss', patience=3)
history = model.fit(
ds_train,
epochs=100,
validation_data=ds_test,
verbose=0,
callbacks=[callback]
)
train_loss, train_acc = model.evaluate(ds_train, verbose=0)
test_loss, test_acc = model.evaluate(ds_test, verbose=0)
epochs = len(history.history['loss'])
f.write((
f"{1 - dropout_rate},"
f"{train_loss},"
f"{1 - train_acc},"
f"{test_loss},"
f"{1 - test_acc},"
f"{epochs}n"))
del model
tf.keras.backend.clear_session()
gc.collect()
print(tf.config.experimental.get_memory_info('GPU:0'))
</code>
<code>import tensorflow as tf import tensorflow_datasets as tfds import gc batch_size = 128 sizes = [2048 + n * batch_size * 5 for n in range(10)] dropout_points = 10 vals_ds = tfds.load( 'mnist', split=[f'train[{k}%:{k+10}%]' for k in range(0, 100, 10)], as_supervised=True, ) trains_ds = tfds.load( 'mnist', split=[f'train[:{k}%]+train[{k+10}%:]' for k in range(0, 100, 10)], as_supervised=True, ) _, ds_info = tfds.load('mnist', with_info=True) def normalize_img(image, label): return tf.cast(image, tf.float32) / 255., label for N in sizes: for i, (ds_train, ds_test) in enumerate(zip(trains_ds, vals_ds)): ds_train = ds_train.map(normalize_img, num_parallel_calls=tf.data.AUTOTUNE) ds_train = ds_train.shuffle(ds_info.splits['train'].num_examples) ds_train = ds_train.batch(128) ds_test = ds_test.map(normalize_img, num_parallel_calls=tf.data.AUTOTUNE) ds_test = ds_test.batch(128) print(f"N={N} split {i} memory usage") with open(f"out_{N}_{i}.csv", "w") as f: f.write(("retention_rate," "train_loss," "train_err," "test_loss," "test_err," "epochsn")) for p in range(dropout_points): dropout_rate = p / dropout_points layers = [tf.keras.layers.Flatten(input_shape=(28, 28))] for i in range(4): layers.append(tf.keras.layers.Dense(N, activation='relu')) layers.append(tf.keras.layers.Dropout(dropout_rate)) layers.append(tf.keras.layers.Dense(10)) with tf.device('/GPU:0'): model = tf.keras.models.Sequential(layers) model.compile( optimizer=tf.keras.optimizers.Adam(0.001), loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=[tf.keras.metrics.SparseCategoricalAccuracy()], ) callback = tf.keras.callbacks.EarlyStopping(monitor='loss', patience=3) history = model.fit( ds_train, epochs=100, validation_data=ds_test, verbose=0, callbacks=[callback] ) train_loss, train_acc = model.evaluate(ds_train, verbose=0) test_loss, test_acc = model.evaluate(ds_test, verbose=0) epochs = len(history.history['loss']) f.write(( f"{1 - dropout_rate}," f"{train_loss}," f"{1 - train_acc}," f"{test_loss}," f"{1 - test_acc}," f"{epochs}n")) del model tf.keras.backend.clear_session() gc.collect() print(tf.config.experimental.get_memory_info('GPU:0')) </code>
import tensorflow as tf
import tensorflow_datasets as tfds
import gc

batch_size = 128
sizes = [2048 + n * batch_size * 5 for n in range(10)]
dropout_points = 10

vals_ds = tfds.load(
    'mnist',
    split=[f'train[{k}%:{k+10}%]' for k in range(0, 100, 10)],
    as_supervised=True,
)
trains_ds = tfds.load(
    'mnist',
    split=[f'train[:{k}%]+train[{k+10}%:]' for k in range(0, 100, 10)],
    as_supervised=True,
)
_, ds_info = tfds.load('mnist', with_info=True)


def normalize_img(image, label):
    return tf.cast(image, tf.float32) / 255., label


for N in sizes:
    for i, (ds_train, ds_test) in enumerate(zip(trains_ds, vals_ds)):
        ds_train = ds_train.map(normalize_img, num_parallel_calls=tf.data.AUTOTUNE)
        ds_train = ds_train.shuffle(ds_info.splits['train'].num_examples)
        ds_train = ds_train.batch(128)

        ds_test = ds_test.map(normalize_img, num_parallel_calls=tf.data.AUTOTUNE)
        ds_test = ds_test.batch(128)

        print(f"N={N} split {i} memory usage")
        with open(f"out_{N}_{i}.csv", "w") as f:
            f.write(("retention_rate,"
                     "train_loss,"
                     "train_err,"
                     "test_loss,"
                     "test_err,"
                     "epochsn"))
            for p in range(dropout_points):
                dropout_rate = p / dropout_points

                layers = [tf.keras.layers.Flatten(input_shape=(28, 28))]
                for i in range(4):
                    layers.append(tf.keras.layers.Dense(N, activation='relu'))
                    layers.append(tf.keras.layers.Dropout(dropout_rate))
                layers.append(tf.keras.layers.Dense(10))

                with tf.device('/GPU:0'):
                    model = tf.keras.models.Sequential(layers)
                    model.compile(
                        optimizer=tf.keras.optimizers.Adam(0.001),
                        loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
                        metrics=[tf.keras.metrics.SparseCategoricalAccuracy()],
                    )

                    callback = tf.keras.callbacks.EarlyStopping(monitor='loss', patience=3)
                    history = model.fit(
                        ds_train,
                        epochs=100,
                        validation_data=ds_test,
                        verbose=0,
                        callbacks=[callback]
                    )

                    train_loss, train_acc = model.evaluate(ds_train, verbose=0)
                    test_loss, test_acc = model.evaluate(ds_test, verbose=0)
                    epochs = len(history.history['loss'])
                f.write((
                    f"{1 - dropout_rate},"
                    f"{train_loss},"
                    f"{1 - train_acc},"
                    f"{test_loss},"
                    f"{1 - test_acc},"
                    f"{epochs}n"))
                del model
                tf.keras.backend.clear_session()
                gc.collect()
                print(tf.config.experimental.get_memory_info('GPU:0'))

How can I perform this loop effectively without my memory usage growing?

New contributor

Gaston Barboza is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật