How to calculate loss over a sliding window of samples and then backpropagate the weighted average loss

I am trying to implement a learning technique from a paper. The relevant portion is: The SNN baseline used a sliding window of 50 consecutive data points, representing 200 ms of data (50-point window, single-point stride) in order to calculate the loss, to allow for more information for backpropagation and avoid dead neurons and vanishing gradients. The MSE loss was linearly weighted from 0 to 1 for the 50 points within the window. However, I am getting issues with the gradient calculation.

My attempt at implementing this is below: `

for epoch in range(100):
    net.train()
    
    best_loss = float('inf')
    patience_counter = 0
    best_state = torch.save(net.state_dict(), "cur_state.pth")
    
    loss_window = deque(maxlen=50)
    window_sum = 0.0
    
    for i, data in enumerate(train_set_loader):
        inputs, label = data
        optimizer.zero_grad()
        outputs, _ = net(inputs)
        
        loss = criterion(outputs, label)
        
        loss_window.append(loss)
        
        window_sum = window_sum + loss.item()

        # # If the window is full, calculate the weighted loss and perform backpropagation
        if len(loss_window) == 50:
            weighted_loss = sum(((j + 1) / 50) * loss_value for j, loss_value in  enumerate(loss_window))
       
            print(f'weighted_loss: {weighted_loss}, requires_grad: {weighted_loss.requires_grad}')
            
            weighted_loss.backward(retain_graph=True)
            #weighted_loss.backward()
            optimizer.step()
            
            #Print gradients for debugging
            for name, param in net.named_parameters():
                if param.grad is not None:
                    print(f'{name}: {param.grad.norm()}')
            
            
            # Update the window sum by subtracting the oldest loss
            window_sum -= loss_window[0].item()

            #Remove oldest loss element
            loss_window.popleft()
  
        


    net.eval()
    val_loss = evaluate_model(net, criterion, val_set_loader)
    
    
    if val_loss < best_loss:
        best_loss = val_loss
        best_state = torch.save(net.state_dict(), "cur_state.pth")
        patience_counter = 0
    else:
        patience_counter += 1
    
    if patience_counter >= patience:
        print("Early Stopping")
        print(f"Best loss: {best_loss}")
        device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
        net.load_state_dict(torch.load("cur_state.pth", map_location=device))
        print("Model state returned to best performing.")
        break

If I try without the retain_graph=True line in my backwards pass, I get the error that I’m trying to backward through the graph a second time. This makes sense as it is trying to backwards pass 49 of the same 50 gradients from the first call. When I do have retain_graph=True, I get the error: “one of the variables needed for gradient computation has been modified by an inplace operation: [torch.FloatTensor [50, 2]]”. I believe this is an issue with the updating of loss_window, but I am not sure how to go about changing this. My question is somewhat similar to how to calculate loss over a number of images and then back propagate the average loss and update network weight but in that question he doesn’t have overlap in his window which I believe avoids the problem.

New contributor

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

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