reduce_memory 减少内存

数据太大爆掉内存? 可以使用下面方法至少减少一般内存,来源kaggle中能源比赛
https://www.kaggle.com/roydatascience/ashrae-leak-validation-heuristics-stable

在这里插入代码片# Original code from https://www.kaggle.com/gemartin/load-data-reduce-memory-usage by @gemartin
# Modified to support timestamp type, categorical type
# Modified to add option to use float16 or not. feather format does not support float16.
from pandas.api.types import is_datetime64_any_dtype as is_datetime
from pandas.api.types import is_categorical_dtype

def reduce_mem_usage(df, use_float16=False):
    """ iterate through all the columns of a dataframe and modify the data type
        to reduce memory usage.        
    """
    start_mem = df.memory_usage().sum() / 1024**2
    print('Memory usage of dataframe is {:.2f} MB'.format(start_mem))
    
    for col in df.columns:
        if is_datetime(df[col]) or is_categorical_dtype(df[col]):
            # skip datetime type or categorical type
            continue
        col_type = df[col].dtype
        
        if col_type != object:
            c_min = df[col].min()
            c_max = df[col].max()
            if str(col_type)[:3] == 'int':
                if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:
                    df[col] = df[col].astype(np.int8)
                elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:
                    df[col] = df[col].astype(np.int16)
                elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:
                    df[col] = df[col].astype(np.int32)
                elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:
                    df[col] = df[col].astype(np.int64)  
            else:
                if use_float16 and c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:
                    df[col] = df[col].astype(np.float16)
                elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:
                    df[col] = df[col].astype(np.float32)
                else:
                    df[col] = df[col].astype(np.float64)
        else:
            df[col] = df[col].astype('category')

    end_mem = df.memory_usage().sum() / 1024**2
    print('Memory usage after optimization is: {:.2f} MB'.format(end_mem))
    print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) / start_mem))
    return df
深度学习训练过程中,`DistributedDataParallel`(DDP)是常用的分布式训练工具,它可以在多个GPU上并行训练模型。然而,DDP在某些情况下可能会增加内存使用量,特别是在小批量(batch size)训练时。为了减少内存使用量,可以考虑以下几种方法: 1. **使用`DataParallel`代替`DistributedDataParallel`**:`DataParallel`是另一种数据并行工具,它在单台机器上使用多个GPU进行并行计算。相比DDP,`DataParallel`的实现更简单,内存开销也更小。 2. **减少模型参数量**:通过减少模型的层数或每层的神经元数量,可以有效减少内存使用量。 3. **使用混合精度训练**:混合精度训练可以在保持模型精度的情况下减少内存使用量。常用的方法是使用`torch.cuda.amp`进行自动混合精度训练。 4. **梯度累积**:通过累积多个小批量数据的梯度再进行一次反向传播更新模型参数,可以减少内存使用量。常用的方法是使用`torch.utils.data.DataLoader`的`accumulate_grad_batches`参数。 5. **优化数据结构**:使用更节省内存的数据结构,如`torch.utils.checkpoint`可以在反向传播时重新计算中间结果,而不是存储它们。 以下是使用`DataParallel`代替`DistributedDataParallel`的一个简单示例: ```python import torch import torch.nn as nn from torch.nn.parallel import DataParallel # 假设我们有一个简单的模型 class SimpleModel(nn.Module): def __init__(self): super(SimpleModel, self).__init__() self.layer = nn.Linear(10, 10) def forward(self, x): return self.layer(x) # 初始化模型 model = SimpleModel() # 使用DataParallel进行并行计算 model = DataParallel(model) # 假设我们有一个输入张量 input_tensor = torch.randn(64, 10) # 前向传播 output = model(input_tensor) # 反向传播 output.mean().backward() ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值