Python没有在for循环中释放内存

爱德华多

我正在研究对大输入数据进行一些处理的功能。但是,由于我无法一次将所有数据放入内存中(点积为117703x200000矩阵),因此我将其分为多个块并按部分进行计算。

输出仅采用前5个元素(排序后),因此输出的形状必须为117703x5,可以保存在存储器中。但是,由于某种原因,随着循环的进行,我的内存消耗一直在增加,直到出现内存错误为止。有什么想法吗?这是代码:

def process_predictions_proto(frac=50):
    # Simulate some inputs
    query_embeddings = np.random.random((117703, 512))
    proto_feat = np.random.random((200000, 512))
    gal_cls = np.arange(200000)

    N_val = query_embeddings.shape[0]
    pred = []

    for i in tqdm(range(frac)):
        start = i * int(np.ceil(N_val / frac))
        stop = (i + 1) * int(np.ceil(N_val / frac))
        val_i = query_embeddings[start:stop, :]
        # Compute distances
        dist_i = np.dot(val_i, proto_feat.transpose())
        # Sort
        index_i = np.argsort(dist_i, axis=1)[::-1]
        dist_i = np.take_along_axis(dist_i, index_i, axis=1)
        # Convert distances to class_ids
        pred_i = np.take_along_axis(
            np.repeat(gal_cls[np.newaxis, :], index_i.shape[0], axis=0),
            index_i, axis=1)
        # Use pd.unique to remove copies of the same class_id and
        # get 5 most similar ids
        pred_i = [pd.unique(pi)[:5] for pi in pred_i]
        # Append to list
        pred.append(pred_i)
        # Free memory
        gc.collect()
    pred = np.stack(pred, 0)  # N_val x 5
    return pred
巴尔玛

在调用之前删除所有临时变量gc.collect(),以使数据立即变为垃圾。

del start, stop, val_i, dist_i, index_i, dist_i, pred_i
gc.collect()

在您的代码中,gc.collect()第一次调用时,所有数据都不是垃圾数据,因为仍然可以从所有变量中引用它们。直到第二次迭代结束,才会收集第一次迭代的数据。在第一次迭代之后的每次迭代中,您将在内存中拥有两个数据块(当前迭代和上一个迭代)。因此,您使用的内存是所需的两倍(我假设某些对象之间存在引用,因此自动GC不会清理对象,因为在循环期间会重新分配变量)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章